### Build Demo Page for fhirpath.js
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Installs dependencies, builds the demo page, and starts a local development server. Open your browser to localhost:8080.
```sh
npm install && npm run build
cd demo
npm install && npm run build && npm run start
```
--------------------------------
### Install Dependencies
Source: https://github.com/hl7/fhirpath.js/blob/master/converter/README.md
Use this command to install project dependencies.
```npm
npm ci
```
--------------------------------
### Install fhirpath for Node.js
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use npm to install the fhirpath package for server-side Node.js applications. This command installs the package and saves it as a dependency in your package.json file.
```sh
npm install --save fhirpath
```
--------------------------------
### FHIRPath Evaluation with Environment Variables
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Shows how to pass environment variables to the evaluate function, useful for dynamic expressions. The example subtracts 1 from a variable 'a'.
```javascript
fhirpath.evaluate({}, '%a - 1', {a: 5});
```
--------------------------------
### Basic FHIRPath Evaluation
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
A simple example demonstrating how to evaluate a FHIRPath expression on a Patient resource to retrieve the given names.
```javascript
fhirpath.evaluate({"resourceType": "Patient", ...}, 'Patient.name.given');
```
--------------------------------
### Define Custom Power Function
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Example of defining a custom 'pow' function for raising numbers to a power, with a default exponent of 2. Requires the 'userInvocationTable' option.
```javascript
const userInvocationTable = {
pow: {fn: (inputs,exp=2)=>inputs.map(i => Math.pow(i, exp)), arity: {0: [], 1: ["Integer"]}},
};
const res = fhirpath.evaluate({"a": [5,6,7]}, "a.pow()", null, null, { userInvocationTable });
```
--------------------------------
### Browser usage with pre-loaded FHIR model
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Example of using fhirpath.js in a browser environment after loading the main library and a specific FHIR model (e.g., R4). Assumes global availability of fhirpath and the model.
```javascript
// Browser (global variable after loading fhirpath.r4.min.js)
//
//
// fhirpath.evaluate(resource, 'Patient.name.given', null, fhirpath_r4_model);
```
--------------------------------
### CLI: Evaluate FHIRPath expression against a JSON file
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Uses the `fhirpath` command-line tool to evaluate a FHIRPath expression against a specified JSON resource file. Installs via npm.
```bash
# Install
npm install -g fhirpath
# Evaluate a path expression against a JSON resource file
fhirpath --expression 'Patient.name.given' --resourceFile pt.json
```
--------------------------------
### Evaluate FHIRPath with Precise Math
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use the `preciseMath: true` option in `fhirpath.evaluate` for accurate decimal arithmetic, essential for clinical calculations. This example demonstrates adding decimals and ensuring the unit is preserved.
```javascript
fhirpath.evaluate(
{
"resourceType": "Observation",
"valueQuantity": {
"value": 0.1,
"system": "http://unitsofmeasure.org",
"code": "kg"
}
},
'Observation.value + 0.2 \'kg\'',
null,
fhirpath_r4_model,
{ preciseMath: true } // Returns 0.3 'kg' instead of 0.30000000000000004 'kg'
);
```
--------------------------------
### FHIRPath Evaluation with FHIR Model Data
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Demonstrates including FHIR model data, such as R4, to support choice types during evaluation. This example retrieves the value from an Observation resource.
```javascript
fhirpath.evaluate({"resourceType": "Observation", "valueString": "green"},
'Observation.value', null, fhirpath_r4_model);
```
--------------------------------
### Define Asynchronous Identity Function
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Example of defining an asynchronous 'asyncIdentity' function that returns a promise. It checks for async evaluation allowance and requires the 'async: true' option.
```javascript
const userInvocationTable = {
asyncIdentity: {
fn: function(inputs) {
fhirpath.util.checkAllowAsync(this, 'asyncIdentity');
return Promise.resolve(inputs);
},
arity: {0: []}
}
};
// Throws without { async: true }.
const resultPromise = fhirpath.evaluate(
{ value: [3, 2, 1] },
"value.sort(asyncIdentity())",
{},
null,
{ async: true, userInvocationTable }
);
```
--------------------------------
### Get full element path with indices
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Retrieves the full path of each node within the input collection, including array indices. Requires the fhirpath library and a FHIR context model.
```javascript
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
const patient = {
resourceType: 'Patient',
name: [{ family: 'Doe', given: ['John'] }],
id: 'pt1'
};
// Full path with indices
fhirpath.evaluate(patient, 'Patient.name.given.pathname()', r4_model);
```
--------------------------------
### Cancel Asynchronous FHIRPath Evaluation with AbortSignal
Source: https://context7.com/hl7/fhirpath.js/llms.txt
When using async evaluation, an `AbortSignal` can be passed via the `signal` option on the function returned by `compile` or directly to `evaluate`. If the signal is already aborted before evaluation starts, an error is thrown immediately.
```javascript
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
const evalExpr = fhirpath.compile(
"Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))",
r4_model,
{ async: true }
);
const controller = new AbortController();
const promise = evalExpr(resource, {}, { signal: controller.signal });
// Cancel the ongoing async evaluation
controller.abort();
try {
await promise;
} catch (err) {
err.name; // 'AbortError'
}
```
--------------------------------
### Print FHIRPath Abstract Syntax Tree (AST)
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
If only a FHIRPath expression is provided without resource input, the CLI will output the parsed Abstract Syntax Tree (AST) in YAML format.
```sh
fhirpath --expression 'Patient.name.given'
```
--------------------------------
### Get Types of FHIRPath Evaluation Result
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use the 'types' function to get an array of strings representing the FHIR data types of elements in a FHIRPath evaluation result, provided internal types were not resolved.
```javascript
const res = fhirpath.types(
fhirpath.evaluate(resource, expression, envVars, model, {resolveInternalTypes: false})
);
```
--------------------------------
### Download and Convert Test Files
Source: https://github.com/hl7/fhirpath.js/blob/master/converter/README.md
Execute the converter script to download and convert FHIRPath XML test cases and resource files.
```bash
converter/bin/index.js
```
--------------------------------
### Terminology Server Integration (Async)
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Connect to a terminology server for value set lookups using `--terminologyUrl`. This operation is asynchronous and supports `AbortSignal` for long-running operations.
```bash
fhirpath --expression "Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))" \
--resourceFile observation.json \
--model r4 \
--terminologyUrl https://lforms-nlm.nih.gov/baseR4
```
--------------------------------
### Getting FHIRPath Result Types
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Retrieves the internal data types of elements within a FHIRPath evaluation result when internal types are preserved.
```APIDOC
## Getting FHIRPath Result Types
### Description
Returns an array of strings representing the internal data types of each element in a FHIRPath evaluation result, provided `resolveInternalTypes` was set to `false` during evaluation.
### Method
`fhirpath.types(evaluatedResult)`
### Parameters
- **evaluatedResult**: The result array from `fhirpath.evaluate()` where internal types were preserved.
### Request Example
```js
const res = fhirpath.types(
fhirpath.evaluate(resource, expression, envVars, model, {resolveInternalTypes: false})
);
// Example result: ['FHIR.dateTime', 'FHIR.string', ...]
```
```
--------------------------------
### Run Converter Tests
Source: https://github.com/hl7/fhirpath.js/blob/master/converter/README.md
Execute the entire test scope for the converter using this npm script.
```npm
npm run test
```
--------------------------------
### Execute FHIRPath Expression with Native Math Mode
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Utilize native floating-point arithmetic for faster computations by setting --mathMode to 'native'. Be aware of potential precision issues.
```sh
# Using native math (faster but with floating-point precision issues)
fhirpath --expression '0.1 + 0.2' --resourceJSON '{}' --mathMode native
```
--------------------------------
### Execute FHIRPath Expression on Local File
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use the CLI to evaluate a FHIRPath expression against a local JSON file containing a FHIR resource. Ensure the resource file is downloaded first.
```sh
curl http://www.hl7.org/fhir/patient-example-a.json > pt.json
fhirpath --expression 'Patient.name.given' --resourceFile pt.json
```
--------------------------------
### Precompile FHIRPath for Resource Parts
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
When using precompiled paths with resource parts not obtained via fhirpath.js, specify the 'base' and 'expression' for the partial resource context.
```javascript
const path = fhirpath.compile({ "base": "QuestionnaireResponse.item",
"expression": "answer.value = 2 year"},
fhirpath_r4_model);
let res = path({ "answer": { "valueQuantity": ...}, {a: 5, ...});
```
--------------------------------
### Get short element path without indices
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Retrieves a shorter form of the element path, omitting array indices. Useful for simplifying path representations. Requires the fhirpath library and a FHIR context model.
```javascript
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
const patient = {
resourceType: 'Patient',
name: [{ family: 'Doe', given: ['John'] }],
id: 'pt1'
};
// Short path without indices
fhirpath.evaluate(patient, 'Patient.name.given.pathname(true)', r4_model);
```
--------------------------------
### Retrieve FHIR Types of Evaluation Results
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Get an array of type strings (e.g., `'FHIR.dateTime'`, `'System.String'`) for each element in an evaluation result. This is useful when `{ resolveInternalTypes: false }` was used and you need to know the specific FHIR primitive or complex type without resolving the values. The `type()` function in FHIRPath expressions can also be used to achieve similar results.
```javascript
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
const observationResource = require('./test/resources/r4/observation-example.json');
// Get types of System primitives
const systemValues = fhirpath.evaluate(
{},
"true.combine(1).combine(2.5).combine('abc')",
{},
null,
{ resolveInternalTypes: false }
);
fhirpath.types(systemValues);
// => ['System.Boolean', 'System.Integer', 'System.Decimal', 'System.String']
// Get types of FHIR resource fields
const fhirValues = fhirpath.evaluate(
observationResource,
'Observation.status.combine(Observation.effectiveDateTime).combine(Observation.valueQuantity.value)',
{},
r4_model,
{ resolveInternalTypes: false }
);
fhirpath.types(fhirValues);
// => ['FHIR.code', 'FHIR.dateTime', 'FHIR.decimal']
// Also available via type() in FHIRPath expressions
fhirpath.evaluate(
fhirValues,
'%context.type().name',
{},
r4_model
);
// => ['code', 'dateTime', 'decimal']
```
--------------------------------
### FHIRPath Evaluation with Partial Resource Context
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use this when the first parameter is a resource part obtained without fhirpath.js. The expression is relative to the specified 'base' path.
```javascript
fhirpath.evaluate({ "answer": { "valueQuantity": ...}},
{ "base": "QuestionnaireResponse.item",
"expression": "answer.value = 2 year"},
null, fhirpath_r4_model);
```
--------------------------------
### Execute FHIRPath Expression with Precise Math Mode
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use precise decimal arithmetic for calculations by setting --mathMode to 'precise'. This ensures accuracy for financial or critical calculations.
```sh
# Using precise math (accurate decimal arithmetic)
fhirpath --expression '0.1 + 0.2' --resourceJSON '{}' --mathMode precise
```
--------------------------------
### Create FHIR Module Version Folder
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Creates a new directory to store the FHIR module for a specific version.
```sh
> mkdir r6
```
--------------------------------
### Enable Asynchronous FHIRPath Functions
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Pass `{ async: true }` to `evaluate` or `compile` to enable asynchronous functions like `memberOf`. This returns a Promise only for expressions containing such functions. Ensure `terminologyUrl` is provided when using `memberOf`.
```javascript
fhirpath.evaluate(
resource,
"Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))",
{},
model,
{ async: true, terminologyUrl: 'https://lforms-fhir.nlm.nih.gov/baseR4' }
)
```
--------------------------------
### CLI: Inline JSON resource evaluation
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Evaluates a FHIRPath expression using an inline JSON resource provided directly on the command line. Supports basic arithmetic operations.
```bash
# Inline JSON resource
fhirpath --expression 'a.b + 2' --resourceJSON '{"a": {"b": 1}}'
```
--------------------------------
### Download FHIR StructureDefinitions
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Fetches the necessary FHIR StructureDefinition JSON files for updating the FHIR module. These files should be placed in the `fhir-context` directory and are not checked into version control.
```sh
> wget 'http://hl7.org/fhir/6.0.0-ballot3/profiles-types.json' -O profiles-types.json
> wget 'http://hl7.org/fhir/6.0.0-ballot3/profiles-others.json' -O profiles-others.json
> wget 'http://hl7.org/fhir/6.0.0-ballot3/profiles-resources.json' -O profiles-resources.json
> wget 'https://hl7.org/fhir/6.0.0-ballot3/search-parameters.json' -O search-parameters.json
```
--------------------------------
### Copy Index File for FHIR Module
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Copies the `index.js` file from a previous release (e.g., `r5`) into the new version's directory (e.g., `r6`).
```sh
> cp ../r5/index.js r6
```
--------------------------------
### Capture Trace Output during Evaluation
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Include a 'traceFn' in the options object to capture and log evaluations performed by the 'trace' method during expression evaluation.
```javascript
let tracefunction = function (x, label) {
console.log("Trace output [" + label + "]: ", x);
};
const res = fhirpath.evaluate(contextNode, path, envVars, fhirpath_r4_model, { traceFn: tracefunction });
```
--------------------------------
### Run Polyfill Tests in IE11
Source: https://github.com/hl7/fhirpath.js/blob/master/browser-build/test/index.html
Executes a series of JavaScript expressions to test polyfill functionality, primarily for IE11 compatibility. Results are displayed as 'ok' or 'fail' list items, indicating whether each expression evaluated to true.
```javascript
document.querySelector('#tests').innerHTML = [
'Number.isInteger(1)',
'!Number.isInteger(1.1)',
'!Number.isInteger("1")',
'"Some text".startsWith("Some")',
'!"Some Text".startsWith("some")',
'"Some text".endsWith("text")',
'!"Some Text".endsWith("text")',
'"Some text again".includes("text")',
'"Some text again".includes("text", 5)',
'!"Some text again".includes("text", 6)',
'Object.assign({}, {a:1}).a === 1',
'Object.assign("123", {a:1}).a === 1',
'Object.assign("123", {a:1})[1] === "2"',
"fhirpath.evaluate({}, \"'first.\\nsecond'.matches('\\..s')\")[0] === true",
"fhirpath.evaluate({}, \"'first. second'.matches('\\..*s')\")[0] === true",
"fhirpath.evaluate({}, \"'first[\\n]'.matches('t\\\\\\\\.s')\")[0] === true",
"fhirpath.evaluate({}, \"'first. '.matches('t[. ]')\")[0] === true",
"fhirpath.evaluate({}, \"'first\\n'.matches('t[. ]')\")[0] === false",
"fhirpath.evaluate({}, \"'first\\\\.second '.matches('t\\\\\\\\.s')\")[0] === true",
"fhirpath.evaluate({}, \"'first\\\\\\nsecond'.matches('t\\\\\\\\.s')\")[0] === false",
"fhirpath.evaluate({}, \"'first\\nsecond'.matches('t.s')\")[0] === true",
"fhirpath.evaluate({}, \"'first\\nsecond'.matches('t[. ]s')\")[0] === false"
].map(function (expr) {
var result;
try {
result = eval(expr);
} catch (e) {
result = false;
}
return '
' + expr + '';
}).join('');
```
--------------------------------
### Score QuestionnaireResponse answers using weight()
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Calculates the sum of weights for QuestionnaireResponse answers, utilizing the weight() function and potentially an async context. Requires the fhirpath library, a FHIR context model, and specific options for async and terminology.
```javascript
const fhirpath = require('fhirpath');
const modelR4 = require('fhirpath/fhir-context/r4');
// weight()/ordinal() — score QuestionnaireResponse answers via itemWeight extension
fhirpath.evaluate(
questionnaireResponse,
'%context.repeat(item).answer.weight().sum()',
{},
modelR4,
{ async: true, terminologyUrl: 'https://lforms-fhir.nlm.nih.gov/baseR4' }
);
```
--------------------------------
### Execute FHIRPath Expression with Variables
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Pass environment variables to the FHIRPath expression by providing a JSON object with variable names as keys using the --variables flag.
```sh
fhirpath --expression '%v + 2' --resourceJSON '{}' --variables '{"v": 5}'
```
--------------------------------
### CLI: Pass environment variables as JSON
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Evaluates a FHIRPath expression using environment variables passed as a JSON string. Useful for dynamic expression evaluation.
```bash
# Pass environment variables as JSON
fhirpath --expression '%v + 2' --resourceJSON '{}' --variables '{"v": 5}'
```
--------------------------------
### Interact with FHIR Terminology Service API
Source: https://context7.com/hl7/fhirpath.js/llms.txt
When `terminologyUrl` and `async: true` are provided, the `%terminologies` environment variable is populated with an object implementing the FHIRPath Terminology Service API. Supported methods include `expand`, `lookup`, `validateVS`, `validateCS`, `subsumes`, and `translate`. All are asynchronous and require the `async` option to be enabled.
```javascript
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
const TERMINOLOGY_URL = 'https://lforms-fhir.nlm.nih.gov/baseR4';
// Check if a coding is a member of a value set
const result = await fhirpath.evaluate(
observationResource,
"Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))",
{},
r4_model,
{ async: true, terminologyUrl: TERMINOLOGY_URL }
);
```
```javascript
// Expand a value set and check its type
const expanded = await fhirpath.evaluate(
{},
"%terminologies.expand('http://hl7.org/fhir/ValueSet/administrative-gender') is ValueSet",
{},
r4_model,
{ async: true, terminologyUrl: TERMINOLOGY_URL }
);
// => [true]
```
```javascript
// Lookup a code in a code system
const lookup = await fhirpath.evaluate(
{},
"%terminologies.lookup(%coding, 'displayLanguage=en')",
{ coding: { system: 'http://loinc.org', code: '29463-7' } },
r4_model,
{ async: true, terminologyUrl: TERMINOLOGY_URL }
);
```
```javascript
// Pass Authorization headers for secured terminology servers
const secureResult = await fhirpath.evaluate(
questionnaireResponse,
'%context.repeat(item).answer.weight().sum()',
{},
r4_model,
{
async: true,
terminologyUrl: 'https://private-tx-server.example.com',
httpHeaders: {
'https://private-tx-server.example.com': {
Authorization: 'Bearer '
}
}
}
);
```
--------------------------------
### Execute FHIRPath Expression on Resource Part with Base Path
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Evaluate a FHIRPath expression against a specific part of a resource by providing the --basePath and the resource file or JSON.
```sh
fhirpath --basePath QuestionnaireResponse.item --expression 'answer.value' --model r4 --resourceFile questionnaire-part-example.json
```
--------------------------------
### Precompiling FHIRPath Expressions
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Precompiles a FHIRPath expression for reuse, which can improve performance when evaluating the same expression against multiple resources.
```APIDOC
## Precompiling FHIRPath Expressions
### Description
Compiles a FHIRPath expression into a reusable function. This is useful for evaluating the same expression against multiple resources.
### Method
`fhirpath.compile(expression, model, options)`
### Parameters
- **expression**: The FHIRPath expression string or an object with `base` and `expression` properties for partial resource evaluation.
- **model**: The FHIR data model to use.
- **options**: An optional object for advanced settings.
### Request Example (String Expression)
```js
const path = fhirpath.compile('Patient.name.given', fhirpath_r4_model);
let res = path({"resourceType": "Patient", ...}, {a: 5, ...});
```
### Request Example (Object Expression for Partial Resource)
```js
const path = fhirpath.compile({ "base": "QuestionnaireResponse.item",
"expression": "answer.value = 2 year"},
fhirpath_r4_model);
let res = path({ "answer": { "valueQuantity": ...}, {a: 5, ...});
```
```
--------------------------------
### CLI: Use FHIR R4 model for choice type support
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Evaluates a FHIRPath expression using the R4 FHIR model via the CLI, enabling correct handling of FHIR-specific types and structures.
```bash
# Use FHIR R4 model for choice type support
fhirpath --expression 'Observation.value' \
--resourceJSON '{"resourceType":"Observation","valueString":"Green"}' \
--model r4
```
--------------------------------
### Coalesce with async short-circuit
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Demonstrates coalesce with asynchronous expressions, stopping evaluation at the first non-empty async result. Requires async support and a user-defined invocation table for async functions.
```javascript
// coalesce with short-circuit stops at first non-empty async result
await fhirpath.evaluate(
{},
'coalesce(asyncFirst(), asyncSecond())',
{},
null,
{ async: true, userInvocationTable: { /* async fns */ } }
);
```
--------------------------------
### fhirpath.compile(path, model?, options?)
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Compiles a FHIRPath expression into a reusable function. This optimizes performance by parsing the expression only once. The returned function can then be used to evaluate the expression against different FHIR data structures.
```APIDOC
## `fhirpath.compile(path, model?, options?)` — compile a FHIRPath expression for reuse
Parses a FHIRPath expression once and returns a function `(fhirData, envVars?, additionalOptions?) => result`. Reusing the compiled function across multiple resources avoids repeated parsing overhead. Passing `signal` to `compile()` is not allowed; instead, pass it to the returned function per-call. The `path` parameter may be a string or `{ base, expression }` for partial resource contexts.
```js
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
// Compile once, evaluate many times
const getGiven = fhirpath.compile('Patient.name.given', r4_model);
getGiven({ resourceType: 'Patient', name: [{ given: ['Alice'] }] });
// => ['Alice']
getGiven({ resourceType: 'Patient', name: [{ given: ['Bob'] }] });
// => ['Bob']
// Compile with partial resource path
const evalPart = fhirpath.compile(
{ base: 'QuestionnaireResponse.item', expression: 'answer.value.toString()' },
r4_model
);
evalPart(partialItem);
// => ["2 'a'"]
// Compile with environment variable
const addTwo = fhirpath.compile('%a + 2');
addTwo({}, { a: 10 });
// => [12]
// Compile preserving internal types
const getDate = fhirpath.compile('@2018-02-18T12:23:45-05:00', null, { resolveInternalTypes: false });
const raw = getDate({});
// raw[0] is an FP_DateTime instance
// Async compile with per-call AbortSignal
const evalExpr = fhirpath.compile(
"Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))",
r4_model,
{ async: true }
);
const controller = new AbortController();
const promise = evalExpr(resource, {}, { signal: controller.signal });
controller.abort(); // cancel evaluation
```
```
--------------------------------
### Import fhirpath and R4 Model in Node.js
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Import the fhirpath library and the R4 FHIR model for server-side Node.js applications. The R4 model is necessary for handling choice type fields in FHIR resources.
```javascript
const fhirpath = require('fhirpath');
// For FHIR model data (choice type support) pull in the model file:
const fhirpath_r4_model = require('fhirpath/fhir-context/r4');
```
--------------------------------
### CLI: Evaluate resource part using --basePath
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Evaluates a FHIRPath expression against a specific part of a resource using the `--basePath` option, useful for targeting nested structures within larger JSON files.
```bash
# Evaluate a resource part using --basePath
fhirpath --basePath QuestionnaireResponse.item \
--expression 'answer.value' \
--model r4 \
--resourceFile questionnaire-part-example.json
```
--------------------------------
### Precompile FHIRPath Expression
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Precompile expressions for efficient reuse against multiple resources. This is beneficial when evaluating the same path repeatedly.
```javascript
const path = fhirpath.compile('Patient.name.given', fhirpath_r4_model);
let res = path({"resourceType": "Patient", ...}, {a: 5, ...});
```
--------------------------------
### Terminology Service API via %terminologies
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Interact with a FHIR terminology server using the `%terminologies` environment variable. When `terminologyUrl` and `async: true` are provided, this variable is populated with an object implementing the FHIRPath Terminology Service API, supporting methods like `expand`, `lookup`, `validateVS`, `validateCS`, `subsumes`, and `translate`.
```APIDOC
## Terminology Service API via `%terminologies` — interact with a FHIR terminology server
When `terminologyUrl` and `async: true` are provided, the `%terminologies` environment variable is populated with an object implementing the FHIRPath Terminology Service API. Supported methods include `expand`, `lookup`, `validateVS`, `validateCS`, `subsumes`, and `translate`. All are asynchronous and require the `async` option to be enabled.
### Example Usage:
```js
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
const TERMINOLOGY_URL = 'https://lforms-fhir.nlm.nih.gov/baseR4';
// Check if a coding is a member of a value set
const result = await fhirpath.evaluate(
observationResource,
"Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))",
{},
r4_model,
{ async: true, terminologyUrl: TERMINOLOGY_URL }
);
// Expand a value set and check its type
const expanded = await fhirpath.evaluate(
{},
"%terminologies.expand('http://hl7.org/fhir/ValueSet/administrative-gender') is ValueSet",
{},
r4_model,
{ async: true, terminologyUrl: TERMINOLOGY_URL }
);
// => [true]
// Lookup a code in a code system
const lookup = await fhirpath.evaluate(
{},
"%terminologies.lookup(%coding, 'displayLanguage=en')",
{ coding: { system: 'http://loinc.org', code: '29463-7' } },
r4_model,
{ async: true, terminologyUrl: TERMINOLOGY_URL }
);
// Pass Authorization headers for secured terminology servers
const secureResult = await fhirpath.evaluate(
questionnaireResponse,
'%context.repeat(item).answer.weight().sum()',
{},
r4_model,
{
async: true,
terminologyUrl: 'https://private-tx-server.example.com',
httpHeaders: {
'https://private-tx-server.example.com': {
Authorization: 'Bearer '
}
}
}
);
```
```
--------------------------------
### Compile FHIRPath Expression for Reuse
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Compile a FHIRPath expression once to create a reusable evaluation function. This avoids repeated parsing overhead for multiple evaluations. The `path` can be a string or an object for partial resource contexts. Environment variables can be used in expressions. Async compilation with per-call AbortSignal is supported.
```javascript
const fhirpath = require('fhirpath');
const r4_model = require('fhirpath/fhir-context/r4');
// Compile once, evaluate many times
const getGiven = fhirpath.compile('Patient.name.given', r4_model);
getGiven({ resourceType: 'Patient', name: [{ given: ['Alice'] }] });
// => ['Alice']
getGiven({ resourceType: 'Patient', name: [{ given: ['Bob'] }] });
// => ['Bob']
// Compile with partial resource path
const evalPart = fhirpath.compile(
{ base: 'QuestionnaireResponse.item', expression: 'answer.value.toString()' },
r4_model
);
evalPart(partialItem);
// => ["2 'a'"]
// Compile with environment variable
const addTwo = fhirpath.compile('%a + 2');
addTwo({}, { a: 10 });
// => [12]
// Compile preserving internal types
const getDate = fhirpath.compile('@2018-02-18T12:23:45-05:00', null, { resolveInternalTypes: false });
const raw = getDate({});
// raw[0] is an FP_DateTime instance
// Async compile with per-call AbortSignal
const evalExpr = fhirpath.compile(
"Observation.code.coding.where(memberOf('http://hl7.org/fhir/ValueSet/observation-vitalsignresult'))",
r4_model,
{ async: true }
);
const controller = new AbortController();
const promise = evalExpr(resource, {}, { signal: controller.signal });
controller.abort(); // cancel evaluation
```
--------------------------------
### Execute FHIRPath Expression with Inline JSON
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Pass a FHIR resource directly as a JSON string using the --resourceJSON flag for concise expressions.
```sh
fhirpath --expression 'a.b + 2' --resourceJSON '{"a": {"b": 1}}'
```
--------------------------------
### Evaluate FHIRPath Expression
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Use this for direct evaluation of a FHIRPath expression against a resource or a part of a resource. Ensure the correct model is provided.
```javascript
const resourcePart = fhirpath.evaluate(
questionnaireResponse,'QuestionnaireResponse.item', null, fhirpath_r4_model);
fhirpath.evaluate(
resourcePart, "answer.value = 2 year", null, fhirpath_r4_model);
```
--------------------------------
### Extract Model Info with NodeJS
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Runs the `extract-model-info.js` script using NodeJS to process FHIR definition files and output model information into a specified directory.
```sh
> node ./extract-model-info.js --outputDir r6 --fhirDefDir .
```
--------------------------------
### Basic Evaluation
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Evaluates a FHIRPath expression against a given FHIR resource. The `fhirpath_r4_model` is used as the data model.
```APIDOC
## Basic Evaluation
### Description
Evaluates a FHIRPath expression against a FHIR resource using a specified model.
### Method
`fhirpath.evaluate(resource, expression, environmentVariables, model, options)`
### Parameters
- **resource**: The FHIR resource or a part of it to evaluate against.
- **expression**: The FHIRPath expression string.
- **environmentVariables**: An object containing environment variables (can be null).
- **model**: The FHIR data model to use (e.g., `fhirpath_r4_model`).
- **options**: An optional object for advanced settings.
### Request Example
```js
const resourcePart = fhirpath.evaluate(questionnaireResponse, 'QuestionnaireResponse.item', null, fhirpath_r4_model);
fhirpath.evaluate(resourcePart, "answer.value = 2 year", null, fhirpath_r4_model);
```
```
--------------------------------
### Capturing Trace Information
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Enables capturing trace information during FHIRPath expression evaluation by providing a callback function.
```APIDOC
## Capturing Trace Information
### Description
Allows capturing the intermediate steps and values during FHIRPath evaluation by providing a trace function in the options object.
### Method
`fhirpath.evaluate(contextNode, path, envVars, model, { traceFn: function(value, label) })`
### Parameters
- **traceFn**: A callback function that accepts two arguments: `value` (the traced data) and `label` (a string identifying the trace point).
### Request Example
```js
let tracefunction = function (x, label) {
console.log("Trace output [" + label + "]: ", x);
};
const res = fhirpath.evaluate(contextNode, path, envVars, fhirpath_r4_model, { traceFn: tracefunction });
```
```
--------------------------------
### fhirpath.parse(expression)
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Parses a FHIRPath expression string into its abstract syntax tree (AST). This is useful for debugging, building tooling, or understanding the structure of FHIRPath expressions.
```APIDOC
## `fhirpath.parse(expression)` — parse a FHIRPath expression into an AST
Parses a FHIRPath expression string and returns the internal abstract syntax tree (AST). Primarily used for debugging or building tooling around FHIRPath expression structure. The CLI uses this when no resource is supplied, printing the result as YAML.
```js
const fhirpath = require('fhirpath');
const ast = fhirpath.parse('Patient.name.where(use = \'official\').family');
console.log(JSON.stringify(ast, null, 2));
// Outputs the parsed AST structure
// CLI equivalent (prints YAML):
// fhirpath --expression 'Patient.name.given'
```
```
--------------------------------
### Extend FHIRPath with User-Defined Functions
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Define custom FHIRPath functions or override existing ones using the `userInvocationTable` option in `evaluate` and `compile`. Specify the function handler (`fn`), parameter arity (`arity`), and optional flags like `nullable` and `internalStructures`. When `internalStructures: true`, functions receive raw `ResourceNode` instances and must use `fhirpath.util.valData` to access values.
```javascript
const fhirpath = require('fhirpath');
// Define a power function (pow()) and use it in an expression
const options = {
userInvocationTable: {
pow: {
fn: (inputs, exp = 2) => inputs.map(i => Math.pow(i, exp)),
arity: { 0: [], 1: ['Integer'] }
}
}
};
fhirpath.evaluate({ a: [5, 6, 7] }, 'a.pow()', null, null, options);
// => [25, 36, 49]
fhirpath.evaluate({ a: [5, 6, 7] }, 'a.pow(3)', null, null, options);
// => [125, 216, 343]
// Using internalStructures to access ResourceNode metadata
const optionsInternal = {
userInvocationTable: {
pow: {
fn: (inputs, exp = 2) => inputs.map(i => Math.pow(fhirpath.util.valData(i), exp)),
arity: { 0: [], 1: ['Integer'] },
internalStructures: true
}
}
};
fhirpath.evaluate({ a: [2, 3] }, 'a.pow()', null, null, optionsInternal);
// => [4, 9]
// Async user-defined function
const asyncOptions = {
async: true,
userInvocationTable: {
asyncIdentity: {
fn: function(inputs) {
fhirpath.util.checkAllowAsync(this, 'asyncIdentity');
return Promise.resolve(inputs);
},
arity: { 0: [] }
}
}
};
const r = await fhirpath.evaluate(
{ value: [3, 2, 1] },
'value.sort(asyncIdentity())',
{},
null,
asyncOptions
);
```
--------------------------------
### Parse FHIRPath Expression to AST
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Use `fhirpath.parse()` to convert a FHIRPath expression string into its abstract syntax tree (AST). This is useful for debugging or building tools that analyze FHIRPath structure.
```javascript
const fhirpath = require('fhirpath');
const ast = fhirpath.parse('Patient.name.where(use = \'official\').family');
console.log(JSON.stringify(ast, null, 2));
// Outputs the parsed AST structure
// CLI equivalent (prints YAML):
// fhirpath --expression 'Patient.name.given'
```
--------------------------------
### Precise Decimal Math Mode
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Use the `--mathMode precise` flag for calculations requiring exact decimal semantics, such as clinical dosage or financial computations.
```bash
fhirpath --expression '0.1 + 0.2' --resourceJSON '{}' --mathMode precise
# => [0.3]
```
--------------------------------
### Execute FHIRPath Expression with FHIR Model
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
Specify the FHIR model version (e.g., 'r4') to be used for expression evaluation with the --model flag.
```sh
fhirpath --expression 'Observation.value' --resourceJSON '{"resourceType": "Observation", "valueString": "Green"}' --model r4
```
--------------------------------
### User-defined functions via `userInvocationTable`
Source: https://context7.com/hl7/fhirpath.js/llms.txt
Extend or override FHIRPath functions by providing a `userInvocationTable` in the options for `evaluate` or `compile`. This allows defining custom logic or modifying existing function behavior.
```APIDOC
## User-defined functions via `userInvocationTable` — extend or override FHIRPath functions
The `userInvocationTable` option in `evaluate` and `compile` allows defining new FHIRPath functions or overriding built-in ones. Each entry maps a function name to an implementation object with `fn` (the handler), `arity` (a map from parameter count to parameter type array), and optional flags `nullable` and `internalStructures`. When `internalStructures: true`, the function receives raw `ResourceNode` instances and must use `fhirpath.util.valData` to unwrap values.
```js
const fhirpath = require('fhirpath');
// Define a power function (pow()) and use it in an expression
const options = {
userInvocationTable: {
pow: {
fn: (inputs, exp = 2) => inputs.map(i => Math.pow(i, exp)),
arity: { 0: [], 1: ['Integer'] }
}
}
};
fhirpath.evaluate({ a: [5, 6, 7] }, 'a.pow()', null, null, options);
// => [25, 36, 49]
fhirpath.evaluate({ a: [5, 6, 7] }, 'a.pow(3)', null, null, options);
// => [125, 216, 343]
// Using internalStructures to access ResourceNode metadata
const optionsInternal = {
userInvocationTable: {
pow: {
fn: (inputs, exp = 2) => inputs.map(i => Math.pow(fhirpath.util.valData(i), exp)),
arity: { 0: [], 1: ['Integer'] },
internalStructures: true
}
}
};
fhirpath.evaluate({ a: [2, 3] }, 'a.pow()', null, null, optionsInternal);
// => [4, 9]
// Async user-defined function
const asyncOptions = {
async: true,
userInvocationTable: {
asyncIdentity: {
fn: function(inputs) {
fhirpath.util.checkAllowAsync(this, 'asyncIdentity');
return Promise.resolve(inputs);
},
arity: { 0: [] }
}
}
};
const r = await fhirpath.evaluate(
{ value: [3, 2, 1] },
'value.sort(asyncIdentity())',
{},
null,
asyncOptions
);
```
```
--------------------------------
### Evaluating FHIRPath Expressions
Source: https://github.com/hl7/fhirpath.js/blob/master/README.md
The `evaluate` function is the primary method for evaluating FHIRPath expressions against FHIR resources. It takes the resource object, the FHIRPath expression, optional environment variables, a model, and additional options as arguments.
```APIDOC
## evaluate
### Description
Evaluates a FHIRPath expression against a given FHIR resource or a part of it.
### Signature
```js
evaluate(resourceObject, fhirPathExpression, envVars, model, options)
```
### Parameters
* **resourceObject** (object | array) - The FHIR resource object, a part of a resource, or a bundle (as a JS object or array of resources).
* **fhirPathExpression** (string | object) - A string containing the FHIRPath expression (e.g., 'Patient.name.given'). If `fhirData` represents a part of the FHIR resource obtained without using fhirpath.js, this can be an object with `base` and `expression` properties.
* `fhirPathExpression.base` (string) - The base path in the resource from which `fhirData` was extracted.
* `fhirPathExpression.expression` (string) - The FHIRPath expression relative to `base`.
* **envVars** (object) - A hash of variable name/value pairs to be used in the expression. Modifying internal fields of variables after passing them is not recommended due to caching.
* **model** (object) - The domain-specific data model object (e.g., R4). For example, the result of `require("fhirpath/fhir-context/r4");`.
* **options** (object) - Additional options for controlling the evaluation process:
* `options.resolveInternalTypes` (boolean) - Whether to convert values of internal types to standard JavaScript types. Defaults to `true`.
* `options.keepDecimalTypes` (boolean) - When `true`, preserves `FP_Decimal` values instead of converting them to JavaScript numbers. Defaults to `false`.
* `options.traceFn` (function) - An optional trace function to call during tracing.
* `options.userInvocationTable` (object) - A user-defined table to replace or define functions.
* `options.async` (boolean | string) - Defines how to support asynchronous functions. `false` (or similar) throws an exception (default). `true` returns a `Promise` for asynchronous functions only. `"always"` returns a `Promise` always.
* `options.terminologyUrl` (string) - A URL pointing to a terminology server for initializing `%terminologies`.
* `options.fhirServerUrl` (string) - A URL pointing to a FHIR RESTful API server for `resolve()` resources.
* `options.signal` (AbortSignal) - An `AbortSignal` object to abort asynchronous evaluation.
* `options.httpHeaders` (object) - An object with HTTP headers for requests to FHIR servers, structured as `{ "": { "": "", ... } }`.
* `options.preciseMath` (boolean) - Defines the mathematical operations mode. `true` uses precision-safe math for accurate decimal calculations. `false` (default) uses native JavaScript math for better performance but with potential floating-point precision issues.
### Notes
* The `resourceObject` may be modified by this function to add type information.
### Request Example (Basic)
```js
fhirpath.evaluate({"resourceType": "Patient", ...}, 'Patient.name.given');
```
### Request Example (Environment Variables)
```js
fhirpath.evaluate({}, '%a - 1', {a: 5});
```
### Request Example (With Model Data)
```js
fhirpath.evaluate({"resourceType": "Observation", "valueString": "green"},
'Observation.value', null, fhirpath_r4_model);
```
### Request Example (Partial Resource)
```js
fhirpath.evaluate({ "answer": { "valueQuantity": ...}},
{ "base": "QuestionnaireResponse.item",
"expression": "answer.value = 2 year"},
null, fhirpath_r4_model);
```
```