Skip to content
Reference

Transforms

Every transform type, its settings and its input and output, with the sandbox limits for JavaScript.

On this page

A transform step changes the data that flows through a workflow. A step has a transformType. The step's config holds the settings for that type.

TypeTurnsInto
field-mappinga messagea new object, or a copy of the input with fields changed
javascriptinputwhatever your code returns
code-tablecodestranslated codes
sql-lookupa messagethe message with one database value added
hl7v2-to-fhiran HL7v2 messagea FHIR R4 transaction Bundle
fhir-to-hl7v2one FHIR resourceone HL7v2 message
fhir-bulk-splita FHIR Bundleone item per resource
x12-parseX12 textJSON
x12-generateJSONX12 text
cda-parseCDA or C-CDA XMLJSON
csv-parsedelimited textone object per row
csv-generatea list of objectsdelimited text
xml-parseXMLa JSON tree, and values read with XPath
fixed-width-parsefixed-width textone object per record
fixed-width-generatea list of objectsfixed-width text
ncpdp-parseNCPDP Telecommunication textJSON keyed by segment and field id
ncpdp-generatethat JSONNCPDP Telecommunication text
hl7-validatean HL7v2 messagethe same message, checked against a conformance profile
hl7-to-xmlan HL7v2 messageMirth's HL7 v2 XML (<HL7Message>)
xml-to-hl7Mirth's HL7 v2 XMLthe HL7v2 message
xsltXMLthe output of an XSLT 1.0 stylesheet
templatean objecttext or JSON built from a template
deidentifyHL7v2, FHIR, JSONthe same message with patient identifiers removed

The output of a step is the input of the next step on its edge.

Field mapping

A step with a mapping list maps fields row by row. Each row reads a source value, optionally changes it, and writes it to a target path.

config.mapMode decides what the rows write onto. new (the default, Build new in the builder) builds a new object. copy (Copy and edit) copies the input and changes only the mapped targets. On an HL7 input in copy mode, a target such as hl7:PID.5.1 edits that field of the HL7 text in place, so the step returns the message with your changes.

An HL7 input is the HL7 text itself, an MLLP payload's rawMessage, or the content of a file/SFTP pickup run or a GCS get. An hl7: source reads it, and a copy-mode edit writes back to the same field. A pickup read with encoding: "binary" is base64, so it is never read as HL7.

Row fieldWhat it does
sourceA JSON path ($.name.family, $.entry[0].id, $.obx[*].value), or an HL7 path with the hl7: prefix (hl7:PID.5.1).
sources, separatorUp to 10 more sources. Their values are joined to source's with separator (a space by default), and empty parts are skipped. Each names one value, with no [*].
targetThe path to write, such as patient.lastName. Missing objects and arrays are created. In copy mode on HL7, an hl7: path.
lookupValuesAn inline table of from and to rows. A value not in the table gets default if one is set.
defaultUsed when the source is missing or empty.
opsUp to 10 value operations, run in order. See below.
lookupThe name of a code table that translates the value. Applied last.
onMissingCodeA value the lookup table does not hold: fail (default) fails the row, passthrough keeps it, default uses default.
transformLegacy: uppercase, lowercase, trim or date. It runs as the first op. Use ops for new rows.

A row runs in this order: lookupValues, then default, then ops, then the lookup code table.

OpSettingsWhat it does
uppercase, lowercase, trimnoneChanges case, or trims spaces.
substringstart, optional endKeeps the characters from start up to, not including, end. Counts from 0.
padlength, optional char (a space) and side (left)Pads the value to length.
replacefind, optional withReplaces every literal find. It is not a regular expression.
date-formatoptional from (auto), to, optional timezoneRewrites a date. Formats: ISO, ISO-DATE, HL7, HL7DT, YYYYMMDD, YYYY-MM-DD, MM/DD/YYYY. timezone is an IANA zone.
type-castto (number, boolean or string)Converts the value. A value that does not convert fails the row.
regex-replacepattern, optional with and flags (g)Replaces matches of a regular expression. with can name a numbered group as a dollar sign and its number. Flags: g, i, m, s, u. See below.
concatpaths, optional separator (a space) and positionJoins the values of other paths (hl7:PID.5.2, $.name.given) after the value, or before it with position: "before". Empty parts are skipped.
splitseparator, takeSplits the value and keeps part take, counting from 1. -1 is the last part. A part that is not there is empty.
mathoperator, operand, optional decimalsadd, subtract, multiply, divide or round. A value that is not a number, or a divide by zero, fails the row.
default-whenwhen, value, values for equalsUses value when the value is empty, blank (empty or spaces), or one of values (equals), such as NA or UNK.

concat and default-when also run on an empty value. Every other op passes an empty value through unchanged.

A regex-replace pattern is at most 500 characters and runs on values up to 100,000 characters. A pattern that could backtrack badly, such as (a+)+$, is allowed: the builder warns, and a run gives it a 50 ms time limit on values up to 20,000 characters. A pattern that runs past the limit fails the row, which then follows the step's row policy. The builder's preview does not run such a pattern; the dry run does.

when on a row runs it only when its rules pass on the step's input, with the same rules as a condition step: { "logic": "AND", "rules": [{ "field": "PV1.2", "operator": "equals", "value": "I" }] }. logic is AND (default) or OR; up to 20 rules. A row that does not run writes nothing.

In the builder, the cog on a row opens these rules: Code table, When the code table has no entry, Value ops, Only when and Default value. The preview shows a concat path as a placeholder, such as DOE, ‹hl7:PID.5.2›.

Segment ops

In copy mode on an HL7 input, config.segmentOps removes, adds, copies or moves whole segments. The ops run in order, before the rows, so a row can fill in a segment an op added. Every byte outside the segments an op touches, the segment terminators included, is kept as received. A new segment ends with the message's own terminator.

OpSettingsWhat it does
removesegment, optional occurrenceRemoves every matching segment, or one (2, or "last"). segment is an id (NTE) or a pattern (Z*, N?E). MSH is never removed.
insertsegment, optional fields, position, anchor, anchorOccurrence, ifMissingAdds a segment, such as PV1, after (default) or before an anchor segment. fields sets fields by number, { "2": "I" }. With no anchor it goes at the end. ifMissing: true adds it only when the message has none.
copysegment, optional occurrence (1), as, position, anchor, anchorOccurrenceCopies a segment, right after itself by default. as renames the copy, such as IN1 as IN2.
movethe same as copyMoves a segment to the anchor. With no anchor, as renames it in place.

after an anchor means after its last occurrence, and before before its first, unless anchorOccurrence names one. An anchor that is not in the message fails the op: it follows the step's row policy, so skip leaves the message as it was and warns. Removing, copying or moving a segment the message does not have changes nothing.

json
"config": {
  "mapMode": "copy",
  "segmentOps": [
    { "op": "remove", "segment": "Z*" },
    { "op": "insert", "segment": "PV1", "anchor": "PID", "ifMissing": true, "fields": { "2": "U" } },
    { "op": "copy", "segment": "IN1", "as": "IN2" }
  ]
}

In the builder, Copy and edit on an HL7 sample shows Segments above the rows. Its preview lists the sample's segment ids before and after the ops, never field values.

HL7 paths and repeats

HL7 paths count from 1. A plain path reads the first occurrence of a segment and the first repetition of a field. hl7:OBX[2].5 reads the second OBX, hl7:PID.3(2).1 the second repetition of PID-3, and hl7:OBX[*].5 or hl7:PID.3(*) every one, as an array. See Field paths for the full syntax.

A wildcard source writes an array, and each value goes through the row's lookups, default and ops. A target with one [*], such as obs[*].value, writes item by item, so several wildcard rows zip into one array of objects. The builder's Map all sets this up for a field that repeats in the sample.

When a row fails

A row that cannot be applied, such as an unparsable date or number, a target that runs through a value, or a path that names __proto__, constructor or prototype, fails the step. The error names the row, the source and the target, never the value. The failure is permanent, so it is not retried. Set config.onRowError to skip (When a row fails: Skip the field, warn) to drop that field with a warning instead.

Set config.includeMetadata to true to copy messageType and controlId from the trigger payload into the output.

JavaScript

A javascript step runs your code on the step's input. The code is the body of a function: read input, and return the output.

