@glion/encode-escapes
v0.16.0
Published
hl7v2 plugin to encode special characters as hl7v2 escape sequences
Maintainers
Readme
@glion/encode-escapes
Unified plugin to encode special characters as HL7v2 escape sequences in literal values.
What it does
Walks an HL7v2 AST and encodes delimiter characters found in subcomponent node values as HL7v2 escape sequences, so a tree that has been modified in memory can be safely serialized back to HL7v2 text without breaking the delimiter structure. It is the inverse of @glion/decode-escapes: encode then decode round-trips to the original values.
Install
npm install @glion/encode-escapesUse
import { hl7v2EncodeEscapes } from "@glion/encode-escapes";
import { hl7v2ToHl7v2 } from "@glion/to-hl7v2";
import { unified } from "unified";
// After modifying AST values that may contain delimiters:
const file = await unified()
.use(hl7v2EncodeEscapes) // encode special chars as escape sequences
.use(hl7v2ToHl7v2) // serialize AST to HL7v2 text
.stringify(tree);Before encoding, a subcomponent.value might contain literal delimiters:
{
"type": "subcomponent",
"value": "Patient allergic to |Peanuts| and \rSevere reaction"
}After this plugin runs:
{
"type": "subcomponent",
"value": "Patient allergic to \\F\\Peanuts\\F\\ and \\.br\\Severe reaction"
}API
unified().use(hl7v2EncodeEscapes[, options])
Encode special characters as HL7v2 escape sequences in literal nodes.
Parameters
options.delimiters(optional) — Override delimiters. If omitted, the plugin reads them fromRoot.data.delimiters(set by the parser). Defaults to the HL7 standard (| ^ ~ & \).
Returns
Nothing (undefined). Mutates the AST in-place.
Behavior
The plugin visits every subcomponent node and rewrites node.value, substituting delimiter and control characters with their HL7v2 escape sequences:
| Input | Output |
| ----- | ------------------------------ |
| \| | \F\ (field separator) |
| ^ | \S\ (component separator) |
| ~ | \R\ (repetition separator) |
| & | \T\ (subcomponent separator) |
| \ | \E\ (escape character) |
| \r | \.br\ (line break directive) |
Delimiter resolution order: Root.data.delimiters (preferred, set by the parser) → options.delimiters → HL7 defaults.
This is the inverse of @glion/decode-escapes:
import { hl7v2DecodeEscapes } from "@glion/decode-escapes";
import { hl7v2EncodeEscapes } from "@glion/encode-escapes";
// encode → decode round-trip
const encoded = await unified().use(hl7v2EncodeEscapes).run(tree);
const decoded = await unified().use(hl7v2DecodeEscapes).run(encoded);
// decoded values === original valuesThe plugin only transforms AST nodes and does not execute code.
Part of Glion
@glion/encode-escapes is part of Glion, the application framework for HL7v2. See the Glion README for the full package catalog and architecture.