javascript
const name = input.patient.name;
return {
  fullName: `${name.given} ${name.family}`.toUpperCase(),
  source: "example",
};
LimitValue
Memory128 MB
Time5 seconds
Inputinput, a frozen copy. Writing to it does nothing.
OutputThe returned value, as JSON. undefined becomes null.
Network and diskNone, except http.request and the Mirth APIs router, DatabaseConnectionFactory and FileUtil, which call the engine. The code has no require or fetch. To read a database without a script, use an SQL lookup step.
Asyncawait works and a returned Promise is awaited, inside the same 5 seconds. There are no timers or network APIs (the Mirth APIs are synchronous), so a promise settles only on values the code resolves itself; one that never settles fails the step. At most 100,000 promise reactions (then, catch, finally) per run.
Channel mapvars holds at most 64 KB.
Global mapglobals: 256 keys and 64 KB per workflow.

The code runs in an isolated VM (isolated-vm). A step that runs over 5 seconds fails with a timeout error. One that uses over 128 MB is stopped. An engine where isolated-vm cannot load does not run custom code at all: the step fails with isolated-vm is not available on this engine, and /api/health reports checks.sandbox as something other than isolated-vm.

Helpers

HelperWhat it does
hl7.get(raw, path)Reads a field from HL7 text, with the same paths as a mapping (PID.5.1, OBX[2].5, PID.3(*)).
hl7.set(raw, path, value)Returns the HL7 text with that field set.
hl7.parse(raw)The parsed segments.
hl7.editSegments(raw, ops)Returns the HL7 text with segment ops applied, the same as config.segmentOps. hl7.removeSegments(raw, "Z*", occurrence) is the remove op on its own.
date.format(value, from, to, timezone)Rewrites a date, with the formats of the date-format op. timezone is optional.
lookup(table, code, fallback)Translates a code with a code table declared in the step's config.codeTables (up to 10 names). Without fallback, an unknown code fails the step.
lookupRow(table, match, fallback)The first row of a declared code table whose columns match match, such as { sender: "DEMO_NORTH", local_code: "ADM" }, as { column: value }. A string matches the first column. Without fallback, no match fails the step.
console.log, info, warn, errorCaptured on the step's result, at most 100 lines of 1024 characters. Never sent to the log exporter.
varsThe channel map. What one JavaScript step of a message puts there, the next one reads. Imported Mirth $c and $r use it.
responsesIn a destination that runs after others, the earlier destinations' results by name: { status, data, error }. Read-only.
envThe workspace variables, read-only. An unknown or empty name fails the step.
globalsThe workflow's global map.
libsThe shared libraries the step pins in config.libraries: libs.NAME.fn().

Mirth msg and tmp

A step imported from Mirth starts with var msg = __mirthMessage(input), tmp;. For HL7 v2 or XML input, msg is the message as Mirth's tree, and Mirth-style code runs on it. The input is the message text, an MLLP payload's rawMessage, or the content of a file/SFTP pickup or a GCS get, as a Mirth File Reader feeds its scripts. Only a pickup's content is read: a file or sftp run, or a record with the pickup's file object or a GCS get's objectName. Any other record's content, such as a REST response's, and a binary (base64) pickup are never read as the message: msg is a copy of the input.

CodeWhat it does
msg['PID']['PID.5']['PID.5.1'].toString()Reads a component. String(x), x + '' and x == 'F' read it too. A missing element reads as ''.
msg['PID']['PID.5']['PID.5.1'] = 'DOE'Writes it. A missing field or segment is created, and the gaps are padded.
msg['PID']['PID.3'][1], msg['OBX'].length()A repetition or segment occurrence, counted from 0, and how many there are.
delete msg['PID']['PID.19']Removes a field, a repetition ([n]) or a segment.
msg['@id'], msg.attribute('id')An XML attribute.
new XML(text), createSegment, createSegmentAfter, appendChild, copy()Builds elements and segments, as in Mirth.

return msg returns the edited message as text, or, for an MLLP payload, a file/SFTP pickup run or a GCS get, the same payload with the edited text in the field it came from (rawMessage or content) and its MSH keys updated. An unedited message comes back byte for byte. Two things differ from Mirth: toString() of a field with components gives its HL7 text (DOE^JOHN), not XML (use toXMLString() for that), and assigning one field to another copies its content under the target's own name. Literal E4X syntax (<PID/>, msg..OBX, x.@id, for each, default xml namespace) does not run: saving the step warns E4X_LITERAL, and the AI rewrite can convert it. A step may create at most 100,000 elements and use positions up to 999.

If a step has both a mapping and code, the mapping runs first and the code receives its result. Condition expressions run in the same sandbox with a 1 second limit, and read data instead of input. An expression can read env and globals, but cannot change the global map.

Mirth Mapper and Message Builder steps

A Mirth Mapper or Message Builder step that the import does not turn into a data map becomes the JavaScript Mirth generates for it, in the imported JavaScript step. A channel-scope Mapper with a default and one replacement becomes code like this:

js
var mapping;
try {
  mapping = msg["PID"]["PID.3"]["PID.3.1"].toString();
} catch (e) {
  logger.error(e);
  mapping = "";
}
channelMap.put(
  "mrn",
  validate(mapping, "UNKNOWN", new Array(new Array("-", ""))),
);

The map is the step's scope: channelMap, connectorMap, responseMap, globalChannelMap or globalMap. A Message Builder becomes one assignment, such as msg['PID']['PID.5']['PID.5.1'] = validate((...), "", new Array());.

validate(value, defaultValue, replacements) is Mirth's: when value is undefined, null or empty, it takes defaultValue (or ''). A text or message-tree value is then turned into text and each [pattern, replacement] pair is applied as a global regular expression. Any other value, such as a number or an object, is returned as it is, without the replacements.

The step's mapping, and a default or replacement that is an expression ($('mrn'), msg['PID']['PID.8']), run as code, as in Mirth. Everything else in the step's settings is written into the code as a quoted string: the variable name, a quoted default, a quoted pattern and its replacement. The target must be a plain msg[...] or tmp[...] path. A setting that is not one JavaScript expression, a target that is not a plain path, or a pattern only Java's regular expressions accept leaves the step unconverted, with a finding that says which.

Each step keeps its settings on a // mirth-generated-step: line above its code. While the code is unchanged, the Mirth export writes the step back as the same Mapper or Message Builder step; once you edit it, the export writes it as a JavaScript step and says so. A Mapper in connector scope writes a map that lasts only for that JavaScript step, so a later step that reads the variable gets undefined; the finding suggests channel scope.

Outbound template (tmp)

When the Mirth transformer has an outbound template, the whole transformer imports as one JavaScript step, as Mirth runs it: tmp starts as the template, and the step returns tmp, because Mirth sends tmp when a template is set. Edits to msg stay visible to the later steps but are not sent. The template is parsed in the transformer's outbound data type, as Mirth does:

Outbound data typetmp starts as
HL7 v2Mirth's tree of the template, line breaks turned into \r. For an MLLP payload, the payload with the text replaced
XMLMirth's tree of the template
JSONJSON.parse(template)
RawThe template text
DelimitedThe delimited tree of the template (see below)

The template is written into the code as one quoted string. A template in another data type (HL7 v3, NCPDP, X12), one over 1 MB, one that is not valid in its type (an HL7 v2 template that doesn't start with MSH, JSON that doesn't parse), or one holding a credential-looking value (a key, token or password shape, or a value next to a name such as password, pwd or token) is not imported: a step that uses tmp stays unconverted, and a finding says MedHook sends msg where Mirth sends the template. A transformer with a template and no steps still sends the template, as in Mirth. The settings sit on a // mirth-data-types: line after the shims. The Mirth export writes an HL7 v2 or JSON template back as the transformer's outbound template; it reports the other types for you to set in Mirth.

Delimited data

On a delimited channel, msg is Mirth's delimited tree: <delimited><row><column1>…</column1></row></delimited>, one row per record (row1, row2, … with Numbered Rows), one element per value, named from Column Names and then column1, column2, …. msg['row'][0]['column2'] = 'x' writes a value, and a missing column is added. The step returns the tree as delimited text, written with the outbound data type's properties: values that hold the column or record delimiter are quoted, the escape token is doubled and the quote escaped, and every record ends with the record delimiter, as Mirth's serializer does. Like Mirth's, that text doesn't always read back the same (a value that starts with a quote but holds no delimiter is written as it is), so the Mirth steps of a delimited transformer run together in one JavaScript step and the tree is written once, at the end. The source's CSV parse step runs after them. A delimited message may hold up to 200,000 values.

The column delimiter, record delimiter, quote token, quote escape token, Escape with double quote, Ignore carriage returns and column names are read from the channel (\n, \r, \t written as Mirth writes them). Delimiters are compared as text, never as regular expressions. With Column Widths (fixed width), each record is cut at the widths and trailing spaces dropped, and the tree is written back with each value padded with spaces to its width, or cut to it; the source's fixed-width parse step runs after the steps. A token over 16 characters, a column name that isn't an XML element name, column widths that aren't whole numbers, or a delimited file the SFTP pickup splits into rows (Mirth's batch by record) leaves the step unconverted, with a finding.

Destinations after an XML or delimited source

Mirth gives each destination the source's message as text. When a destination's Mirth steps read XML or delimited data, that destination gets the text and its steps run on Mirth's tree. The source's XML parse or CSV parse step moves to the start of the other destinations, which get the parsed message as before.

Mirth APIs

Mirth scripts call Mirth's own objects, and an imported step keeps those calls. These run in every JavaScript step and JavaScript Writer. A filter expression has the utilities but not router, DatabaseConnectionFactory or the FileUtil file calls.

APIWhat it does in MedHookLimits
channelMap, responseMap, $c, $rThe step's vars: what one JavaScript step of a message puts there, the next one reads.64 KB
globalMap, globalChannelMap, $g, $gcThe workflow's global map.Strings, numbers and booleans; 256 keys
configurationMap, $cfgThe workspace variables, read-only.
connectorMap, sourceMap, $co, $s, $()Per-message maps that start empty; $() searches the maps in Mirth's order.
logger.info, warn, error, debug, trace, fatalCaptured on the step's result, like console.100 lines
router.routeMessage(name, message), router.routeMessageByChannelId(id, message)Queues a run of the workflow with that name (or id) in the same workspace, the way a Run workflow step does, with the message text as its input. Returns a Response: getStatus() is SENT and getMessage() is the new run's id.20 a run, and 100 a chain (a run and every run it started, however deep; SANDBOX_ROUTE_BUDGET). The target must be on and in the same workspace, and a chain of routes stops 5 workflows deep. A retried step does not route twice. Audited. Saving warns SCRIPT_ROUTE_CYCLE when a script routes to its own workflow or around a cycle. A run that another workflow started stays in that chain when it runs again, as a durable retry does: a replay or a bulk reprocess of it (into the same or another workflow) keeps its depth and counts against the same budget, whether it was started with a record or with a raw message such as the HL7 text routeMessage sends. A replay's edited input cannot change that.
DatabaseConnectionFactory.createDatabaseConnection(driver, url, user, password), or ('profile:NAME')A connection through the SQL database adapter: executeCachedQuery(sql, params) reads, executeUpdate(sql, params) writes and returns the row count, close(). ? placeholders bind the values in params (an array or java.util.ArrayList).5 connections and 100 calls a run, at most 1,000 rows a query. Statements time out after 5 seconds. The adapter's host and TLS rules apply. Writes are audited.
FileUtil.read(path), readBytes, write(path, append, data), exists, delete, deleteFileReads and writes through the Local File adapter profile of the workspace whose base folder holds the path. write creates missing folders, as Mirth does.50 calls a run, 8 MB a call. The path must be in a profile's base folder inside FILE_ADAPTER_ROOTS; symlinks and hard links out of it are refused. Writes and deletes are audited.
FileUtil.encode(bytes), FileUtil.decode(text), Base64Util.encode, decodeBase64. Bytes are a Uint8Array.
DateUtil.getCurrentDate(pattern), formatDate(pattern, date), convertDate(in, out, text), getDate(pattern, text)Java SimpleDateFormat patterns (yyyyMMddHHmmss, MM/dd/yyyy, EEE, a, Z, X), in the engine's time zone.Parsing is strict: 20260231 fails instead of rolling over.
StringUtils (also StringUtil)The commons-lang3 helpers scripts use: isBlank, isNotBlank, isEmpty, trim, trimToNull, defaultString, leftPad, rightPad, substringBefore, substringAfter, substringBetween, split, join, replace, equalsIgnoreCase, abbreviate and similar, null-safe.
UUIDGenerator.getUUID()A random UUID.
SerializerFactory.getSerializer('HL7V2')toXML(er7) gives Mirth's HL7 XML and fromXML(xml) gives ER7 back; both also take msg. 'XML' passes text through.HL7V2 and XML only
XmlUtil.prettyPrint, encode, decode, JsonUtil.prettyPrintIndents XML or JSON; escapes and unescapes XML text.

The calls that reach the engine (router, DatabaseConnectionFactory, FileUtil reads and writes) run while the script waits, inside the step's 5 seconds (SANDBOX_CODE_TIMEOUT_MS): a slow database fails the step with a timeout. A run makes at most 200 such calls and moves at most 32 MB through them, and each call's arguments and answer are at most 8 MB. They run with the workflow's workspace: a script cannot route to, connect with or read through another workspace's workflows and profiles. An error names the API, such as executeCachedQuery: the query returned more than 1000 rows; narrow it (WHERE, LIMIT). A routeMessage, executeUpdate, FileUtil.write or delete still running when the step's time is up is abandoned, and the step's error is marked uncertain, because it may still complete: neither the step's retry nor a workflow retry runs the script again, and the run shows the step as uncertain, as for a JavaScript Writer. In a dry run, routeMessage, executeUpdate, FileUtil.write and delete do nothing; reads run. Outside a running workflow (a filter expression, a preview) they fail with is not available here.

Prefer naming a profile: createDatabaseConnection('profile:Lab DB') uses an SQL database profile of the workspace, whose password stays encrypted on the profile. A JDBC URL with a user and password also works, as in Mirth. The password is used as given and never logged, audited or shown in an error, but it sits in the step's code, so the importer redacts a password literal and asks you to re-enter it. The URL can be jdbc:postgresql, jdbc:sqlserver, jdbc:jtds:sqlserver, jdbc:mysql, jdbc:mariadb or jdbc:oracle:thin, and its TLS settings map as on an imported Database Reader.

HTTP from scripts

http.request calls an HTTP API from a JavaScript step, a shared library or a JavaScript Writer. It goes through the Generic REST adapter: its SSRF check on the final URL and every redirect, the profile's TLS options and timeout, OAuth2 tokens and signing.

js
var r = http.request({
  profile: "Scheduling API", // a Generic REST profile of this workspace: its base URL and credentials
  method: "POST", // GET (default), POST, PUT, PATCH or DELETE
  path: "/appointments", // after the profile's base URL; starts with / or ?
  query: { since: "2026-11-01" },
  headers: { "X-Source": "medhook" },
  body: { patient: msg["PID"]["PID.3"]["PID.3.1"].toString() }, // an object is sent as JSON
});
if (r.status === 201) $c("appointmentId", r.json().id);
  • Credentials come from the profile. Name a Generic REST profile (by name or id) and the call uses its base URL, auth (basic, bearer, API key, OAuth2) and default headers; the password or token never appears in the script. The path can't change the profile's host.
  • { url: "https://status.example.test/ping" } instead of a profile calls a URL with no credentials, still SSRF-checked. A URL with a user and password in it is refused.
  • The answer is { status, ok, headers, body, json() } for any status, so a script can branch on a 404. Headers are lower-cased, and credential headers such as Set-Cookie are redacted. body is text.
  • Body: a string is sent as is (text/plain unless you set Content-Type or contentType), an object as JSON, a Uint8Array as bytes.
  • A header can't hold a line break.
  • Per run: at most 20 calls (SANDBOX_HTTP_MAX_CALLS) and 8 MiB of request and response bodies (SANDBOX_HTTP_MAX_BYTES), inside the step's time and the 200-call, 32 MB limit of all engine calls.
  • Every call is in the audit log (workflow.script_http) with the method, host, status and duration, and in the engine log the same way; never the path, query, headers or body.
  • In a dry run (a test run or the live preview, which runs again on every edit) nothing is sent: every call answers { status: 200, dryRun: true, body: null }, and json() on it is an empty object {}, so r.json().id is undefined rather than an error. Check r.dryRun to tell a preview from a real answer. To read a real answer in a test, add sendForReal: true to a GET; any other method is still not sent.
  • It needs a running workflow: in a filter expression or a preview it fails with is not available here. It waits for the answer (no await needed); a call still running when the step's time is up marks the step uncertain, as a routeMessage does.
  • Imported Mirth scripts that call Java's HttpURLConnection or Apache HttpClient are not rewritten to it: the import flags them for review. Rewrite the call with http.request and a profile.

Where it differs from Mirth:

  • executeCachedQuery runs read-only. Write with executeUpdate, which commits on its own; setAutoCommit, commit, rollback and getConnection() throw.
  • A query that returns more than 1,000 rows (SANDBOX_DB_MAX_ROWS, up to 10,000) fails rather than being cut short.
  • routeMessage queues the run and does not wait for it, so the Response carries the run id rather than the target's reply. A workflow name that is missing, or used by two workflows, fails the script; route by id instead.
  • A retried step runs its script again: routeMessage does not queue a second run, but executeUpdate and FileUtil.write run again.
  • A script connection gets its own pool, per workspace, with a 5 second statement timeout, even when it names a profile; at most 8 such pools are kept beside the profiles' own.
  • On import, credentials in a script are redacted where they can be seen: the password argument of createDatabaseConnection (a literal, or literals joined with +), credential-named variables (var dbPassword = '...'), and ;password= or Oracle user/password@ in any string, in steps and code template libraries. A password computed at run time cannot be seen; connect with 'profile:NAME'.
  • A run's __parentExecution (its chain and depth) comes only from runs the engine queued itself (a Run workflow step or routeMessage); in a webhook body or an API call it is ignored and dropped.
  • Java is not emulated. java.lang.String, java.text.SimpleDateFormat, java.util.Date, java.util.UUID, java.util.ArrayList and org.apache.commons.lang3.StringUtils work under java.*, org.* and Packages.*, for the calls scripts make on text, dates and query parameters. Any other class fails with java.io.File is not available in the MedHook sandbox, naming it, and so do importPackage, importClass and JavaImporter.
  • Not available: DatabaseConnectionFactory.createConnection, SMTPConnectionFactory, HTTPUtil, ChannelUtil, AlertSender and alerts, attachments (addAttachment, AttachmentUtil), destinationSet, ACKGenerator, VMRouter, DICOMUtil and FileUtil.rtfToPlainText. The import, the onboarding findings and saving the step (MIRTH_API_UNSUPPORTED) name each one a script calls. Calls on this page are not flagged.

Global map

globals is a small key/value map that belongs to the workflow and outlives a run: a counter, the last id seen, a timestamp. It is the MedHook equivalent of Mirth's global map and global channel map, but it is per workflow: two workflows never share one. For a constant that several workflows share, use a workspace variable.

The global map is not for PHI or secrets. Its values are stored unencrypted, and run history shows every write. A key that looks like a credential (token, secret, password, apiKey) is refused when a step sets it. Reading such a key returns nothing, so an imported $('apiToken') lookup moves on to the configuration map and reads the workspace variable.

CallWhat it does
globals.get(key)The value, or null. Reads what the map held before the step, plus this step's writes.
globals.set(key, v)Sets a string (up to 256 characters), a number or a boolean. The last write wins.
globals.incr(key, n)Adds n (default 1) to a number; a key that is not set counts from 0.
globals.delete(key)Removes the key.

A step's writes are applied together, after the step succeeds. A step that fails applies none of them. incr adds on the database, so two runs that count at the same time, on any replica, never lose a count. A key has at most 128 characters; a step can write at most 1000 times; a write that would take the map past 256 keys or 64 KB fails the step and applies nothing.

A dry run and the deploy checklist's saved test cases read the real map but never change it: the result lists the writes the step would make. Run history shows a step's writes under Global map writes. An operator can read a workflow's map and reset one key with the global map API.

Code table

code-table replaces codes using a named table, set in codeTableName. The table is read from the workflow's own workspace. Lookups are exact and case-sensitive.

A code table has named columns, two or more. A table made from two columns, source then target, is named source and target. A crosswalk can carry one row per healthcare organization and local code, with the standard code and its display beside them, so one workflow serves every sender.

SettingWhat it does
config.fieldsJSON paths of the values to translate, one [*] allowed ($.codes[*].code). The step translates them on a copy of the input.
config.matchColumnsThe columns to match. A column name alone matches the value being translated. column=path matches the value at path in the step's input, such as sender=sendingFacility. Exactly one column takes the value being translated. Default: the first column.
config.returnColumnThe column whose value replaces the code, or * for the whole row as { column: value }. Default: the first column not matched.
config.onMissingCodeA code the table does not hold: fail, passthrough (keep it) or default. With fields the default is fail. Without fields it is passthrough.
config.defaultThe value for onMissingCode: "default".

With neither matchColumns nor returnColumn, the step reads the first column and returns the second, as it always has. When several rows match, the first one wins.

json
{
  "transformType": "code-table",
  "codeTableName": "visit_class",
  "config": {
    "fields": ["visit.class"],
    "matchColumns": ["sender=sendingFacility", "local_code"],
    "returnColumn": "standard_code"
  }
}

Without fields, a string input is looked up directly, and in an object every string value, at any depth in nested objects and arrays, is looked up. A table that does not exist, or a column the table does not have, always fails the step, and the failure is not retried.

On the Code tables page, Edit opens a table as a grid: rename, add and remove columns, edit cells, add and remove rows. CSV downloads every column. To create a table with more than two columns, paste or upload CSV whose header row names them.

An edit reaches running workflows on every replica within about a second. Create and edit tables in the engine UI or with Code tables in the API.

SQL lookup

sql-lookup runs one SELECT against an SQL database profile of the workflow's workspace and writes the answer onto a copy of the input. It is the only transform that reads through an adapter profile. The query runs READ ONLY, reads one row, and binds each value as a parameter.

SettingWhat it does
config.adapterProfileIdThe SQL database profile.
config.sqlThe SELECT, with :name values: SELECT org_id FROM facility_map WHERE facility = :facility.
config.paramsEach :name and the input path it reads: { "facility": "visit.facility" }. A missing value binds NULL.
config.targetWhere the answer is written: visit.orgId.
config.pickvalue (default): the first column of the first row. row: the whole row.
config.onMissingfail (default) fails the step when no row matches, without a retry. null writes null.

The same lookup with the same values queries the database once per execution, and the next execution reads fresh rows.

HL7v2 to FHIR

hl7v2-to-fhir takes an HL7v2 message (the raw string, an MLLP trigger payload with rawMessage, or a file/SFTP pickup run with the message in content) and returns a FHIR R4 Bundle of type transaction. Resources are linked with urn:uuid: references, so POST the Bundle to the server's root as a transaction.

SegmentResource
PIDPatient
PV1Encounter
OBR, ORCServiceRequest
OBXObservation
SCH with AIS, AIL, AIPAppointment
DG1Condition
AL1AllergyIntolerance
IN1Coverage
OBR in an ORUDiagnosticReport
RXA, RXRImmunization
TXA and OBX in an MDMDocumentReference
PR1Procedure
NK1 (opt-in)RelatedPerson
MSH (opt-in)MessageHeader

The newer maps follow the HL7 v2-to-FHIR implementation guide's segment maps:

  • ORU results. Each OBR in an ORU also gives a DiagnosticReport. Its result lists the Observations from the OBX segments after that OBR, and basedOn points at the order's ServiceRequest. Status comes from OBR-25, category from OBR-24, issued from OBR-22. An OBR in an order message (ORM, OML) stays a ServiceRequest only.
  • Immunizations (VXU). Each RXA gives an Immunization: vaccine (RXA-5, CVX), date (RXA-3), dose (RXA-6 and RXA-7; 999 is left out), lot and expiry, manufacturer (RXA-17, MVX), administering provider, new or historical record (RXA-9), and status from RXA-20 and RXA-21. The RXR after it gives route and site, and the ORC before it the filler order number.
  • Documents (MDM). The TXA gives a DocumentReference: type, status (TXA-17, TXA-19), author, the unique document number as masterIdentifier, and the parent document. In an MDM message the OBX segments are the document, so they become its content instead of Observations. An ED value (such as a base64 PDF) is kept exactly as received; text lines (TX, ST, FT) are joined into one text/plain attachment.
  • Procedures. Each PR1 gives a Procedure on the patient and visit, with the code, date, surgeon and practitioners.

Date-times that carry no UTC offset, unsupported segments and similar problems are reported as step warnings, not as errors. Merge messages (MRG) are not applied.

If the step has a mapping, the rows are written on top of the converted Bundle. A target names a resource and a field, such as Patient.name[0].family. Set config.mappingMode to replace (Custom mappings: Replace the converter in the builder) to use only the mappings.

Options

Set these in the step's config. A bad value fails the step.

OptionDefaultWhat it does
timezonenoneAn IANA zone such as America/Chicago, for times with no UTC offset.
missingTimezonewarnWith no timezone, fail fails the step. warn reads such times as UTC (SIU times are left out) and adds a warning. New templates set fail.
includeSsnfalseKeep PID-19 and SS-typed PID-3 identifiers. They are dropped by default.
identifierSystemsnoneMaps an assigning-authority namespace (CX.4.1) to a system URI, for senders that give a bare name.
conditionalCreatefalsePOST Patient and Encounter with ifNoneExist, matched on PID-3 and PV1-19, so a repeated message does not duplicate them.
conditionalUpdatefalsePUT Patient and Encounter by identifier instead. It replaces the stored resource with what this message carries.
zSegmentsskipskip reports Z-segments and leaves them out. extension forwards each one raw as an extension on the Patient.
nextOfKinskiprelated-person writes each NK1 as a RelatedPerson linked to the Patient (Next of kin (NK1) in the builder).
messageHeaderskipinclude adds a MessageHeader from MSH, whose focus lists every other resource in the Bundle (Message header (MSH) in the builder).
fhirVersionR4Set R5 to upgrade the Bundle to R5 shape.
mappingModemergemerge writes the mapping rows onto the converter's Bundle. replace returns only the mapping's output.

FHIR to HL7v2

fhir-to-hl7v2 builds one HL7v2 2.5.1 message from one FHIR resource.

ResourceMessage
PatientADT^A08
Encounter, in-progressADT^A01, or ADT^A08 on an update
Encounter, finishedADT^A03
Appointment, bookedSIU^S12, or SIU^S14 on an update
Appointment, cancelledSIU^S15
DiagnosticReportORU^R01
ImmunizationVXU^V04
DocumentReferenceMDM^T02

An update is a resource whose meta.versionId is above 1.

ORU^R01 writes PID, PV1 when the report's encounter is in the file, ORC, OBR, and one OBX per result Observation, then one ED OBX per presentedForm. Every result must be in the same file (or contained): a report with a missing result is refused rather than sent short. VXU^V04 writes PID, ORC, RXA and, with a route or site, RXR. MDM^T02 writes EVN, PID, PV1, TXA and the content: a text/plain attachment as one TX OBX per line, any other attachment as an ED OBX with its base64 unchanged, and a URL-only attachment as RP. To send these from a FHIR Bulk file, list the types in the split step's resourceTypes (for example DiagnosticReport, Observation, Patient), so each report carries its results. The input is a resource, or a loop item from fhir-bulk-split. A whole Bundle, or a list of several entries, is refused: split it first.

OptionWhat it does
messageTypesOverrides the table. Keys are Resource, Resource:status, or Resource:status:updated. The most specific key wins.
sendingApplication, sendingFacilityMSH-3 and MSH-4.
receivingApplication, receivingFacilityMSH-5 and MSH-6.
processingIdMSH-11: P (default), T or D.
timezoneIANA zone for MSH-7 and EVN-2. The default is UTC.

The output holds message (segments joined by carriage returns, which is what the MLLP adapter sends), messageType, controlId and segments. A reference the converter cannot resolve from the same file must carry an identifier, or the step refuses it, because a FHIR logical id is not an MRN a receiver can match.

FHIR bulk split

fhir-bulk-split takes a FHIR Bundle, such as the one a webhook trigger builds from an NDJSON upload, and returns { items, count, ignored }. Each item holds index, ref (Patient/id), the resource, and references, the resources it points to that are in the same file. Feed items to a loop step.

OptionDefaultWhat it does
resourceTypesPatient, Encounter, AppointmentThe types to keep. ignored counts the rest.

X12

x12-parse takes X12 text (a string, or an object with raw, content or rawData, as an X12 trigger's run input has) and returns JSON. The input must be at least 106 characters, because the engine reads the delimiters from the fixed-width ISA segment.

The result holds segments, envelope (ISA and GS), transactionSets (each with transactionSetId, controlNumber and its segments), segmentsById (every occurrence of each segment id), and the first occurrence of each segment by id, such as result.BHT. A top-level segment array holds the segment id first, so result.CLM[1] is CLM01.

Each segment has id, elements (the raw element text) and values, a split view: values[element][repetition][component]. The four delimiters are elementSeparator, segmentTerminator, componentSeparator (ISA-16) and repetitionSeparator (ISA-11, from version 00402 on).

x12-generate goes the other way. It takes the same segments list, or ISA, GS and ST arrays with a body list of segment arrays, and returns { raw, segmentCount }. It joins elements with the result's elementSeparator and ends each segment with its segmentTerminator. The defaults are * and ~. SE01, GE01 and IEA01 are recomputed from the segments, and a value that contains a delimiter is refused.

To build a whole interchange, set config.envelope (senderQualifier, senderId, receiverQualifier, receiverId, functionalId, version, usage P or T, optional ackRequested) and pass transactions: [{ transactionSetId, segments }] as the input, the segments between ST and SE. The step writes ISA, GS, each ST to SE, GE and IEA with correct counts, and returns { raw, segmentCount, controlNumbers }. config.delimiters (element, segment, sub) sets the delimiters. Control numbers come from a counter per workspace, sender and receiver that is kept in the database, shared with the X12 adapter's generate on any profile: each new message gets the next ISA13, GS06 and ST02, and a retry of the same step writes the same numbers again, so the receiver sees a duplicate, not a second claim. They wrap from 999999999 to 1.

CDA parse

cda-parse takes CDA or C-CDA XML, as a string or as an object with content, xml or raw. A binary input (contentEncoding or encoding is "base64") fails the step: set the pickup's encoding to a text charset. It returns a structured object with the patient, the author, the sections and their entries. It uses a built-in parser with no external dependency. To go on to FHIR, use the CDA adapter action cda-to-fhir.

CSV parse

csv-parse reads delimited text (CSV, tab or pipe separated) and returns { rows, rowCount }, one object per row. The input is the text, or an object with content, as a file/SFTP pickup run or a GCS get carries. A binary (base64) one fails the step: set the pickup's encoding to a text charset. A quoted field may hold the delimiter, line breaks and quotes. A UTF-8 byte order mark is dropped.

OptionDefaultWhat it does
delimiter,One character. Write \t for a tab.
recordDelimiterautoauto ends a row at CRLF, LF or CR. Any other text is a literal row separator, such as ~.
quote"The quote character.
escapedoubleHow a quote is written inside a quoted field: double ("") or backslash (\").
headertrueThe first row names the columns. With false, columns are named col1, col2, … or by columns.
columnsnone[{ "name": "age", "type": "number" }]. Types: string, number, boolean, date (ISO). An empty value is null.
skipLines0Lines to drop before the header, such as a report title.
trimfalseTrim spaces around values that are not quoted.
skipEmptytrueDrop empty lines.
strictColumnsfalseA row with more or fewer values than the header fails the step. Otherwise missing values are empty and extra ones are named colN.
maxRows10000More rows fail the step. At most 100000. For a larger CSV file on an SFTP server, use a batch.

An unterminated quote, a value that does not convert to its column type, or too many rows fails the step. The error names the row and the column, never the value.

CSV generate

csv-generate writes a list of objects (or { rows }) as delimited text, with a header line first.

OptionDefaultWhat it does
delimiter,One character.
quote"The quote character. A quote inside a value is doubled.
quoteModeminimalminimal quotes a value only when it holds the delimiter, a quote, a line break or edge spaces. all quotes every value.
headertrueWrite the header line.
columnsall keysThe column order. Without it, the first row's keys, then any other key a later row has.
lineEndingCRLF\r\n or \n.
guardFormulasfalsePut ' before a value that starts with =, +, - or @, so a spreadsheet does not run it as a formula.

A date is written as ISO text, and an object or a list as JSON.

Fixed-width parse

fixed-width-parse reads fixed-width text, where each value sits at a set position on the line, and returns { rows, rowCount }, one object per record. The input is the text, or an object with content, as a file/SFTP pickup run carries; a binary (base64) one fails the step. A file pickup can also run once per record: see batch.fixedWidth.

columns lists the layout. Each column has a name, a width (or an inclusive end), and a 1-based start; without start, a column begins right after the one before it.

Column optionDefaultWhat it does
trimbothSpaces removed when reading: both, left, right or none.
pada spaceThe character the value is padded with. When reading, it is removed from the padded side (000123 → 123).
padSiderightWhere the padding goes: right for left-aligned text, left for right-aligned numbers.
typestringnumber, boolean or date. An empty value is null. A date in CCYYMMDD reads as 2026-11-17.
decimalsnoneFor a number with implied decimals: 012345 with decimals: 2 reads as 123.45.

A file with several kinds of line (a header record, detail records, a trailer) lists records instead of columns: each record type has a name, the prefix its lines start with, and its own columns. The longest matching prefix wins, and each row carries recordType with the record type's name.

OptionDefaultWhat it does
recordDelimiterautoauto splits on CRLF, LF or CR; or give the separator.
recordLengthnoneRecords of this many characters with no line breaks between them.
headerLines0Lines at the top kept aside, returned as header (a list of text lines).
footerLines0Lines at the bottom kept aside, returned as footer.
skipEmptytrueDrop blank lines.
strictLengthfalseA line shorter than its layout fails the step. Without it, the missing columns read as empty.
unknownRecordsfailA line no record type matches: fail the step, skip it, or keep it as { recordType: null, line }.
maxRows10,000More records than this fails the step. At most 100,000.

An error names the line and the column, never the value.

Fixed-width generate

fixed-width-generate writes a list of objects (or { rows }, with the header and footer lines a parse kept) as fixed-width text, one line per object, with the same columns or records layout. Each value is padded with its pad character on its padSide to the column's width. A number with decimals is written without the point, a date column as CCYYMMDD, and a boolean as Y or N. With records, each object's recordType picks its layout, and the record type's prefix starts the line when the code column is empty. A parse followed by a generate with the same layout gives back the same file.

OptionDefaultWhat it does
lineEndingCRLF\r\n, \n, or empty for records with no line breaks.
overflowfailA value longer than its column fails the step, or with truncate is cut to fit.
trimEndfalseDrop the spaces at the end of each line.

NCPDP parse and generate

ncpdp-parse reads an NCPDP Telecommunication message (version D.0, and 5.1, which has the same header) and returns JSON. The fixed-position header becomes header (binNumber, versionReleaseNumber, transactionCode, processorControlNumber, transactionCount, serviceProviderIdQualifier, serviceProviderId, dateOfService and softwareVendorCertificationId on a request; a response has headerResponseStatus and no BIN, processor control number or vendor). Each segment is keyed by AM and its id, and each field by its two-character field id:

json
{
  "messageType": "request",
  "header": {
    "binNumber": "999999",
    "versionReleaseNumber": "D0",
    "transactionCode": "B1"
  },
  "segments": {
    "AM04": { "C2": "DEMO000001" },
    "AM01": { "C4": "19800101", "CA": "TEST" }
  },
  "transactions": [
    {
      "AM07": { "D2": "000000123456", "E7": "30000" },
      "AM11": { "D9": "1000" }
    }
  ]
}

segments holds the segments before the first group (patient, insurance); each group (one claim or service) is an entry in transactions. A field that repeats in a segment, such as the other-payer fields in AM05, becomes a list. Whether a message is a request or a response is read from the header (a request starts with the 6-digit BIN); set messageType to request or response to say so.

ncpdp-generate writes that JSON back as NCPDP text: header values padded with spaces to their positions, and listed fields written group by group (5C 6C, 5C 6C). A parse followed by a generate gives back the same message.

Both steps use Mirth's default separators: segment 0x1E, group 0x1D, field 0x1C. Set segmentDelimiter, groupDelimiter or fieldDelimiter to one character or a hex code such as 0x7E. An error names the segment, never a value.

XML parse and XPath

xml-parse reads XML (the text, or an object with content; a binary, base64 one fails the step) and returns { xml, values }. xml is the document as JSON: attributes as @_name, text as #text, or a plain string for an element with only text, and a list for a repeated element. values holds what each expression in config.xpaths reads.

json
{
  "xpaths": {
    "mrn": "//Patient/identifier/@value",
    "names": "/Bundle/Patient/name"
  }
}

An expression that matches one node gives a string, several give a list, none gives null. count() gives a number.

OptionDefaultWhat it does
xpathsnoneNames and XPath expressions.
stripNamespacestrueDrop namespace prefixes from names in xml.
maxBytes5 MBA larger document fails the step. At most 5 MB.
maxDepth256A document nested deeper fails the step. At most 256.

MedHook reads a subset of XPath, which covers the lookups Mirth channels make:

ExpressionReads
/a/b, a/bb children of the root a (both read from the document).
//b, /a//bEvery b at any depth.
*Any element.
@id, @*An attribute, or every attribute.
text()The element's own text nodes.
count(path)How many nodes the path matches.
[2], [last()]A position among siblings, counted from 1.
[@use='official'], [mrn='TP-1']Elements whose attribute or child has that value.
[@id], [name]Elements that have that attribute or child.

Names match on the local name, so /Patient also reads <h:Patient>. Anything else, such as an axis (following-sibling::), .., |, a function or an operator, is refused when the workflow is saved, with "XPath not supported" and the construct. The same expressions work in filters with the xpath: prefix.

HL7 v2 conformance

hl7-validate checks an HL7 v2 message against a conformance profile before anything else handles it. The message is the input text, or the input's rawMessage, the content of a file/SFTP pickup run or a GCS get (never a binary, base64 one), raw, message or body, so it works straight after an MLLP trigger or a file/SFTP pickup.

SettingValues
config.profileauto (default: the built-in profile for MSH-9), ADT^A01, ADT^A04, ADT^A08, ORU^R01, custom, or a workspace message definition's id
config.customProfileThe profile, as JSON, when profile is custom
config.onFailurereject (default) or annotate

The checks:

FindingWhen
MESSAGE_UNPARSEABLEThe text is not HL7 v2 (it must start with MSH).
PROFILE_NOT_FOUNDauto and no built-in profile for the message type.
MESSAGE_TYPE_MISMATCHMSH-9 is not the profile's message type.
SEGMENT_MISSINGA required segment is not there.
SEGMENT_REPEATA segment appears more often than the profile allows.
SEGMENT_ORDERA segment's first occurrence comes before one listed ahead of it.
SEGMENT_UNEXPECTEDWith strictSegments, a segment the profile does not list. Z-segments never count. A line that is not a known HL7 v2 or Z-segment is reported as "Unexpected segment at position N" without its text (an error with strictSegments, else a warning).
FIELD_REQUIREDA required field is empty.
FIELD_REPEATA field has more repetitions (~) than maxRepeats.
FIELD_TOO_LONGThe first component of a repetition is longer than maxLength.
FIELD_DATATYPENot a valid TS/DTM (YYYY[MM[DD[HH[MM[SS[.S]]]]]][+/-ZZZZ]), DT, TM, NM or SI.
FIELD_TABLEWith a message definition, a value outside the field's code table. A warning, or an error (ACK AE) when the definition says so.

Order is checked on each segment's first occurrence, so repeating groups such as OBR, OBX, OBR, OBX pass. Each finding is { severity, code, segment, segmentIndex, field, message }. Findings name rules and positions, such as FIELD_REQUIRED PID-5, never a value from the message. Segments end at a carriage return. A line feed also ends one only when the next line starts with a known HL7 v2 segment id or a Z-segment followed by the field separator; any other line break, such as one inside free text in OBX-5 or NTE-3, stays part of the value.

With onFailure: "reject", a message with an error fails the step with HL7 conformance failed (AR): SEGMENT_MISSING PV1. The failure is permanent: it is never retried, and the step's error edge runs if it has one, so you can route rejects to a quarantine destination. A message that passes goes on unchanged. On an MLLP trigger with ackMode: "destination", the sender's ACK reports the reject: AR for a structural problem (type, segments) and AE for a field rule, with the rules in MSA-3.

With onFailure: "annotate", every message goes on with hl7Conformance: { valid, profileId, findings, errorCount, warningCount, ackCode }. A text input becomes { rawMessage, hl7Conformance }. A filter on hl7Conformance.valid can then branch.

The built-in profiles are HL7 v2.5.1 subsets: MSH-7, MSH-9 to MSH-12; EVN-2; PID-3, PID-5, PID-7 (TS), PID-8; PV1-2 for ADT; OBR-4 and OBX-2, OBX-3, OBX-11, and OBX-5 typed by OBX-2 for ORU^R01. A custom profile is plain JSON:

json
{
  "id": "demo-health-adt",
  "messageType": "ADT^A01",
  "strictSegments": false,
  "segments": [
    { "id": "MSH", "required": true },
    { "id": "EVN", "required": true },
    {
      "id": "PID",
      "required": true,
      "fields": [
        { "position": 3, "required": true },
        { "position": 5, "required": true },
        { "position": 7, "datatype": "TS", "maxRepeats": 1 },
        { "position": 8, "datatype": "IS", "maxLength": 1 }
      ]
    },
    { "id": "NK1", "max": 0 },
    { "id": "PV1", "required": true }
  ]
}

A segment's max defaults to 1, and 0 means any number. A field rule takes position, required, maxRepeats, datatype (ST, ID, IS, NM, SI, TS, DTM, DT, TM), datatypeFrom (the field that names the datatype, as OBX-2 does for OBX-5) and maxLength. A profile that does not fit this shape is refused when the workflow is saved. HL7 conformance-profile XML is not read.

XSLT

xslt runs an XSLT 1.0 stylesheet over XML text, as Mirth's XSLT Step and Rhapsody's XSLT filter do. The stylesheet is stored on the step. In the builder, add XSLT from the step palette and paste the stylesheet into its Stylesheet box; Run test shows what it produces.

SettingValues
config.stylesheetThe stylesheet text
config.sourcemessage (default): the message text, an MLLP payload's rawMessage, or the content of a file/SFTP pickup run. field: the text at sourceField. variable: the channel map's sourceVariable. hl7-xml: the HL7 v2 message as Mirth's HL7 v2 XML, as Mirth's XSLT Step reads msg on an HL7 v2 channel
config.sourceFieldA dot path, such as document.xml, when source is field
config.sourceVariableA channel map name, when source is variable
config.resultTomessage (default): the output becomes the message, and a file pickup keeps its file details with the output as content. field: resultField on a copy of the message (a text message moves to content). variable: the channel map's resultVariable, and the message goes on unchanged
config.resultFieldA dot path, when resultTo is field
config.resultVariableA channel map name, when resultTo is variable
config.params[{ "name": "facility", "value": "DEMO-NORTH" }]: values for the stylesheet's global xsl:params

A parameter value is text. {{channel.KEY}} in it reads the channel map, as an earlier JavaScript step left it, and {{sender.KEY}} reads the run's sender settings. In the builder, Parameters takes one name = value per line.

json
{
  "type": "transform",
  "transformType": "xslt",
  "config": {
    "stylesheet": "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:v3=\"urn:hl7-org:v3\"><xsl:param name=\"facility\"/><xsl:template match=\"/\"><patient facility=\"{$facility}\" mrn=\"{//v3:patientRole/v3:id/@extension}\"/></xsl:template></xsl:stylesheet>",
    "params": [{ "name": "facility", "value": "{{sender.facility}}" }],
    "resultTo": "variable",
    "resultVariable": "patientXml"
  }
}

xsl:output decides the output: method="xml", html or text, so a stylesheet can produce HL7 v2 text, CSV or JSON as well as XML. The output is always text; add an xml-parse step after it to read the result with XPath.

A stylesheet is self-contained. It reads the message, its parameters and itself: document('') returns the stylesheet, so lookup tables can live inside it. xsl:include, xsl:import and document() of any other file or URL are refused, so a step never reads the engine's files or calls out to the network. A DOCTYPE or entity declaration in the input or the stylesheet is refused, as in xml-parse, so there is no XXE.

The stylesheet runs in its own worker thread, under the same memory and time settings as the JavaScript sandbox (SANDBOX_MEMORY_LIMIT_MB and SANDBOX_CODE_TIMEOUT_MS), so a runaway stylesheet is stopped and fails its step without affecting other workflows. xsl:message terminate="yes" fails the step with the message's text.

Imported Mirth XSLT steps and Rhapsody XSLT filters become xslt steps with their stylesheet. A Mirth step keeps its result variable (resultTo: "variable"), so the JavaScript steps after it read the result with $('name') as before. On an HL7 v2 channel the step reads source: "hl7-xml", the XML Mirth gave the stylesheet, so a stylesheet written for Mirth (/HL7Message/PID/PID.5/PID.5.1) runs unchanged. With hl7-xml, output that goes to the message and is <HL7Message> XML becomes HL7 v2 again, as Mirth's msg does; output to a field or variable stays text, as in Mirth. A stylesheet that loads other files, a step whose source isn't msg or a map variable, and a Mirth step on a JSON or delimited channel get a REVIEW finding. The Mirth export writes an xslt step that reads the message (as text or hl7-xml) or a map variable into a map variable back as an XSLT Step.

HL7 v2 as XML

hl7-to-xml writes an HL7 v2 message as Mirth's HL7 v2 XML, and xml-to-hl7 reads it back. Use them to give an HL7 v2 message to an XML tool, such as xml-parse with XPath, or to take a message a Mirth channel exported as XML. The input is the text, an MLLP payload's rawMessage or the content of a file/SFTP pickup run; the output is the converted text, and a pickup keeps its file details with the output as content. They take no settings.

xml
<HL7Message>
  <MSH><MSH.1>|</MSH.1><MSH.2>^~\&amp;</MSH.2><MSH.3><MSH.3.1>DEMO-ADT</MSH.3.1></MSH.3>…</MSH>
  <PID>
    <PID.2/>
    <PID.3><PID.3.1>TESTMRN0042</PID.3.1>…</PID.3>
    <PID.3><PID.3.1>TESTSSN0042</PID.3.1>…</PID.3>
    <PID.5><PID.5.1>TESTPATIENT</PID.5.1><PID.5.2>ALPHA</PID.5.2></PID.5>
  </PID>
</HL7Message>

Each field repetition is its own element, components are always written (an empty one as <PID.5.2/>), and subcomponents only where the value has them (<PV1.3.4><PV1.3.4.1>DEMO</PV1.3.4.1>…). MSH keeps its field separator and encoding characters as text. HL7 escape sequences (\T\, \F\) stay as they were, as in Mirth, so a message converted and converted back is the same, byte for byte. Converting back writes fields, components and subcomponents in order, filling any gaps, and ends segments with a carriage return. The output matches Mirth's own: the engine's tests compare it with what Open Integration Engine 4.5.2 writes for the same messages. In a JavaScript step, SerializerFactory.getSerializer('HL7V2').toXML(text) and .fromXML(xml) do the same.

Template

template renders text from customCode with the input. Paths are JSON paths (patient.id, $.name[0].family).

TagWhat it does
{{path}}The value, escaped for the output format.
{{{path}}}The value, not escaped.
{{#each path}}…{{/each}}Once per item. Inside, {{this}} is the item, {{@index}} its position, and ../ reads the parent.
{{#if path}}…{{else}}…{{/if}}The first part when the value is non-empty, non-zero and not an empty list.
text
{"patientId": "{{patient.id}}", "codes": [{{#each codes}}{{#if @index}}, {{/if}}"{{this}}"{{/each}}]}

With FLAT_FIELD_PATHS_ENABLED=true (beta), a template over an HL7 v2 input also reads {{hl7:PATH}}, where PATH uses the HL7 path syntax: {{hl7:PID.5.1}}, {{hl7:OBX[2].5}}, {{hl7:PID.3(2).1}}, and {{#each hl7:OBX[*].5}}{{this}}{{/each}} for every value. The hl7: root always reads the message, never the data. If the flag is turned off later, these tags render empty. See Field paths.

config.escape sets how values are escaped. Left out, it comes from the template text after any leading block tags: json for text that starts with { or [, hl7 for MSH, xml for <, otherwise none.

EscapeWhat a value cannot do
jsonBreak out of a JSON string. Outside a string, the value is written as a JSON literal. The output must be valid JSON, or the step fails.
hl7Add a field or a segment: | and line breaks are escaped with the template's MSH delimiters. ^, ~ and & are kept.
xmlAdd markup.
noneNothing is escaped. Output that is a valid JSON object or array is still returned parsed.

Generating XML

Write the XML in the template. With escape set to xml (or left out, for text that starts with <), every {{value}} has &, <, >, " and ' escaped, in element text and in attributes alike.

text
<Patient id="{{patient.id}}"><name>{{patient.name}}</name>{{#each codes}}<code>{{this}}</code>{{/each}}</Patient>

A missing value renders empty, or null under json, with a warning that names the path. Set config.onMissing to fail to fail the step instead. Limits: blocks nest 8 deep, loops run at most 10,000 times, and the output is at most 5 MB. Errors name paths and tags, never values.

De-identify

deidentify (De-identify in the builder's palette) removes or transforms the identifiers in a message, as Rhapsody, Iguana and IRIS de-identification do. Use it to land an analytics copy (BigQuery, a data lake) without patient identity, or to build test messages from production traffic. It reads HL7 v2 (the text, an MLLP payload or a file pickup), FHIR R4 JSON (a resource or a Bundle) and plain JSON, and returns the same kind of message. config.format is auto (the default) or one of hl7v2, fhir and json.

The HIPAA Safe Harbor preset (preset: "safe-harbor", the default) covers the 18 identifiers:

FormatFields
HL7 v2PID-2, 3, 4, 18, 21 and MRG ids, PV1-19/50 visit numbers, ORC/OBR placer and filler numbers, MSH-10 (pseudonym); PID-5, 6, 9, NK1-2/30, GT1-3/4/16, IN1-9/11/16 names (masked); PID-11, NK1-4/32, GT1-5/17, IN1-19 addresses (state, ZIP3, country); phones and email (dropped); PID-19, PID-20, GT1-12, NK1-37 SSN and license (dropped); birth, death, admit, discharge, message, event, order, result and specimen dates
FHIR R4Patient, RelatedPerson, Practitioner and Person name (masked), telecom and photo (dropped), address (state, ZIP3, country), birthDate; every resource's id, identifier values and the ids inside reference, fullUrl and urn:uuid links (pseudonym, so links still resolve); SSN and driver's license identifiers (dropped); a Reference's display; the narrative text; every full date
JSONKeys by name at any depth, ignoring case, _ and -: names (firstName, last_name, ...), ids (mrn, patientId, memberId, accountNumber, visitNumber, policyNumber, ...), ssn and license numbers, phones and email, street and city, address objects, zip/postalCode, dob/birthDate, admit, discharge and service dates, age

Free text (freeText, on by default) drops HL7 NTE-3 and OBX-5 of type TX, FT and ED, and FHIR note, comment and attachment data, since names hide in prose. HL7 Z segments are dropped (zSegments: "drop") because nobody can say what they hold; set keep to keep them. Provider names (PV1-7 and the like) are not identifiers of the patient and are kept unless you add an override.

Each field gets one action:

ActionWhat it does
dropRemoves the value.
maskReplaces it with maskWith (REDACTED by default).
pseudonymReplaces it with a keyed HMAC-SHA256 pseudonym: 16 letters and digits, the same for the same value on every run, in every workflow of the workspace and in every format, so joins still work. An HL7 id keeps its assigning authority and type (CX.4, CX.5).
date-shiftMoves the date by the patient's own number of days (between 1 and shiftDays, 365 by default, earlier or later), keeping its precision and time. Every date of one patient moves by the same amount, so intervals hold.
generalizeA birth date or date keeps its year; an address keeps state, ZIP3 and country; a ZIP becomes ZIP3; an age over 89 becomes 90+.
keepLeaves the value as it is.

dates: "year" (the default) keeps only the year of every date, as Safe Harbor requires. dates: "shift" shifts them instead, which keeps intervals for analytics; shifted dates are not Safe Harbor on their own, so use it where your privacy officer or an expert determination allows. In both modes a birth date that makes the patient 90 or older becomes the year that makes them 90, and a three-digit ZIP covering 20,000 people or fewer becomes 000. The patient for the shift is PID-3 (then PID-2, 4, 18), the Patient's first identifier, or in JSON patientKeyPath (else the first mrn, patientId or memberId). The same MRN gets the same shift in HL7 v2, FHIR and JSON. A message with no patient id shifts by an amount of its own, with a warning.

Overrides (config.overrides, the Field overrides table) replace the preset's action for one field: { "path": "PID-5", "action": "pseudonym" }. Paths are an HL7 field or component (PID-11, PID-11.3, ZPI-2), a FHIR path under a resource type or * (Patient.name, *.identifier, Observation.valueString), or a dotted JSON path from the top with * for any key or item (patient.mrn, visits.*.reason). An override can add a field the preset leaves, or keep one it covers. With preset: "none" only the overrides act. Save refuses a path that doesn't fit the format, a field with two overrides and an unknown action.

json
{
  "type": "transform",
  "transformType": "deidentify",
  "config": {
    "dates": "shift",
    "overrides": [
      { "path": "PID-11.3", "action": "keep" },
      { "path": "PV1-7", "action": "drop" }
    ]
  }
}

The key

Pseudonyms and date shifts are keyed by a secret workspace variable, DEIDENTIFY_KEY by default (keyVariable names another). Without the key nobody can recompute a pseudonym from an MRN. The value is sealed with the engine's encryption key, never shown again after it is saved, and masked in every stored step output. The step refuses to run when it needs the key and the variable is missing, is a plain (not secret) variable, or is shorter than 16 characters; it fails as a setup problem and is not retried. The builder's preview offers Create the key, which adds the variable with 32 random bytes. To add it yourself, use Settings › Secrets & variables with a long random value (openssl rand -hex 32).

Rotating the key changes every pseudonym and every shift, so copies made before and after no longer join. Rotate it on purpose: change the variable's value in Settings › Secrets & variables. The change is recorded in the audit log as workspace_variable.updated with valueChanged: true (never the value), and the 90-day rotation reminder restarts. Keep the old value somewhere safe if you may need to join older copies, and reload the analytics copy after a rotation.

Preview

The step's Preview on sample runs the saved sample through the step's current settings, saved or not, on the engine, with the workspace's key. The After side shows the result, with every value an action keeps shown as [kept]. The Before side is the original and is PHI: it stays hidden until you choose Show PHI and give a reason, which is audited. The preview (POST /api/workflows/{id}/deidentify-preview) needs permission to view message content and is audited as workflow.deidentify_previewed, with counts and never content.

The step is pure: no network, no database, and it adds no time to other steps beyond walking the message once. Errors and warnings name fields, never values.

Collector

A Collector step (step type collector) gathers messages and passes them on as one list per window, the way Mirth's batch writers and Rhapsody's Collector do: a daily payer CSV, one batch HL7 file or one aggregated JSON document.

SettingWhat it does
maxCountClose the window after this many messages (1 to 10,000).
windowMsClose the window this long after its first message (1 second to 31 days).
cronClose the window at a schedule slot, such as 0 2 * * * for 02:00 every day, in timezone (an IANA zone).
keyPathOne window per value of this path in the step input, such as payer.id, for one file per key.
maxBytesClose the window once its messages reach this size (1 KiB to 50 MiB, 10 MiB by default); the message that crosses it is included.

Set at least one of maxCount, windowMs and cron. With windowMs and cron both set, the earlier time wins, and a window always closes at 10,000 messages.

Each message's run adds it to the window and ends at the step. When the window closes, one new run of the workflow starts at the step, with the window's messages as a list in arrival order, for the next steps to turn into one output (CSV generate, a template or JavaScript). The windows are kept in Postgres and shared by every replica, so each window is passed on exactly once, after a crash too. Replaying or retrying that run passes on the same window again. A Collector must be on the workflow's main path (both branches of a condition count): save and deploy refuse one inside a loop, a parallel branch or a router destination. To collect from there, hand the messages to a workflow that collects them.

To write each window as one object to S3 or Google Cloud Storage, which can't append to a file, put the Collector before the write. SFTP, FTP and file destinations can also append to one file with writeMode: "append".

Errors and retries

A transform step takes an errorHandling like a send step: strategy retry, skip or fail, maxRetries (up to 10), retryDelay (up to 60 seconds) and backoffMultiplier (up to 10). A skipped transform passes its input on unchanged, but inside a destination it still fails that destination. A failure the engine knows is permanent, such as a mapping row that cannot be applied, a missing code table, a template error or an HL7 conformance reject, is never retried.

Reference