@cosyte/hl7 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +436 -147
- package/README.md +154 -91
- package/TRADEMARKS.md +37 -0
- package/dist/index.cjs +1504 -111
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2060 -477
- package/dist/index.d.ts +2060 -477
- package/dist/index.mjs +1479 -112
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -6
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/errors.ts","../src/parser/segments.ts","../src/parser/delimiters.ts","../src/parser/known-segments.ts","../src/parser/warnings.ts","../src/parser/mllp.ts","../src/parser/charset.ts","../src/parser/normalize.ts","../src/parser/escapes.ts","../src/parser/tokenize.ts","../src/parser/message-structure.ts","../src/model/dot-path.ts","../src/serialize/emit-field.ts","../src/model/types/_shared.ts","../src/model/types/ce.ts","../src/model/types/cwe.ts","../src/model/types/hd.ts","../src/model/types/cx.ts","../src/model/types/nm.ts","../src/model/types/pl.ts","../src/model/types/sn.ts","../src/parser/dates.ts","../src/model/types/ts.ts","../src/model/types/xad.ts","../src/model/types/xcn.ts","../src/model/types/xpn.ts","../src/model/types/xtn.ts","../src/model/field.ts","../src/model/segment.ts","../src/helpers/allergies.ts","../src/helpers/appointments.ts","../src/helpers/charges.ts","../src/helpers/diagnoses.ts","../src/helpers/notes.ts","../src/helpers/observations.ts","../src/helpers/documents.ts","../src/helpers/identity.ts","../src/helpers/immunizations.ts","../src/helpers/insurance.ts","../src/helpers/timing.ts","../src/helpers/medications.ts","../src/helpers/meta.ts","../src/helpers/next-of-kin.ts","../src/helpers/orders.ts","../src/helpers/pick-mrn.ts","../src/helpers/patient.ts","../src/helpers/structure.ts","../src/helpers/visit.ts","../src/serialize/pretty-print.ts","../src/serialize/to-json.ts","../src/serialize/to-string.ts","../src/model/message.ts","../src/profiles/default.ts","../src/parser/index.ts","../src/model/types/namespace.ts","../src/builder/control-id.ts","../src/builder/format-timestamp.ts","../src/builder/build-message.ts","../src/builder/ack-tables.ts","../src/builder/build-ack.ts","../src/helpers/acknowledgment.ts","../src/profiles/describe.ts","../src/profiles/merge.ts","../src/profiles/validate.ts","../src/profiles/define.ts","../src/profiles/athena.ts","../src/profiles/cerner.ts","../src/profiles/epic.ts","../src/profiles/genericLab.ts","../src/profiles/meditech.ts","../src/profiles/index.ts","../src/model/coding-system.ts","../src/parser/batch.ts","../src/index.ts"],"names":["snippet","segmentName","pad","parseAssigningAuthority","stringOrUndefined","cweOrUndefined","notes","observations","componentAt","fieldSub","buildRoute","SEGMENT_NAME_RE","absentField","scalarField","compositeField"],"mappings":";;;;AA8BO,IAAM,WAAA,GAAc;AAAA,EACzB,cAAA,EAAgB,gBAAA;AAAA,EAChB,aAAA,EAAe,eAAA;AAAA,EACf,2BAAA,EAA6B,6BAAA;AAAA,EAC7B,WAAA,EAAa;AACf;AAkDO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvB,IAAA;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,WAAA,CAAY,IAAA,EAAiB,OAAA,EAAiB,QAAA,EAAuBA,QAAAA,EAAiB;AAC3F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,OAAA,GAAUA,QAAAA;AAAA,EACjB;AACF;AAmBO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChC,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAST,WAAA,CAAY,SAAiB,WAAA,EAAsB;AACxD,IAAA,KAAA,CAAM,OA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,CAAO,SAAS,CAAA;AAAA,IACjC,OAAA,EAAS,MAAA,CAAO,MAAA,CAAO,aAAa,CAAA;AAAA,IACpC,kBAAkB,aAAA,CAAc,MAAA;AAAA,IAChC,WAAA;AAAA,IACA,QAAA,EAAU,MAAA,CAAO,MAAA,CAAO,QAAQ,CAAA;AAAA,IAChC,GAAI,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,KAAe,EAAC;AAAA,IACjD,GAAI,WAAA,KAAgB,MAAA,GAAY,EAAE,WAAA,KAAgB,EAAC;AAAA,IACnD,GAAI,sBAAA,KAA2B,MAAA,GAAY,EAAE,kBAAA,EAAoB,sBAAA,KAA2B;AAAC,GAC/F;AACA,EAAA,OAAO,MAAA,CAAO,OAAO,MAAM,CAAA;AAC7B;;;AC5gBO,IAAM,OAAA,GAAkB","file":"index.mjs","sourcesContent":["/**\n * Fatal error taxonomy for the `@cosyte/hl7` parser pipeline. Four\n * Tier-3 codes cover every unrecoverable structural failure; anything less\n * severe is a Tier-2 warning (see `./warnings.ts`). `Hl7ParseError` is\n * thrown directly; consumers narrow via the `code` discriminant.\n *\n * `ProfileDefinitionError` is declared here so the error taxonomy is locked\n * before Phase 6 wires profile validation — keeping file ownership clean\n * across phases.\n */\n\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Stable string codes for every Tier-3 fatal the parser may throw. Locked\n * at four codes: anything else MUST be a Tier-2 warning. Consumers narrow\n * on `err.code` to react to specific structural failures.\n *\n * @example\n * ```ts\n * import { parseHL7, FATAL_CODES, Hl7ParseError } from \"@cosyte/hl7\";\n * try {\n * parseHL7(\"\");\n * } catch (err) {\n * if (err instanceof Hl7ParseError && err.code === FATAL_CODES.EMPTY_INPUT) {\n * // handle empty input\n * }\n * }\n * ```\n */\nexport const FATAL_CODES = {\n NO_MSH_SEGMENT: \"NO_MSH_SEGMENT\",\n MSH_TOO_SHORT: \"MSH_TOO_SHORT\",\n INVALID_ENCODING_CHARACTERS: \"INVALID_ENCODING_CHARACTERS\",\n EMPTY_INPUT: \"EMPTY_INPUT\",\n} as const;\n\n/**\n * Discriminant type for `Hl7ParseError.code`. Narrowing a caught error by\n * this code lets consumers write exhaustive `switch` blocks (enabled by the\n * `switch-exhaustiveness-check` lint rule) and guarantees a typo-free\n * comparison against the `FATAL_CODES` registry.\n *\n * @example\n * ```ts\n * import type { FatalCode } from \"@cosyte/hl7\";\n * function describe(code: FatalCode): string {\n * switch (code) {\n * case \"EMPTY_INPUT\":\n * return \"input was empty\";\n * case \"NO_MSH_SEGMENT\":\n * return \"missing MSH\";\n * case \"MSH_TOO_SHORT\":\n * return \"MSH truncated\";\n * case \"INVALID_ENCODING_CHARACTERS\":\n * return \"bad MSH-1/MSH-2\";\n * }\n * }\n * ```\n */\nexport type FatalCode = (typeof FATAL_CODES)[keyof typeof FATAL_CODES];\n\n/**\n * Thrown by `parseHL7` when the input violates one of the 4 unrecoverable\n * Tier-3 structural rules (missing MSH, truncated MSH, invalid encoding\n * characters, or empty input). Carries positional context plus a short\n * snippet of the offending input so consumers can log actionable errors.\n *\n * @remarks\n * Snippets may contain PHI when parsing real clinical messages — redact at\n * the call site if required by your compliance posture. The library does\n * not redact snippets itself.\n *\n * @example\n * ```ts\n * import { parseHL7, Hl7ParseError } from \"@cosyte/hl7\";\n * try {\n * parseHL7(\"\");\n * } catch (err) {\n * if (err instanceof Hl7ParseError && err.code === \"EMPTY_INPUT\") {\n * // handle empty input — err.position, err.snippet available\n * }\n * }\n * ```\n */\nexport class Hl7ParseError extends Error {\n public readonly code: FatalCode;\n public readonly position: Hl7Position;\n public readonly snippet: string;\n\n /**\n * Construct a new `Hl7ParseError`. All four fields are required so every\n * thrower populates full positional context per the TOL-02 requirement.\n *\n * @internal\n */\n public constructor(code: FatalCode, message: string, position: Hl7Position, snippet: string) {\n super(message);\n this.name = \"Hl7ParseError\";\n this.code = code;\n this.position = position;\n this.snippet = snippet;\n }\n}\n\n/**\n * Thrown by `defineProfile()` and profile-validation code (Phase 6) when a\n * profile definition is structurally invalid — e.g. references an undefined\n * parent, declares a malformed custom segment, or includes an unsupported\n * date format. Declared in Phase 2 so the error taxonomy is locked before\n * Phase 6 lands; callers may optionally supply the offending profile name\n * for better diagnostics.\n *\n * @example\n * ```ts\n * import { ProfileDefinitionError } from \"@cosyte/hl7\";\n * throw new ProfileDefinitionError(\n * \"Unknown parent profile: epic-v7\",\n * \"my-epic-extension\",\n * );\n * ```\n */\nexport class ProfileDefinitionError extends Error {\n public readonly profileName: string | undefined;\n\n /**\n * Construct a new `ProfileDefinitionError`. `profileName` is optional so\n * Phase 6 callers may omit it when the offending profile cannot be named\n * (e.g. during initial validation before a name is parsed).\n *\n * @internal\n */\n public constructor(message: string, profileName?: string) {\n super(message);\n this.name = \"ProfileDefinitionError\";\n this.profileName = profileName;\n }\n}\n","/**\n * Segment-split stage for the `@cosyte/hl7` parser pipeline. After\n * input normalization (line endings unified to `\\r`), this module turns the\n * single-string input into an ordered array of segment strings with stable\n * positions. Purely mechanical — no HL7 semantics are evaluated here. MSH\n * detection, delimiter discovery, and field tokenization all live in sibling\n * modules (`delimiters.ts`, `tokenize.ts`).\n *\n * The stage follows the Postel-Law \"liberal parser\" posture: preserves empty\n * middle segments (so that `segmentIndex` stays stable for later warnings)\n * and drops a single trailing `\\r` (so that the universally-seen HL7 \"end\n * with CR\" convention does not produce a spurious empty final segment).\n */\n\n/**\n * Splits a normalized (line-ending = `\\r`) HL7 input string into an ordered\n * array of segment strings. Preserves original order including repeated,\n * empty, and Z-segments. A single trailing `\\r` does NOT create a final\n * empty segment; a MIDDLE empty segment (two consecutive `\\r`) IS preserved\n * so downstream `segmentIndex` positions stay stable against the original\n * input.\n *\n * @example\n * ```ts\n * import { splitSegments } from \"@cosyte/hl7\";\n * splitSegments(\"MSH|A\\rPID|1\\r\"); // [\"MSH|A\", \"PID|1\"]\n * splitSegments(\"MSH|A\\r\\rPID|1\"); // [\"MSH|A\", \"\", \"PID|1\"]\n * ```\n */\nexport function splitSegments(normalized: string): readonly string[] {\n // Strip a single trailing \\r only (preserves middle empty segments).\n const trimmed = normalized.endsWith(\"\\r\") ? normalized.slice(0, -1) : normalized;\n if (trimmed.length === 0) return [];\n return trimmed.split(\"\\r\");\n}\n\n/**\n * Build a short, fixed-length snippet of a segment string for attaching to\n * fatal-error context. Truncates to 40 chars with a trailing ellipsis so the\n * thrown `Hl7ParseError.snippet` stays bounded regardless of input size.\n *\n * @example\n * ```ts\n * import { snippet } from \"@cosyte/hl7\";\n * snippet(\"MSH|^~\\\\&|APP|FAC\"); // \"MSH|^~\\\\&|APP|FAC\"\n * ```\n *\n * @internal\n */\nexport function snippet(segment: string): string {\n return segment.length > 40 ? segment.slice(0, 40) + \"\\u2026\" : segment;\n}\n","/**\n * MSH delimiter-discovery stage for the `@cosyte/hl7` parser pipeline.\n * Reads the encoding characters (MSH-1 field separator + MSH-2 component /\n * repetition / escape / subcomponent, and the optional v2.7+ truncation\n * character) from the first segment and throws a Tier-3 `Hl7ParseError` if\n * the structural preconditions fail. Downstream stages (`tokenize.ts`)\n * consume the returned `EncodingCharacters` verbatim and never re-derive\n * them, which keeps custom-delimiter behaviour (PARSE-02) consistent across\n * the pipeline.\n *\n * Only three of the four Tier-3 fatal codes originate here —\n * `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`, `INVALID_ENCODING_CHARACTERS`. The\n * fourth, `EMPTY_INPUT`, is owned by the `normalize.ts` preprocessing stage.\n */\n\nimport { FATAL_CODES, Hl7ParseError } from \"./errors.js\";\nimport { snippet } from \"./segments.js\";\nimport type { EncodingCharacters } from \"./types.js\";\n\n/**\n * The HL7 default 5-tuple of encoding characters used when a message does\n * not override them via MSH-1 / MSH-2. Re-used by downstream stages (Plan 04\n * escape map, Plan 06 `parseHL7`) as a synthetic-message fallback.\n *\n * @example\n * ```ts\n * import { DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * DEFAULT_ENCODING_CHARACTERS.field; // \"|\"\n * ```\n */\nexport const DEFAULT_ENCODING_CHARACTERS: EncodingCharacters = {\n field: \"|\",\n component: \"^\",\n repetition: \"~\",\n escape: \"\\\\\",\n subcomponent: \"&\",\n};\n\n/**\n * Extract the HL7 encoding characters from the first segment of a message.\n *\n * Accepts a 4-character MSH-2 (HL7 v2.1–v2.6 — component/repetition/escape/\n * subcomponent) or a 5-character MSH-2 (HL7 v2.7+ — adds a truncation\n * character; spec default `#`). Both shapes are spec-conformant and must not\n * fatal.\n *\n * Throws `Hl7ParseError` with one of three Tier-3 fatal codes when the\n * structural preconditions fail:\n *\n * - `NO_MSH_SEGMENT` — first segment does not start with `MSH`.\n * - `MSH_TOO_SHORT` — MSH has fewer than 8 chars (cannot contain the\n * encoding-characters field).\n * - `INVALID_ENCODING_CHARACTERS` — MSH-1 is whitespace; MSH-2 is not\n * 4 or 5 distinct non-whitespace chars; or the field separator appears\n * among the MSH-2 encoding chars.\n *\n * @example\n * ```ts\n * import { readDelimiters } from \"@cosyte/hl7\";\n * const v25 = readDelimiters(\"MSH|^~\\\\&|APP|FAC|...\");\n * v25.truncation; // undefined\n * const v27 = readDelimiters(\"MSH|^~\\\\&#|APP|FAC|...\");\n * v27.truncation; // \"#\"\n * ```\n */\nexport function readDelimiters(firstSegment: string): EncodingCharacters {\n const fatalPosition = { segmentIndex: 0 };\n const snip = snippet(firstSegment);\n\n if (firstSegment.length < 3 || firstSegment.slice(0, 3) !== \"MSH\") {\n throw new Hl7ParseError(\n FATAL_CODES.NO_MSH_SEGMENT,\n \"First segment is not MSH — HL7 v2 messages must begin with an MSH segment.\",\n fatalPosition,\n snip,\n );\n }\n\n // Need \"MSH\" + field separator + 4 encoding chars = 8 chars minimum\n // (4-char MSH-2 is the v2.1–v2.6 floor; a 5-char v2.7+ MSH-2 needs 9).\n if (firstSegment.length < 8) {\n throw new Hl7ParseError(\n FATAL_CODES.MSH_TOO_SHORT,\n \"MSH segment is truncated — cannot read encoding characters.\",\n fatalPosition,\n snip,\n );\n }\n\n const field = firstSegment.charAt(3);\n\n if (/\\s/u.test(field)) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"MSH-1 field separator is whitespace — refusing to parse.\",\n fatalPosition,\n snip,\n );\n }\n\n // MSH-2 spans from char 4 to the next field separator. If no terminator\n // appears, MSH-2 runs to end-of-segment. This lets v2.7+ 5-char MSH-2\n // (e.g. `^~\\&#`) parse without hard-coding a slice length.\n const nextFieldSep = firstSegment.indexOf(field, 4);\n const msh2End = nextFieldSep === -1 ? firstSegment.length : nextFieldSep;\n const encodingField = firstSegment.slice(4, msh2End);\n const chars = [...encodingField];\n\n if (chars.length !== 4 && chars.length !== 5) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n `MSH-2 encoding characters must be 4 (v2.1–v2.6) or 5 (v2.7+ adds truncation) characters (got ${String(chars.length)}).`,\n fatalPosition,\n snip,\n );\n }\n if (new Set(chars).size !== chars.length) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n `MSH-2 encoding characters must be ${String(chars.length)} distinct characters.`,\n fatalPosition,\n snip,\n );\n }\n if (chars.some((c) => /\\s/u.test(c))) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"MSH-2 encoding characters must not contain whitespace.\",\n fatalPosition,\n snip,\n );\n }\n if (chars.includes(field)) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"Field separator must not appear among the MSH-2 encoding characters.\",\n fatalPosition,\n snip,\n );\n }\n\n // `noUncheckedIndexedAccess` requires explicit narrowing even though the\n // length/distinct-count checks above guarantee these are defined.\n const component = chars[0];\n const repetition = chars[1];\n const escape = chars[2];\n const subcomponent = chars[3];\n if (\n component === undefined ||\n repetition === undefined ||\n escape === undefined ||\n subcomponent === undefined\n ) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"MSH-2 encoding characters could not be read.\",\n fatalPosition,\n snip,\n );\n }\n\n const truncation = chars.length === 5 ? chars[4] : undefined;\n return truncation === undefined\n ? { field, component, repetition, escape, subcomponent }\n : { field, component, repetition, escape, subcomponent, truncation };\n}\n","/**\n * Registry of standard HL7 v2 segment names used for UNKNOWN_SEGMENT\n * warning detection. Any segment name NOT in this set AND NOT declared in\n * the active profile's customSegments map emits UNKNOWN_SEGMENT per D-31.\n *\n * Derived from HL7 v2.5.1 chapters 3-7 (core message segments, order/result\n * tree, financial tree, scheduling, master files). Z-segments\n * (`/^Z[A-Z0-9]{2}$/`) are NOT in this set — they're always user-defined\n * and must be declared in a profile to avoid the warning.\n *\n * Frozen as `ReadonlySet<string>` for O(1) lookup without mutation risk.\n */\n\n/**\n * Frozen set of every standard HL7 v2 segment name the library recognises.\n * Consumers parsing any segment whose name is neither in this set nor\n * declared by the active profile will see `UNKNOWN_SEGMENT` in\n * `msg.warnings`.\n *\n * @example\n * ```ts\n * import { KNOWN_SEGMENTS } from \"@cosyte/hl7\";\n * console.log(KNOWN_SEGMENTS.has(\"PID\")); // true\n * console.log(KNOWN_SEGMENTS.has(\"ZPI\")); // false\n * ```\n */\nexport const KNOWN_SEGMENTS: ReadonlySet<string> = new Set<string>([\n // Core message header + event + acknowledgement\n \"MSH\",\n \"MSA\",\n \"EVN\",\n \"ERR\",\n \"SFT\",\n // Patient identifiers + demographics + visit\n \"PID\",\n \"PD1\",\n \"MRG\",\n \"PV1\",\n \"PV2\",\n \"PDA\",\n \"PDC\",\n \"PEO\",\n \"DB1\",\n // Next of kin / guarantor / contacts / insurance\n \"NK1\",\n \"GT1\",\n \"IN1\",\n \"IN2\",\n \"IN3\",\n \"ACC\",\n // Allergy / diagnosis / problem / history / goal\n \"AL1\",\n \"DG1\",\n \"PRB\",\n \"IAM\",\n \"FAM\",\n \"GOL\",\n \"PR1\",\n // Observation / order / result / timing\n \"OBR\",\n \"OBX\",\n \"ORC\",\n \"SPM\",\n \"TQ1\",\n \"TQ2\",\n \"NTE\",\n \"UB1\",\n \"UB2\",\n \"FT1\",\n // Pharmacy / treatment\n \"RXA\",\n \"RXC\",\n \"RXD\",\n \"RXE\",\n \"RXG\",\n \"RXO\",\n \"RXR\",\n \"RXV\",\n // Scheduling\n \"SCH\",\n \"AIG\",\n \"AIL\",\n \"AIP\",\n \"AIS\",\n \"ARQ\",\n \"APR\",\n \"RGS\",\n // Document / master files\n \"TXA\",\n \"MFE\",\n \"MFI\",\n \"MFA\",\n \"MCP\",\n \"LDP\",\n \"LCH\",\n \"LOC\",\n \"LRL\",\n \"LCC\",\n // Roles / staff / organizations\n \"ROL\",\n \"STF\",\n \"PRA\",\n \"EDU\",\n \"CER\",\n \"CTD\",\n \"CTI\",\n \"ORG\",\n \"PRC\",\n \"PRD\",\n // Query + response\n \"QAK\",\n \"QPD\",\n \"QRF\",\n \"QRI\",\n \"QID\",\n \"RDF\",\n \"RDT\",\n \"DSC\",\n \"DSP\",\n \"EQL\",\n \"OMC\",\n // Batch / header envelope (out-of-scope per project OOS but valid tokens)\n \"FHS\",\n \"BHS\",\n \"BTS\",\n \"FTS\",\n // Other legacy / clinical study\n \"CSR\",\n \"CSP\",\n \"CSS\",\n]);\n","/**\n * Tier-2 warning registry and factories for the `@cosyte/hl7` parser\n * pipeline. Consumers compare `warning.code === WARNING_CODES.<CODE>` to\n * narrow and react; the parser uses the factories here to construct every\n * warning it emits so that messages, payload shape, and positional context\n * stay consistent across stages.\n */\n\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Stable string codes for every Tier-2 warning the parser may emit. The\n * registry is frozen via `as const` so TypeScript infers the exact string\n * literal union for `WarningCode` — there is zero runtime cost and no\n * magic-string comparisons for consumers.\n *\n * @example\n * ```ts\n * import { parseHL7, WARNING_CODES } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * if (msg.warnings.some((w) => w.code === WARNING_CODES.MLLP_FRAMING_STRIPPED)) {\n * // handle MLLP-wrapped input\n * }\n * ```\n */\nexport const WARNING_CODES = {\n MLLP_FRAMING_STRIPPED: \"MLLP_FRAMING_STRIPPED\",\n FIELD_WHITESPACE_TRIMMED: \"FIELD_WHITESPACE_TRIMMED\",\n UNKNOWN_ESCAPE_SEQUENCE: \"UNKNOWN_ESCAPE_SEQUENCE\",\n TIMESTAMP_FALLBACK_FORMAT: \"TIMESTAMP_FALLBACK_FORMAT\",\n SEGMENT_CASE: \"SEGMENT_CASE\",\n EXTRA_FIELDS: \"EXTRA_FIELDS\",\n UNKNOWN_SEGMENT: \"UNKNOWN_SEGMENT\",\n DUPLICATE_REQUIRED_SEGMENT: \"DUPLICATE_REQUIRED_SEGMENT\",\n ENCODING_MISMATCH: \"ENCODING_MISMATCH\",\n MISSING_REQUIRED_FIELD: \"MISSING_REQUIRED_FIELD\",\n MISSING_EXPECTED_GROUP: \"MISSING_EXPECTED_GROUP\",\n OUT_OF_ORDER_SEGMENT: \"OUT_OF_ORDER_SEGMENT\",\n VERSION_MISMATCH: \"VERSION_MISMATCH\",\n UNKNOWN_CHARSET: \"UNKNOWN_CHARSET\",\n UNSUPPORTED_CHARSET: \"UNSUPPORTED_CHARSET\",\n ACK_NO_CORRELATION_ID: \"ACK_NO_CORRELATION_ID\",\n MERGE_MISSING_PRIOR_OR_SURVIVOR: \"MERGE_MISSING_PRIOR_OR_SURVIVOR\",\n BATCH_COUNT_MISMATCH: \"BATCH_COUNT_MISMATCH\",\n BATCH_MISSING_TRAILER: \"BATCH_MISSING_TRAILER\",\n} as const;\n\n/**\n * Discriminant type for `Hl7ParseWarning.code`. Narrowing a warning by this\n * code lets consumers write exhaustive `switch` blocks (enabled by the\n * `switch-exhaustiveness-check` lint rule) and guarantees a typo-free\n * comparison against the `WARNING_CODES` registry.\n *\n * @example\n * ```ts\n * import type { Hl7ParseWarning, WarningCode } from \"@cosyte/hl7\";\n * function describe(w: Hl7ParseWarning): string {\n * const code: WarningCode = w.code;\n * switch (code) {\n * case \"MLLP_FRAMING_STRIPPED\":\n * return \"stripped MLLP framing\";\n * default:\n * return `warning: ${code}`;\n * }\n * }\n * ```\n */\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Data shape for every Tier-2 warning emitted by the parser. Warnings are\n * plain data (distinct from `Hl7ParseError`, which is a thrown `Error`\n * subclass) so they can be safely accumulated into\n * `Hl7Message.warnings` and passed to `onWarning` callbacks.\n *\n * @example\n * ```ts\n * import type { Hl7ParseWarning } from \"@cosyte/hl7\";\n * const w: Hl7ParseWarning = {\n * code: \"UNKNOWN_SEGMENT\",\n * message: \"Unknown segment: ZZZ\",\n * position: { segmentIndex: 4 },\n * };\n * ```\n */\nexport interface Hl7ParseWarning {\n readonly code: WarningCode;\n readonly message: string;\n readonly position: Hl7Position;\n}\n\n/**\n * Build a `MLLP_FRAMING_STRIPPED` warning. Emitted once per parse when the\n * preprocessor detects and removes MLLP framing bytes (`0x0B` / `0x1C` /\n * trailing `0x0D`) from the input.\n *\n * @example\n * ```ts\n * import { mllpFramingStripped } from \"@cosyte/hl7\";\n * const w = mllpFramingStripped({ segmentIndex: 0 });\n * ```\n */\nexport function mllpFramingStripped(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.MLLP_FRAMING_STRIPPED,\n message: \"MLLP framing bytes (VT/FS/CR) were stripped from the input.\",\n position,\n };\n}\n\n/**\n * Build a `FIELD_WHITESPACE_TRIMMED` warning. Emitted when the parser trims\n * leading or trailing whitespace from a field value (the `trimFields`\n * option, on by default). The message carries only the leading/trailing\n * character **counts** — NEVER the field value itself (before or after\n * trimming) — so no PHI is exposed; the trimmed value is still preserved\n * verbatim in the parsed output.\n *\n * @example\n * ```ts\n * import { fieldWhitespaceTrimmed } from \"@cosyte/hl7\";\n * const w = fieldWhitespaceTrimmed({ segmentIndex: 1, fieldIndex: 5 }, 2, 1);\n * ```\n */\nexport function fieldWhitespaceTrimmed(\n position: Hl7Position,\n leadingCount: number,\n trailingCount: number,\n): Hl7ParseWarning {\n const parts: string[] = [];\n if (leadingCount > 0) parts.push(`${String(leadingCount)} leading`);\n if (trailingCount > 0) parts.push(`${String(trailingCount)} trailing`);\n const summary = parts.length > 0 ? parts.join(\" + \") : \"0\";\n return {\n code: WARNING_CODES.FIELD_WHITESPACE_TRIMMED,\n message: `Field had ${summary} whitespace character(s) trimmed.`,\n position,\n };\n}\n\n/**\n * The standard HL7 v2 escape-identifier letters/prefixes (§2.7): the\n * single-character escapes (`F S T R E X C M Z H N`) and the `.`-prefixed\n * formatting escapes. These are structural HL7 grammar, not sender content —\n * safe to name in a warning message even when the escape body as a whole is\n * unrecognized (e.g. a malformed `\\Cxx\\` or a vendor `\\Z...\\`).\n *\n * @internal\n */\nconst KNOWN_ESCAPE_TYPE_LETTERS: ReadonlySet<string> = new Set([\n \"F\",\n \"S\",\n \"T\",\n \"R\",\n \"E\",\n \"X\",\n \"C\",\n \"M\",\n \"Z\",\n \"H\",\n \"N\",\n]);\n\n/**\n * Identify the structural \"type\" of an escape-sequence body for PHI-safe\n * warning reporting: the leading character when it is one of the standard\n * HL7 escape-identifier letters (`F S T R E X C M Z H N`) or a `.`-prefixed\n * formatting escape, `null` otherwise. A `null` result means the body is not\n * recognizable HL7 escape grammar at all (i.e. it is untrusted field text\n * that happened to follow a stray escape character) and must not be named in\n * a warning.\n *\n * @internal\n */\nexport function classifyEscapeType(body: string): string | null {\n if (body.startsWith(\".\")) return \".\";\n const first = body.charAt(0);\n return KNOWN_ESCAPE_TYPE_LETTERS.has(first) ? first : null;\n}\n\n/**\n * Build an `UNKNOWN_ESCAPE_SEQUENCE` warning for a **terminated** escape\n * sequence (`\\..\\`) whose body is not a recognized HL7 escape. The message\n * NEVER embeds the escape body — only its length and, when the body's first\n * character is a recognized HL7 escape-identifier letter (structural HL7\n * grammar, not PHI — e.g. `Z` for a vendor escape, `.` for a formatting\n * escape), that single letter. A body that doesn't start with a known escape\n * letter is untrusted field text and names no character at all. The sequence\n * itself is still preserved verbatim in the parsed output — only the WARNING\n * message is PHI-safe.\n *\n * @example\n * ```ts\n * import { unknownEscapeSequence } from \"@cosyte/hl7\";\n * const w = unknownEscapeSequence({ segmentIndex: 2, fieldIndex: 3 }, \"Z99\");\n * // message: `Unknown HL7 escape sequence of type \"Z\" (3 chars) preserved verbatim.`\n * ```\n */\nexport function unknownEscapeSequence(position: Hl7Position, body: string): Hl7ParseWarning {\n const type = classifyEscapeType(body);\n const typeClause = type !== null ? ` of type \"${type}\"` : \"\";\n return {\n code: WARNING_CODES.UNKNOWN_ESCAPE_SEQUENCE,\n message: `Unknown HL7 escape sequence${typeClause} (${String(body.length)} chars) preserved verbatim.`,\n position,\n };\n}\n\n/**\n * Build an `UNKNOWN_ESCAPE_SEQUENCE` warning for an **unterminated** escape\n * (an escape character with no closing partner before end-of-input). The\n * \"body\" in this case is the entire remainder of the field, so the message\n * carries NEITHER the body NOR its length (the length of a truncated tail is\n * itself derivable field-shape information) — just the fact that an\n * unterminated escape was found, and the position. The remainder is still\n * preserved verbatim in the parsed output.\n *\n * @example\n * ```ts\n * import { unterminatedEscapeSequence } from \"@cosyte/hl7\";\n * const w = unterminatedEscapeSequence({ segmentIndex: 2, fieldIndex: 3 });\n * // message: `Unterminated HL7 escape sequence preserved verbatim.`\n * ```\n */\nexport function unterminatedEscapeSequence(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNKNOWN_ESCAPE_SEQUENCE,\n message: \"Unterminated HL7 escape sequence preserved verbatim.\",\n position,\n };\n}\n\n/**\n * Build a `TIMESTAMP_FALLBACK_FORMAT` warning. Emitted when a date/time\n * field could not be parsed with its primary (strict HL7) format but a\n * fallback format from `ParseOptions.dateFormats` or built-in fallbacks\n * succeeded.\n *\n * @example\n * ```ts\n * import { timestampFallbackFormat } from \"@cosyte/hl7\";\n * const w = timestampFallbackFormat(\n * { segmentIndex: 1, fieldIndex: 7 },\n * \"YYYY-MM-DD\",\n * );\n * ```\n */\nexport function timestampFallbackFormat(\n position: Hl7Position,\n matchedFormat: string,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.TIMESTAMP_FALLBACK_FORMAT,\n message: `Timestamp parsed with fallback format \"${matchedFormat}\" (not the strict HL7 format).`,\n position,\n };\n}\n\n/**\n * Build a `SEGMENT_CASE` warning. Emitted when a segment identifier is not\n * all-uppercase (e.g. `pid` instead of `PID`). The parser accepts the\n * segment; the warning alerts consumers to non-conforming senders.\n *\n * @example\n * ```ts\n * import { segmentCase } from \"@cosyte/hl7\";\n * const w = segmentCase({ segmentIndex: 3 }, \"pid\");\n * ```\n */\nexport function segmentCase(position: Hl7Position, observed: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.SEGMENT_CASE,\n message: `Segment identifier \"${observed}\" is not uppercase; normalized to \"${observed.toUpperCase()}\".`,\n position,\n };\n}\n\n/**\n * Build an `EXTRA_FIELDS` warning. Emitted when a segment contains more\n * fields than the profile definition (or HL7 spec) declares — the extras\n * are preserved on `RawSegment.fields` but flagged for consumers.\n *\n * @example\n * ```ts\n * import { extraFields } from \"@cosyte/hl7\";\n * const w = extraFields({ segmentIndex: 4 }, \"PID\", 3);\n * ```\n */\nexport function extraFields(\n position: Hl7Position,\n segmentName: string,\n extraCount: number,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.EXTRA_FIELDS,\n message: `Segment \"${segmentName}\" has ${String(extraCount)} more field(s) than the profile declares.`,\n position,\n };\n}\n\n/**\n * Build an `UNKNOWN_SEGMENT` warning. Emitted when a segment identifier is\n * not in the HL7 spec's standard set and not registered in the active\n * profile's `customSegments`.\n *\n * @example\n * ```ts\n * import { unknownSegment } from \"@cosyte/hl7\";\n * const w = unknownSegment({ segmentIndex: 7 }, \"ZZZ\");\n * ```\n */\nexport function unknownSegment(position: Hl7Position, segmentName: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNKNOWN_SEGMENT,\n message: `Unknown segment \"${segmentName}\" — not in HL7 spec and no profile claim.`,\n position,\n };\n}\n\n/**\n * Build a `DUPLICATE_REQUIRED_SEGMENT` warning. Emitted when a segment the\n * profile marks as singleton appears more than once (e.g. two `MSH`\n * segments). The parser keeps both; the warning alerts the consumer to\n * potential sender bugs.\n *\n * @example\n * ```ts\n * import { duplicateRequiredSegment } from \"@cosyte/hl7\";\n * const w = duplicateRequiredSegment({ segmentIndex: 1 }, \"MSH\");\n * ```\n */\nexport function duplicateRequiredSegment(\n position: Hl7Position,\n segmentName: string,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.DUPLICATE_REQUIRED_SEGMENT,\n message: `Required singleton segment \"${segmentName}\" appears more than once.`,\n position,\n };\n}\n\n/**\n * Build an `ENCODING_MISMATCH` warning. Emitted when the MSH-2 encoding\n * characters declared by the sender do not match what the parser observed\n * downstream (e.g. the sender declares `^~\\&` but uses `!@#$` as actual\n * separators in later segments).\n *\n * @example\n * ```ts\n * import { encodingMismatch } from \"@cosyte/hl7\";\n * const w = encodingMismatch({ segmentIndex: 0 }, \"MSH-2 declares ^~\\\\& but segment used !@#$\");\n * ```\n */\nexport function encodingMismatch(position: Hl7Position, detail: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.ENCODING_MISMATCH,\n message: `Encoding mismatch: ${detail}`,\n position,\n };\n}\n\n/**\n * Build a `MISSING_REQUIRED_FIELD` warning. Emitted when a field the active\n * profile marks as required is empty or missing. Distinct from the\n * `NO_MSH_SEGMENT` fatal, which escalates a missing MSH altogether.\n *\n * @example\n * ```ts\n * import { missingRequiredField } from \"@cosyte/hl7\";\n * const w = missingRequiredField({ segmentIndex: 0, fieldIndex: 3 }, \"MSH\", 3);\n * ```\n */\nexport function missingRequiredField(\n position: Hl7Position,\n segmentName: string,\n fieldIndex: number,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.MISSING_REQUIRED_FIELD,\n message: `Required field ${segmentName}-${String(fieldIndex)} is missing or empty.`,\n position,\n };\n}\n\n/**\n * Build a `MISSING_EXPECTED_GROUP` warning (roadmap Phase G). Emitted once per\n * absent Required segment group when the message's (MSH-9.1, MSH-9.2) type is\n * one the structure safety net recognizes and an expected group is entirely\n * missing — e.g. an `ORU^R01` carrying no `OBR`/`OBX` result group, the\n * signature of a truncated or misrouted feed. Tier-2 and additive: lenient\n * parse never throws on it, `strict` mode may promote it. The message carries\n * only the structural fact (message type, group name, anchor segment names) —\n * NEVER a field value, so no PHI is exposed. `position` references MSH-9.\n *\n * @example\n * ```ts\n * import { missingExpectedGroup } from \"@cosyte/hl7\";\n * const w = missingExpectedGroup(\n * { segmentIndex: 0, fieldIndex: 9 },\n * \"ORU^R01\",\n * \"result\",\n * [\"OBR\", \"OBX\"],\n * );\n * ```\n */\nexport function missingExpectedGroup(\n position: Hl7Position,\n messageType: string,\n groupName: string,\n anchorSegments: readonly string[],\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.MISSING_EXPECTED_GROUP,\n message:\n `Message type \"${messageType}\" is missing its expected \"${groupName}\" segment group ` +\n `(no ${anchorSegments.join(\"/\")}); message may be truncated or misrouted.`,\n position,\n };\n}\n\n/**\n * Build an `OUT_OF_ORDER_SEGMENT` warning. Emitted when a segment appears\n * outside the order the active profile declares (e.g. `EVN` appearing\n * before `MSH` in a typical ADT message).\n *\n * @example\n * ```ts\n * import { outOfOrderSegment } from \"@cosyte/hl7\";\n * const w = outOfOrderSegment({ segmentIndex: 2 }, \"EVN\");\n * ```\n */\nexport function outOfOrderSegment(position: Hl7Position, segmentName: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.OUT_OF_ORDER_SEGMENT,\n message: `Segment \"${segmentName}\" appears out of the order declared by the active profile.`,\n position,\n };\n}\n\n/**\n * Build a `VERSION_MISMATCH` warning. Emitted when MSH-12 declares an HL7\n * version that does not match what the active profile or `ParseOptions`\n * expected.\n *\n * @example\n * ```ts\n * import { versionMismatch } from \"@cosyte/hl7\";\n * const w = versionMismatch({ segmentIndex: 0, fieldIndex: 12 }, \"2.9\", \"2.5\");\n * ```\n */\nexport function versionMismatch(\n position: Hl7Position,\n declared: string,\n expected: string,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.VERSION_MISMATCH,\n message: `HL7 version mismatch: message declares \"${declared}\", expected \"${expected}\".`,\n position,\n };\n}\n\n/**\n * Build an `UNKNOWN_CHARSET` warning. Emitted when MSH-18 (or an\n * `options.charset` override) declares a value that is **not a recognized HL7\n * Table-0211 character set**. The parser never guesses an encoding: it reads the\n * raw bytes as `latin1` (a 1:1 byte mapping) so single-byte content stays\n * recoverable, rather than corrupting it with replacement characters. The\n * message carries the charset code only — never a decoded field value — so no\n * PHI is exposed.\n *\n * @example\n * ```ts\n * import { unknownCharset } from \"@cosyte/hl7\";\n * const w = unknownCharset({ segmentIndex: 0, fieldIndex: 18 }, \"ISO IR 999\");\n * ```\n */\nexport function unknownCharset(position: Hl7Position, requested: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNKNOWN_CHARSET,\n message: `Unrecognized character set \"${requested}\"; not decoded, bytes read as latin1.`,\n position,\n };\n}\n\n/**\n * Build an `UNSUPPORTED_CHARSET` warning. Emitted when a **recognized**\n * Table-0211 character set is not decoded into text — either because this parser\n * does not decode it (the multibyte / ISO-2022-switched East-Asian sets — JIS,\n * GB 18030, KS X 1001, CNS 11643, BIG-5 — and the wide Unicode transforms\n * UTF-16 / UTF-32), or because a strict decode of a decodable set **failed** (a\n * byte invalid / undefined for the declared set, or an ICU build lacking the\n * label). In every case the raw bytes are read as `latin1`, never guessed at, so\n * the parser does not emit replacement-char-corrupted text. Single-byte content\n * stays byte-recoverable; multibyte content is best-effort (a content byte can\n * coincide with a structural delimiter — see the parser's known-limitations).\n * The switch escapes (`\\Cxxyy\\` / `\\Mxxyyzz\\`) are recognized and preserved by\n * the escape layer; full stateful decoding is a documented non-goal. The message\n * carries the charset code only — never a decoded field value — so no PHI is\n * exposed.\n *\n * @example\n * ```ts\n * import { unsupportedCharset } from \"@cosyte/hl7\";\n * const w = unsupportedCharset({ segmentIndex: 0, fieldIndex: 18 }, \"ISO IR87\");\n * ```\n */\nexport function unsupportedCharset(position: Hl7Position, code: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNSUPPORTED_CHARSET,\n message: `Character set \"${code}\" was not decoded; bytes read as latin1.`,\n position,\n };\n}\n\n/**\n * Build an `ACK_NO_CORRELATION_ID` warning. Emitted by `buildAck` (Phase C),\n * not by the parser: the inbound message carried no MSH-10 message control ID,\n * so the generated ACK leaves MSA-2 empty and, when a positive accept was\n * requested, downgrades it to an error code rather than fabricating an\n * unverifiable `AA`/`CA`. The `position` references the inbound MSH segment.\n * The message NEVER echoes a PHI value — only the structural fact.\n *\n * @example\n * ```ts\n * import { buildAck, WARNING_CODES } from \"@cosyte/hl7\";\n * const ack = buildAck(inbound, { code: \"AA\" }); // inbound has no MSH-10\n * ack.warnings.some((w) => w.code === WARNING_CODES.ACK_NO_CORRELATION_ID); // true\n * ```\n */\nexport function ackNoCorrelationId(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.ACK_NO_CORRELATION_ID,\n message:\n \"Inbound message has no MSH-10 control ID; ACK MSA-2 left empty and any \" +\n \"positive accept downgraded to an error code (no fabricated AA/CA).\",\n position,\n };\n}\n\n/**\n * Build a `MERGE_MISSING_PRIOR_OR_SURVIVOR` warning (roadmap Phase K). Emitted\n * by `identityEvents()` (a read-side helper — it attaches to the returned\n * `IdentityEvent.warnings`, never to `Hl7Message.warnings`) when a merge/move\n * trigger event (A18/A34/A35/A36/A39/A40/A41/A42/A43/A44) is missing one side\n * of the spec-mandated MRG (prior) → PID (surviving) pair — or when that side\n * carries no usable identity field: no MRG segment in the patient group, no\n * PID for an orphaned MRG, or a PID/MRG whose identifier, account, and visit\n * fields are all empty or version-gated (a v2.7+ MRG whose only content was\n * the withdrawn MRG-4 must not read as \"nothing to retire\"). The helper\n * surfaces whatever IS present and never\n * guesses the merge direction — this warning is the signal that the pair is\n * incomplete.\n *\n * The message carries only the structural facts (trigger event code + which\n * role is missing) — NEVER an identifier, name, or any other field value, so\n * no PHI is exposed (HL7 v2 Ch. 3: the PID carries surviving and the MRG\n * carries non-surviving identity information).\n *\n * @example\n * ```ts\n * import { mergeMissingPriorOrSurvivor } from \"@cosyte/hl7\";\n * const w = mergeMissingPriorOrSurvivor({ segmentIndex: 1 }, \"A40\", \"prior\");\n * ```\n */\nexport function mergeMissingPriorOrSurvivor(\n position: Hl7Position,\n eventType: string,\n missing: \"prior\" | \"survivor\",\n): Hl7ParseWarning {\n const detail =\n missing === \"prior\"\n ? \"no MRG segment carries a usable prior (non-surviving) identifier\"\n : \"no PID segment carries a usable surviving identifier\";\n return {\n code: WARNING_CODES.MERGE_MISSING_PRIOR_OR_SURVIVOR,\n message:\n `Identity event \"${eventType}\" is missing its ${missing} role: ${detail}. ` +\n \"Surfacing what is present; the MRG->PID merge direction is not guessed.\",\n position,\n };\n}\n\n/**\n * Build a `BATCH_COUNT_MISMATCH` warning (roadmap Phase L). Emitted by\n * `splitBatch()` — attached to the returned `BatchSplitResult.warnings`, never\n * to `Hl7Message.warnings` — when a declared envelope count does not equal the\n * count actually split out: a **BTS-1** batch message count that differs from\n * the messages found in that batch, or an **FTS-1** file batch count that\n * differs from the batches found in the file (HL7 v2 Ch. 2 §2.10.3; BTS-1 / FTS-1\n * per the BTS / FTS segment definitions in §2.15).\n * The splitter **never drops the tail** to make the numbers agree — the\n * mismatch is surfaced and every message is still returned; the caller decides\n * whether to reject.\n *\n * The message carries only the declared-vs-actual **integers** and the unit\n * (`message` for BTS-1, `batch` for FTS-1) — NEVER a field value, facility\n * identifier, or any other content, so no PHI is exposed. `position` references\n * the trailer segment (`BTS`/`FTS`) that declared the count.\n *\n * @example\n * ```ts\n * import { batchCountMismatch } from \"@cosyte/hl7\";\n * const w = batchCountMismatch({ segmentIndex: 4 }, \"message\", 3, 2);\n * ```\n */\nexport function batchCountMismatch(\n position: Hl7Position,\n unit: \"message\" | \"batch\",\n declared: number,\n actual: number,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.BATCH_COUNT_MISMATCH,\n message:\n `Batch envelope declares ${String(declared)} ${unit}(s) but ${String(actual)} ` +\n `were found; the count mismatch is surfaced and nothing was dropped.`,\n position,\n };\n}\n\n/**\n * Build a `BATCH_MISSING_TRAILER` warning (roadmap Phase L). Emitted by\n * `splitBatch()` — attached to `BatchSplitResult.warnings` — when an envelope\n * header opens a scope that is never closed: a **BHS** batch header with no\n * matching **BTS** trailer, or an **FHS** file header with no matching **FTS**\n * trailer (HL7 v2 Ch. 2 §2.10.3 — each envelope segment is optional, but a\n * profile such as an IIS file-submission spec may mandate the full frame).\n * `splitBatch` **does not enforce** such a rule — it splits, warns, and leaves\n * the accept/reject decision to the caller; the parse never throws for this.\n *\n * The message carries only the header/trailer segment names — NEVER a field\n * value, so no PHI is exposed. `position` references the unmatched header\n * segment (`FHS`/`BHS`).\n *\n * @example\n * ```ts\n * import { batchMissingTrailer } from \"@cosyte/hl7\";\n * const w = batchMissingTrailer({ segmentIndex: 0 }, \"BHS\", \"BTS\");\n * ```\n */\nexport function batchMissingTrailer(\n position: Hl7Position,\n header: \"FHS\" | \"BHS\",\n expectedTrailer: \"FTS\" | \"BTS\",\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.BATCH_MISSING_TRAILER,\n message:\n `Batch envelope header \"${header}\" has no matching \"${expectedTrailer}\" trailer; ` +\n \"splitBatch surfaces this but does not reject — a profile that mandates the full envelope may.\",\n position,\n };\n}\n","/**\n * MLLP (Minimal Lower Layer Protocol) framing byte removal for the\n * `@cosyte/hl7` parser pipeline. MLLP wraps an HL7 v2 message with a\n * start-block byte (`0x0B` / VT) and an end-block pair (`0x1C` / FS followed\n * by `0x0D` / CR). This module strips those control bytes and flags the event\n * via the `MLLP_FRAMING_STRIPPED` Tier-2 warning (TOL-06).\n *\n * Per CONTEXT.md D-03, MLLP stripping runs after BOM strip and before\n * line-ending normalization in the overall pipeline. Plan 06 composes the\n * full pipeline; this module stays standalone so Plan 06 can invoke it in the\n * exact right position.\n */\n\nimport { mllpFramingStripped } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Result of an MLLP framing strip. `wasFramed` is `true` iff any of the three\n * MLLP control bytes (VT = `0x0B`, FS = `0x1C`, trailing CR = `0x0D` paired\n * with an FS) were removed from the input — the signal downstream code uses\n * to decide whether to emit an `MLLP_FRAMING_STRIPPED` warning.\n *\n * @example\n * ```ts\n * import { stripMllp, type StripMllpResult } from \"@cosyte/hl7\";\n * const r: StripMllpResult = stripMllp(\"\\u000BMSH|...\\u001C\\u000D\");\n * // r.stripped === \"MSH|...\"; r.wasFramed === true\n * ```\n */\nexport interface StripMllpResult {\n readonly stripped: string;\n readonly wasFramed: boolean;\n}\n\n/**\n * Strip MLLP framing bytes from a raw HL7 message string. Removes all\n * occurrences of VT (`\\u000B`) and FS (`\\u001C`); additionally removes a\n * single trailing CR (`\\u000D`) if and only if it was paired with a trailing\n * FS (the MLLP end-block convention). Data CRs in the middle of the payload\n * are preserved as segment terminators.\n *\n * Pure function: safe to call on any string. Returns the original string\n * unchanged with `wasFramed: false` when no framing bytes are present.\n *\n * @example\n * ```ts\n * import { stripMllp } from \"@cosyte/hl7\";\n * const { stripped, wasFramed } = stripMllp(\"\\u000BMSH|^~\\\\&|APP\\rPID|1\\u001C\\u000D\");\n * // stripped === \"MSH|^~\\\\&|APP\\rPID|1\"; wasFramed === true\n * ```\n */\nexport function stripMllp(input: string): StripMllpResult {\n const hasVt = input.includes(\"\\u000B\");\n const hasFs = input.includes(\"\\u001C\");\n if (!hasVt && !hasFs) {\n return { stripped: input, wasFramed: false };\n }\n\n const originalEndedWithFsCr = /\\u001C\\u000D$/u.test(input);\n let s = input.replace(/[\\u000B\\u001C]/gu, \"\");\n if (originalEndedWithFsCr && s.endsWith(\"\\u000D\")) {\n s = s.slice(0, -1);\n }\n return { stripped: s, wasFramed: true };\n}\n\n/**\n * Emit an `MLLP_FRAMING_STRIPPED` warning via the supplied callback when the\n * given strip result indicates framing bytes were removed. No-op when\n * `result.wasFramed` is false. Kept as a companion helper (rather than\n * collapsed into `stripMllp`) so the two concerns — transform and emit —\n * stay testable in isolation, per CLAUDE.md guardrails.\n *\n * @example\n * ```ts\n * import { stripMllp, emitIfFramed } from \"@cosyte/hl7\";\n * const result = stripMllp(raw);\n * emitIfFramed(result, (w) => console.warn(w.code), { segmentIndex: 0 });\n * ```\n */\nexport function emitIfFramed(\n result: StripMllpResult,\n emit: (warning: Hl7ParseWarning) => void,\n position: Hl7Position,\n): void {\n if (result.wasFramed) {\n emit(mllpFramingStripped(position));\n }\n}\n","/**\n * HL7 v2 **Table 0211 (Alternate Character Sets)** resolution for the parser's\n * `Buffer`-decode stage (Phase O). Mirrors the frozen read-only registries\n * `KNOWN_SEGMENTS` / `KNOWN_CODING_SYSTEMS`: a single source of truth mapping an\n * MSH-18 character-set code to how the parser treats it — **decode** (single-byte\n * ISO-8859 family + Unicode UTF-8) or **preserve-verbatim** (the multibyte /\n * ISO-2022-switched East-Asian sets and UTF-16/32, which HL7 renders through\n * stateful `\\Mxxyyzz\\` escapes this phase deliberately does not fully decode).\n *\n * Spec traceability: HL7 v2 Chapter 2, **MSH-18** (item 00692) + **Table 0211**\n * (OID 2.16.840.1.113883.18.116). MSH-18 is **repeating** — the first occurrence\n * is the message's default encoding, later occurrences are alternates activated\n * mid-message by the §2.7.4 charset-switch escapes (`\\Cxxyy\\` single-byte,\n * `\\Mxxyyzz\\` multi-byte). A **blank** MSH-18 means 7-bit ASCII (the default).\n *\n * Fail-safe design: a set we do not decode is NEVER silently guessed as another\n * encoding. The caller preserves the raw bytes as a 1:1 `latin1` reading (every\n * byte 0x00..0xFF → U+0000..U+00FF) and emits a warning. For a **single-byte**\n * undecoded charset (an unrecognized label, or a recognized single-byte set) this\n * is byte-recoverable: the HL7 structural bytes (segment terminator CR, and the\n * `|^~\\&` delimiters) are unambiguous, so a field's content bytes survive and can\n * be re-decoded downstream via `Buffer.from(value, \"latin1\")`. For a **multibyte**\n * set (UTF-16/32, the East-Asian DBCS/ISO-2022 sets) a content byte can coincide\n * with a structural byte, so tokenization runs on raw bytes and framing is\n * best-effort, not byte-recoverable — which is exactly why decoding those sets is\n * deferred (see the parser's known-limitations). Because a recognized-but-undecoded\n * set and an unrecognized label both preserve bytes, the exact Table-0211 spelling\n * of the multibyte codes is not load-bearing for safety — only for which warning\n * (`UNSUPPORTED_CHARSET` vs `UNKNOWN_CHARSET`) fires.\n */\n\n/**\n * How the parser treats a resolved MSH-18 character set.\n *\n * - `decode` — decode the byte stream to text with {@link CharsetResolution.decoder}.\n * - `verbatim` — read the raw bytes as a 1:1 `latin1` mapping; do not decode\n * (byte-recoverable for single-byte content — see the module header).\n */\nexport type CharsetTreatment = \"decode\" | \"verbatim\";\n\n/**\n * The outcome of resolving an MSH-18 label (or `options.charset` override)\n * against Table 0211.\n */\nexport interface CharsetResolution {\n /**\n * The canonical Table-0211 code the label resolved to (e.g. `\"UTF-8\"`,\n * `\"8859/1\"`, `\"ISO IR87\"`). For an unrecognized label this is the input\n * trimmed + upper-cased, so it is still a stable key for comparison.\n */\n readonly canonical: string;\n /** Whether the parser decodes this set or preserves its bytes verbatim. */\n readonly treatment: CharsetTreatment;\n /**\n * The WHATWG `TextDecoder` label to decode with when `treatment === \"decode\"`.\n * Empty when `treatment === \"verbatim\"`.\n */\n readonly decoder: string;\n /**\n * `true` when the label is a recognized HL7 Table-0211 code (whether or not\n * the parser decodes it); `false` when the label is not in Table 0211.\n * Drives the warning code on the verbatim path: recognized-but-`verbatim`\n * → `UNSUPPORTED_CHARSET`, unrecognized → `UNKNOWN_CHARSET`.\n */\n readonly recognized: boolean;\n}\n\n/** A frozen Table-0211 registry entry. */\ninterface CharsetEntry {\n readonly canonical: string;\n readonly treatment: CharsetTreatment;\n readonly decoder: string;\n}\n\n/**\n * Normalize an MSH-18 label to a lookup key: trim, upper-case, and collapse\n * internal runs of whitespace to a single space so `\"unicode utf-8\"` and\n * `\"UNICODE UTF-8\"` resolve alike. HL7 codes are ASCII, so an ASCII-safe\n * upper-case is sufficient and locale-independent.\n *\n * @internal\n */\nfunction normalizeLabel(raw: string): string {\n return raw.trim().replace(/\\s+/gu, \" \").toUpperCase();\n}\n\n/** Build a decode entry. @internal */\nfunction decodeEntry(canonical: string, decoder: string): CharsetEntry {\n return { canonical, treatment: \"decode\", decoder };\n}\n\n/** Build a verbatim (recognized-but-not-decoded) entry. @internal */\nfunction verbatimEntry(canonical: string): CharsetEntry {\n return { canonical, treatment: \"verbatim\", decoder: \"\" };\n}\n\n/**\n * Assemble the frozen alias → entry table. Multiple aliases (HL7 spellings +\n * common `ISO-8859-N` synonyms) point at one canonical entry.\n *\n * @internal\n */\nfunction buildTable(): ReadonlyMap<string, CharsetEntry> {\n const table = new Map<string, CharsetEntry>();\n const add = (aliases: readonly string[], entry: CharsetEntry): void => {\n for (const alias of aliases) table.set(normalizeLabel(alias), entry);\n };\n\n // 7-bit ASCII (ISO IR6) — the Table-0211 default. Decoded as UTF-8: for\n // conformant 7-bit content the result is byte-identical, and it tolerates the\n // ubiquitous undeclared-UTF-8 feed without corruption (ASCII ⊂ UTF-8).\n add([\"ASCII\", \"US-ASCII\", \"ISO IR6\"], decodeEntry(\"ASCII\", \"utf-8\"));\n\n // Unicode UTF-8 and its HL7 spellings. `UNICODE` (bare) is the deprecated\n // pre-UTF-8 code that real feeds use to mean UTF-8.\n add([\"UTF-8\", \"UTF8\", \"UNICODE UTF-8\", \"UNICODE\"], decodeEntry(\"UTF-8\", \"utf-8\"));\n\n // ISO-8859-1 (Latin-1) — decoded via Node's `latin1`, which is the TRUE\n // ISO-8859-1 (every byte 0x00–0xFF maps 1:1, byte-exact, never fails). Node's\n // WHATWG `TextDecoder(\"iso-8859-1\")` is actually windows-1252 — it remaps the\n // C1 range (0x80 → €), so it is deliberately NOT used here.\n add([\"8859/1\", \"ISO-8859-1\", \"ISO 8859-1\", \"ISO8859-1\"], decodeEntry(\"8859/1\", \"latin1\"));\n\n // The rest of the single-byte ISO 8859 family that Node's ICU decodes\n // FAITHFULLY — i.e. the C1 range 0x80–0x9F maps to U+0080–U+009F (controls),\n // matching the true ISO-8859-N code page (audited empirically). Decoded\n // strictly (see normalizeBuffer): a byte genuinely undefined in the set fails\n // the decode and preserves verbatim rather than emitting a silent U+FFFD.\n //\n // 8859/9 and 8859/11 are DELIBERATELY EXCLUDED: Node/ICU aliases their labels\n // to windows-1254 / windows-874, which *define* the C1 range as typographic\n // characters (byte 0x80 → €), diverging from true ISO-8859-9/11. A strict\n // decode would NOT throw on those bytes — it would silently emit a wrong,\n // non-recoverable character — so they are preserved verbatim below instead of\n // mis-decoded. (8859/1 is handled byte-exactly above via `latin1`.)\n for (const n of [2, 3, 4, 5, 6, 7, 8, 10, 13, 14, 15, 16]) {\n add(\n [`8859/${n}`, `ISO-8859-${n}`, `ISO 8859-${n}`, `ISO8859-${n}`],\n decodeEntry(`8859/${n}`, `iso-8859-${n}`),\n );\n }\n // Recognized but NOT decoded — Node's ICU has no faithful decoder (windows\n // codepage alias remaps the C1 range); preserved verbatim (byte-recoverable)\n // rather than silently mis-decoded. See the note above.\n add([\"8859/9\", \"ISO-8859-9\", \"ISO 8859-9\", \"ISO8859-9\"], verbatimEntry(\"8859/9\"));\n add([\"8859/11\", \"ISO-8859-11\", \"ISO 8859-11\", \"ISO8859-11\"], verbatimEntry(\"8859/11\"));\n\n // Recognized Table-0211 multibyte / ISO-2022-switched East-Asian sets and\n // the wide Unicode transforms: recognized, but preserved verbatim this phase\n // (full stateful decoding is deferred — see the module header).\n add([\"ISO IR14\", \"JIS X 0201\"], verbatimEntry(\"ISO IR14\"));\n add([\"ISO IR87\", \"JIS X 0208\"], verbatimEntry(\"ISO IR87\"));\n add([\"ISO IR159\", \"JIS X 0212\"], verbatimEntry(\"ISO IR159\"));\n add([\"GB 18030-2000\", \"GB18030\", \"GB 18030\"], verbatimEntry(\"GB 18030-2000\"));\n add([\"KS X 1001\", \"KSX1001\", \"KS C 5601\"], verbatimEntry(\"KS X 1001\"));\n add([\"CNS 11643-1992\", \"CNS 11643\"], verbatimEntry(\"CNS 11643-1992\"));\n add([\"BIG-5\", \"BIG5\"], verbatimEntry(\"BIG-5\"));\n add([\"UNICODE UTF-16\", \"UTF-16\"], verbatimEntry(\"UNICODE UTF-16\"));\n add([\"UNICODE UTF-32\", \"UTF-32\"], verbatimEntry(\"UNICODE UTF-32\"));\n\n return table;\n}\n\n/**\n * The frozen HL7 v2 Table-0211 registry, keyed by normalized label. Read-only —\n * built once at module load, never mutated.\n */\nconst CHARSET_TABLE: ReadonlyMap<string, CharsetEntry> = buildTable();\n\n/**\n * The default resolution for a blank / absent MSH-18: **7-bit ASCII** per\n * Table 0211, decoded as its UTF-8 superset. Recognized, no warning.\n *\n * @internal\n */\nconst DEFAULT_RESOLUTION: CharsetResolution = Object.freeze({\n canonical: \"ASCII\",\n treatment: \"decode\",\n decoder: \"utf-8\",\n recognized: true,\n});\n\n/**\n * Resolve an MSH-18 label (or an `options.charset` override) to a\n * {@link CharsetResolution}. A blank / `undefined` label resolves to the ASCII\n * default. A recognized Table-0211 code returns its registry entry. An\n * unrecognized label resolves to a `verbatim`, `recognized: false` outcome so\n * the caller preserves bytes and emits `UNKNOWN_CHARSET`.\n *\n * @example\n * ```ts\n * import { resolveCharset } from \"@cosyte/hl7\";\n * resolveCharset(\"UNICODE UTF-8\"); // { canonical: \"UTF-8\", treatment: \"decode\", ... }\n * resolveCharset(\"ISO IR87\"); // { canonical: \"ISO IR87\", treatment: \"verbatim\", recognized: true }\n * resolveCharset(\"WINDOWS-1252\"); // { canonical: \"WINDOWS-1252\", treatment: \"verbatim\", recognized: false }\n * ```\n */\nexport function resolveCharset(raw: string | undefined): CharsetResolution {\n if (raw === undefined) return DEFAULT_RESOLUTION;\n const key = normalizeLabel(raw);\n if (key === \"\") return DEFAULT_RESOLUTION;\n const entry = CHARSET_TABLE.get(key);\n if (entry !== undefined) {\n return {\n canonical: entry.canonical,\n treatment: entry.treatment,\n decoder: entry.decoder,\n recognized: true,\n };\n }\n return { canonical: key, treatment: \"verbatim\", decoder: \"\", recognized: false };\n}\n\n/**\n * The canonical Table-0211 code for a label, for equality comparison (e.g. the\n * MSH-18-vs-`options.charset` `ENCODING_MISMATCH` check). Synonyms collapse to\n * one canonical string (`\"UNICODE UTF-8\"` and `\"UTF-8\"` → `\"UTF-8\"`), so a\n * synonym pair does not raise a false mismatch; an unrecognized label returns\n * its normalized form so two genuinely different labels still differ.\n *\n * @example\n * ```ts\n * import { canonicalCharset } from \"@cosyte/hl7\";\n * canonicalCharset(\"unicode utf-8\") === canonicalCharset(\"UTF-8\"); // true\n * ```\n */\nexport function canonicalCharset(raw: string): string {\n return resolveCharset(raw).canonical;\n}\n","/**\n * Input normalization stage for the `@cosyte/hl7` parser pipeline.\n * Normalizes mixed line endings (`\\r\\n`, `\\n`, `\\r`) to a single `\\r` terminator\n * and — for `Buffer` input — decodes bytes into a string using MSH-18 charset\n * resolution with a UTF-8 fallback.\n *\n * Per CONTEXT.md D-03 the canonical preprocessing order is:\n * 1. EMPTY_INPUT check (fatal)\n * 2. BOM strip (silent)\n * 3. MLLP strip\n * 4. Line-ending normalization (this module)\n *\n * Plan 06's `parseHL7` composition owns steps 1–3 explicitly so the ordering is\n * inspectable at the pipeline site. This module is a pure string/Buffer\n * transform that does NOT throw and does NOT strip BOM.\n */\n\nimport { resolveCharset } from \"./charset.js\";\nimport { unknownCharset, unsupportedCharset } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\n\n/**\n * Position attached to every charset warning: MSH (segment 0), field 18. The\n * message carries the charset code only — never a field value — so no PHI is\n * exposed.\n *\n * @internal\n */\nconst CHARSET_POSITION = { segmentIndex: 0, fieldIndex: 18 } as const;\n\n/**\n * Preserve a byte stream as a 1:1 `latin1` reading (every byte 0x00..0xFF →\n * U+0000..U+00FF) and normalize line endings for segment splitting. The\n * fail-safe for any charset the parser does not decode.\n *\n * Recoverability is exact for **single-byte** content: the HL7 structural bytes\n * (CR/LF terminators, `|^~\\&`) are unambiguous, so a field's content bytes\n * survive and re-encode via `Buffer.from(value, \"latin1\")`. For **multibyte**\n * content a code-unit byte can equal a structural byte (e.g. a UTF-16 `0x0D`);\n * line-ending normalization and segment splitting then act on it, so framing is\n * best-effort — the documented reason multibyte decode is deferred, not claimed.\n *\n * @internal\n */\nfunction preserveVerbatim(input: Buffer): string {\n return normalize(input.toString(\"latin1\"));\n}\n\n/**\n * Callback shape for warning emission during `normalizeBuffer`. Plan 06 wires\n * the real chokepoint (push onto `Hl7Message.warnings`, invoke `onWarning`,\n * escalate in strict mode). This type is internal to the parser modules.\n *\n * @internal\n */\ntype EmitFn = (warning: Hl7ParseWarning) => void;\n\n/**\n * Normalize line endings in an HL7 message string to a single `\\r` terminator.\n *\n * Converts `\\r\\n` and standalone `\\n` characters to `\\r`; existing `\\r`\n * characters are preserved. The replacement order matters: `\\r\\n` is handled\n * first so the sequence is not counted twice. Empty and whitespace-only input\n * is returned unchanged — the `EMPTY_INPUT` fatal is Plan 06's responsibility.\n * A leading UTF-8 BOM is preserved; BOM stripping is also Plan 06's job.\n *\n * @example\n * ```ts\n * import { normalize } from \"@cosyte/hl7\";\n * const clean = normalize(\"MSH|^~\\\\&|APP\\r\\nPID|1\\nEVN|A\");\n * // clean === \"MSH|^~\\\\&|APP\\rPID|1\\rEVN|A\"\n * ```\n */\nexport function normalize(input: string): string {\n return input.replace(/\\r\\n/g, \"\\r\").replace(/\\n/g, \"\\r\");\n}\n\n/**\n * Decode a `Buffer` of raw HL7 bytes into a string, then apply line-ending\n * normalization. Charset resolution runs through the frozen HL7 Table-0211\n * registry ({@link resolveCharset}):\n *\n * - `8859/1` (Latin-1) is decoded via `latin1` — byte-exact, never fails;\n * - the other faithfully-decodable sets (ASCII, `8859/2`–`8859/8`/`10`/`13`–`16`,\n * UTF-8) are decoded **strictly** (`fatal: true`); a byte invalid / undefined\n * for the declared set (or an ICU build lacking the label) falls through to\n * the verbatim fail-safe rather than emitting a silent `U+FFFD`. (`8859/9` and\n * `8859/11` are NOT decoded — Node's ICU aliases them to windows-1254/874,\n * which remap the C1 range — so they take the verbatim path below);\n * - a **recognized-but-not-decoded** set (the multibyte / ISO-2022 East-Asian\n * sets, UTF-16/32) preserves the bytes verbatim and emits `UNSUPPORTED_CHARSET`;\n * - an **unrecognized** label preserves the bytes verbatim and emits\n * `UNKNOWN_CHARSET`.\n *\n * The fail-safe never guesses an encoding and never silently corrupts: an\n * undecoded / un-decodable set is preserved as a `latin1` byte reading, not\n * replacement characters, so single-byte content stays byte-recoverable. A blank\n * / `undefined` charset is the ASCII default, decoded strictly as UTF-8 (a\n * superset that renders 7-bit content identically and handles the common\n * undeclared-UTF-8 feed); non-UTF-8 bytes under that default preserve verbatim +\n * warn rather than corrupt.\n *\n * Callers (Plan 06) remain responsible for the `EMPTY_INPUT` fatal check,\n * BOM stripping, and MLLP framing removal on the returned text.\n *\n * @example\n * ```ts\n * import { normalizeBuffer } from \"@cosyte/hl7\";\n * const text = normalizeBuffer(\n * Buffer.from(\"MSH|^~\\\\&|APP\\rPID|1\", \"utf-8\"),\n * \"UTF-8\",\n * (w) => console.warn(w.code),\n * );\n * ```\n */\nexport function normalizeBuffer(input: Buffer, charset: string | undefined, emit: EmitFn): string {\n const resolution = resolveCharset(charset);\n if (resolution.treatment === \"decode\") {\n if (resolution.decoder === \"latin1\") {\n // True ISO-8859-1: latin1 maps every byte losslessly and cannot fail.\n // (Node's `TextDecoder(\"iso-8859-1\")` is windows-1252 — wrong for the C1\n // range — so it is intentionally not used here.)\n return normalize(input.toString(\"latin1\"));\n }\n try {\n // STRICT decode (fatal: true): a byte that is invalid / undefined for the\n // declared set throws rather than silently becoming U+FFFD (irreversible\n // loss). On failure — malformed content, or an ICU build lacking the\n // label — we preserve the bytes verbatim + warn instead of emitting\n // replacement-char-corrupted text. Valid content still decodes; this is\n // NOT a wholesale wrong-encoding guess.\n const decoder = new TextDecoder(resolution.decoder, { fatal: true });\n return normalize(decoder.decode(input));\n } catch {\n emit(unsupportedCharset(CHARSET_POSITION, resolution.canonical));\n return preserveVerbatim(input);\n }\n }\n // Verbatim path: recognized-but-not-decoded → UNSUPPORTED_CHARSET;\n // unrecognized label → UNKNOWN_CHARSET.\n if (resolution.recognized) {\n emit(unsupportedCharset(CHARSET_POSITION, resolution.canonical));\n } else {\n emit(unknownCharset(CHARSET_POSITION, charset ?? \"\"));\n }\n return preserveVerbatim(input);\n}\n","/**\n * HL7 escape-sequence handling for the `@cosyte/hl7` parser pipeline\n * — expands reserved-delimiter escapes on parse (`unescape`) and re-escapes\n * them back when emitting spec-clean HL7 on serialize (`reescape`).\n *\n * The HL7 v2 spec reserves the delimiter characters (field, component,\n * repetition, escape, subcomponent, and the v2.7+ truncation char) plus the\n * newline shorthand `\\.br\\`. Whenever a sender needs one of those characters\n * to appear inside user data, it must escape it using the active escape\n * character (default `\\`).\n *\n * **Recognition vs decoding.** The HL7 spec defines four families of escape\n * sequences. We **decode** sequences whose meaning is byte-exact (delimiter\n * back-substitution, hex, newline, truncation char). We **recognize and\n * preserve verbatim** sequences whose intent is presentational or sender-\n * specific — decoding them would either lose information (formatting/charset)\n * or invent a rendering policy the spec leaves to the consumer. Either way,\n * a recognized standard sequence never emits `UNKNOWN_ESCAPE_SEQUENCE`;\n * that warning is reserved for genuinely-unknown bodies (`\\Z..\\`, garbage).\n *\n * Decoded sequences (consumed by `expandSequence`):\n * \\F\\ → enc.field (field separator)\n * \\S\\ → enc.component (component separator)\n * \\T\\ → enc.subcomponent (subcomponent separator)\n * \\R\\ → enc.repetition (repetition separator)\n * \\E\\ → enc.escape (escape character itself)\n * \\P\\ → enc.truncation ?? \"#\" (truncation char, HL7 v2.7+ §2.5.5.2)\n * \\.br\\ → \"\\n\" (newline shorthand)\n * \\X..\\ → hex decode (2 hex digits per byte; 0x00..0xFF code points)\n *\n * Recognized but preserved verbatim (no decoding, no warning):\n * \\H\\, \\N\\ highlight start / normal text (§2.7.1)\n * \\.sp\\, \\.in\\, \\.ti\\, \\.fi\\, formatting commands (§2.7.6, kept as\n * \\.nf\\, \\.ce\\ semantic sentinels for a renderer)\n * \\Cxxyy\\, \\Mxxyyzz\\ single- / multi-byte charset switch\n * (§2.7.4 — sender-local byte sequences;\n * decoding requires charset context\n * this module does not have)\n *\n * Genuinely unknown (still warns + preserve verbatim):\n * \\Z..\\ → vendor-specific. Profiles may register vendor handlers later.\n * anything else (garbage, unterminated)\n */\n\nimport type { EncodingCharacters, Hl7Position } from \"./types.js\";\nimport {\n unknownEscapeSequence,\n unterminatedEscapeSequence,\n type Hl7ParseWarning,\n} from \"./warnings.js\";\n\n/**\n * Expand HL7 escape sequences (`\\F\\`, `\\S\\`, `\\T\\`, `\\R\\`, `\\E\\`, `\\.br\\`,\n * `\\X..\\`, vendor-specific `\\Z..\\`) inside a field, component, or\n * subcomponent string. The escape delimiter comes from `enc.escape` (default\n * `\\`), so senders using a non-default escape character are handled\n * transparently.\n *\n * Unknown or malformed sequences are preserved VERBATIM in the output and\n * emit an `UNKNOWN_ESCAPE_SEQUENCE` warning via `emit`. Unterminated escapes\n * (an escape character with no closing partner before end-of-input) are also\n * preserved in full and warn once — the scan is strictly O(n) and cannot\n * infinite-loop on malformed input.\n *\n * @example\n * ```ts\n * import { unescape, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const warnings: Array<unknown> = [];\n * const out = unescape(\n * \"patient\\\\F\\\\name\\\\.br\\\\DOB\",\n * DEFAULT_ENCODING_CHARACTERS,\n * (w) => warnings.push(w),\n * { segmentIndex: 1, fieldIndex: 5 },\n * );\n * // out === \"patient|name\\nDOB\"\n * ```\n */\nexport function unescape(\n input: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n): string {\n const esc = enc.escape;\n if (!input.includes(esc)) return input;\n\n let out = \"\";\n let i = 0;\n while (i < input.length) {\n const ch = input.charAt(i);\n if (ch !== esc) {\n out += ch;\n i++;\n continue;\n }\n const close = input.indexOf(esc, i + 1);\n if (close === -1) {\n // Unterminated escape — preserve the rest verbatim, warn once, stop.\n // The warning carries NEITHER the tail content NOR its length (the\n // remainder is arbitrary field text, potentially PHI) — only the fact\n // and position.\n emit(unterminatedEscapeSequence(position));\n out += input.slice(i);\n break;\n }\n const seq = input.slice(i + 1, close);\n const expanded = expandSequence(seq, enc);\n if (expanded !== null) {\n out += expanded;\n } else if (isRecognizedPreservedEscape(seq)) {\n // Standard sequence we deliberately do not decode (formatting / highlight\n // / charset). Preserve verbatim so round-trip is exact; no warning.\n out += esc + seq + esc;\n } else {\n emit(unknownEscapeSequence(position, seq));\n out += esc + seq + esc;\n }\n i = close + 1;\n }\n return out;\n}\n\n/** Spec default truncation char per HL7 v2.7+ §2.5.5.2. */\nconst DEFAULT_TRUNCATION_CHAR = \"#\";\n\n/** Highlight and formatting escapes that we recognize-but-preserve. */\nconst RECOGNIZED_PRESERVED_SET: ReadonlySet<string> = new Set([\n \"H\", // begin highlighting (§2.7.1)\n \"N\", // normal text — end highlighting (§2.7.1)\n \".sp\", // vertical skip (§2.7.6)\n \".in\", // indent\n \".ti\", // temporary indent\n \".fi\", // begin word wrap\n \".nf\", // end word wrap\n \".ce\", // center next line\n]);\n\n/**\n * Returns true for a spec-defined escape body the parser recognizes but\n * deliberately does not decode — recognizing it suppresses the\n * `UNKNOWN_ESCAPE_SEQUENCE` warning while preserving the sequence verbatim\n * so the serializer round-trips it byte-for-byte. Covers HL7 v2 §2.7.1\n * highlight, §2.7.6 formatting commands, and §2.7.4 charset switches\n * (`\\Cxxyy\\` single-byte, `\\Mxxyyzz\\` multi-byte; xx/yy/zz are hex digit\n * pairs).\n *\n * @internal\n */\nfunction isRecognizedPreservedEscape(seq: string): boolean {\n if (RECOGNIZED_PRESERVED_SET.has(seq)) return true;\n // \\Cxxyy\\ — single-byte char set switch (2 hex byte pairs = 4 hex digits).\n if (seq.length === 5 && seq.charAt(0) === \"C\" && /^[0-9A-Fa-f]{4}$/u.test(seq.slice(1))) {\n return true;\n }\n // \\Mxxyyzz\\ — multi-byte char set switch (2 or 3 hex byte pairs = 4 or 6 digits).\n if (\n seq.charAt(0) === \"M\" &&\n (seq.length === 5 || seq.length === 7) &&\n /^[0-9A-Fa-f]+$/u.test(seq.slice(1))\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Expand a known HL7 escape body (the characters between the two escape\n * delimiters) to its decoded value. Returns `null` for any body this\n * function does not decode — `unescape` then routes the body through\n * `isRecognizedPreservedEscape` to decide warn-or-preserve.\n *\n * @internal\n */\nfunction expandSequence(seq: string, enc: EncodingCharacters): string | null {\n if (seq === \"F\") return enc.field;\n if (seq === \"S\") return enc.component;\n if (seq === \"T\") return enc.subcomponent;\n if (seq === \"R\") return enc.repetition;\n if (seq === \"E\") return enc.escape;\n // \\P\\ — truncation character (HL7 v2.7+ §2.5.5.2). Decodes to enc.truncation\n // when MSH-2 declared one (5-char form), otherwise the spec default `#`.\n if (seq === \"P\") return enc.truncation ?? DEFAULT_TRUNCATION_CHAR;\n if (seq === \".br\") return \"\\n\";\n if (seq.startsWith(\"X\")) {\n const hex = seq.slice(1);\n if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9A-Fa-f]+$/u.test(hex)) {\n return null;\n }\n let decoded = \"\";\n for (let j = 0; j < hex.length; j += 2) {\n const byte = parseInt(hex.slice(j, j + 2), 16);\n decoded += String.fromCharCode(byte);\n }\n return decoded;\n }\n // \\Z..\\ is vendor-specific; Phase 2 maintains no allow-list, so callers\n // receive `null` and emit the UNKNOWN_ESCAPE_SEQUENCE warning. Future\n // Phase 6 profiles can register their own vendor handlers.\n return null;\n}\n\n/**\n * Re-escape reserved characters back into their `\\X\\` forms so the serializer\n * can emit spec-clean HL7. This is the inverse of `unescape` for every\n * delimiter-bearing character; round-trip cleanliness\n * (`unescape(reescape(x, enc), enc, emit, pos) === x`) is a documented\n * property covered by tests.\n *\n * The characters re-escaped:\n * enc.escape → \\E\\\n * enc.field → \\F\\\n * enc.component → \\S\\\n * enc.subcomponent → \\T\\\n * enc.repetition → \\R\\\n * enc.truncation → \\P\\ (only when MSH-2 declared one, v2.7+)\n * \"\\n\" (LF) → \\.br\\\n * \"\\r\" (CR) → \\X0D\\ (a decoded CR is the HL7 segment separator;\n * emitting it raw would corrupt wire framing, so\n * it re-encodes to its hex escape — see below)\n *\n * **Lossy by construction for the non-delimiter escape families.** `reescape`\n * only knows about the reserved characters above — it cannot reconstruct a\n * recognize-and-preserve escape (`\\H\\`, formatting, charset, `\\Z..\\`) or the\n * original bytes of a hex escape (`\\X41\\` decoded to `A`; casing of `\\X0d\\`),\n * because those decode to ordinary characters that carry no \"I was an escape\"\n * marker. Byte-verbatim emit for those families is the serializer's job via\n * the `RawComponent.rawSubcomponents` overlay (see {@link escapeFidelityRaw});\n * `reescape` is the fallback for content that has no overlay (constructed\n * values, `Field`-level re-escapes).\n *\n * Iteration uses `for..of`, which walks Unicode code points (not UTF-16 code\n * units), so user-supplied content containing non-BMP characters round-trips\n * correctly without special surrogate-pair handling.\n *\n * @example\n * ```ts\n * import { reescape, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * reescape(\"Smith|John\", DEFAULT_ENCODING_CHARACTERS); // \"Smith\\\\F\\\\John\"\n * reescape(\"line1\\nline2\", DEFAULT_ENCODING_CHARACTERS); // \"line1\\\\.br\\\\line2\"\n * ```\n */\nexport function reescape(input: string, enc: EncodingCharacters): string {\n if (input.length === 0) return input;\n const trunc = enc.truncation;\n let out = \"\";\n for (const ch of input) {\n if (ch === enc.escape) out += enc.escape + \"E\" + enc.escape;\n else if (ch === enc.field) out += enc.escape + \"F\" + enc.escape;\n else if (ch === enc.component) out += enc.escape + \"S\" + enc.escape;\n else if (ch === enc.subcomponent) out += enc.escape + \"T\" + enc.escape;\n else if (ch === enc.repetition) out += enc.escape + \"R\" + enc.escape;\n // \\P\\ — only emitted when MSH-2 declared a truncation character (v2.7+);\n // for pre-v2.7 encodings the character has no reserved meaning and\n // round-trips as a literal.\n else if (trunc !== undefined && ch === trunc) out += enc.escape + \"P\" + enc.escape;\n else if (ch === \"\\n\") out += enc.escape + \".br\" + enc.escape;\n // A literal CR in decoded content (reachable via a spec-legal \\X0D\\ hex\n // escape on parse) is the HL7 segment separator — emitting it raw would\n // CORRUPT the wire framing (a phantom segment split mid-field, silently).\n // Re-emit it as its hex escape so the round-trip is stable and the\n // emitted message always stays structurally intact.\n else if (ch === \"\\r\") out += enc.escape + \"X0D\" + enc.escape;\n else out += ch;\n }\n return out;\n}\n\n/**\n * Decide the **escape-fidelity overlay** entry for one subcomponent: the\n * original wire bytes (`rawSub`) to emit verbatim, or `undefined` when the\n * decoded form already re-escapes back to those exact bytes.\n *\n * The rule is a single equality check — `reescape(decoded) === rawSub` — which\n * captures every family correctly by construction:\n * - **Delimiter escapes** (`\\F\\`→`|`, `\\E\\`→`\\`, `\\.br\\`→`\\n`, `\\X0D\\`→CR) all\n * re-escape back to their exact wire bytes, so they get **no overlay** and\n * ride the `reescape` fast path — no per-subcomponent memory cost.\n * - **Recognize-and-preserve escapes** (`\\H\\`, `\\N\\`, formatting, charset,\n * `\\Z..\\`) decode to a literal backslash-bearing string that `reescape`\n * would double-escape (`\\H\\` → `\\E\\H\\E\\`), so `reescape(decoded) !== rawSub`\n * and the overlay pins the original bytes.\n * - **Hex escapes** (`\\X41\\`→`A`, non-canonical casing `\\X0d\\`) decode away\n * their `\\X..\\` shape, so the overlay preserves the sender's exact bytes\n * (value/casing) rather than canonicalizing.\n *\n * Called once per escape-bearing subcomponent during tokenization; the\n * `rawSub.includes(enc.escape)` guard in the caller skips it entirely for the\n * common no-escape subcomponent, so this never runs on plain content.\n *\n * @internal\n */\nexport function escapeFidelityRaw(\n rawSub: string,\n decoded: string,\n enc: EncodingCharacters,\n): string | undefined {\n return reescape(decoded, enc) === rawSub ? undefined : rawSub;\n}\n","/**\n * Tokenizer stage for the `@cosyte/hl7` parser pipeline. Decomposes\n * an ordered list of segment strings into the nested positional tree that\n * `Hl7Message` holds — `RawSegment` -> `RawField` -> `RawRepetition` ->\n * `RawComponent` -> subcomponent strings. Honors custom encoding characters\n * so PARSE-02 (non-default delimiters) flows through downstream stages\n * without re-derivation.\n *\n * Adopts the unified HL7 1-indexed convention for ALL segments:\n * `fields[0]` is the segment-name / separator placeholder slot (never a\n * data field); `fields[N]` for N >= 1 is the HL7 N-th field. MSH: `fields[0]`\n * holds the field separator char (MSH-1), `fields[1]` holds the encoding\n * chars string (MSH-2). Non-MSH (PID, EVN, ZPI, ...): `fields[0]` holds the\n * segment name, `fields[1]` holds the HL7 first field (PID-1).\n *\n * Escape expansion (Phase 5 round-trip contract): each subcomponent is run\n * through `unescape()` during tokenization, so the raw tree holds DECODED\n * strings (e.g. `Smith|Jones`, not `Smith\\F\\Jones`). This is the exact\n * inverse of `reescape()` in `src/serialize/emit-field.ts`, which is how the\n * serializer produces spec-clean output and how SER-02 structural round-trip\n * equivalence holds: `parseHL7(msg.toString()).rawSegments` deeply equals\n * `msg.rawSegments`. `UNKNOWN_ESCAPE_SEQUENCE` warnings from `unescape`\n * propagate through the `emit` callback.\n *\n * Escape-fidelity overlay (HL7-ESC): `reescape` is a faithful inverse only for\n * the delimiter/newline escapes — recognize-and-preserve escapes (`\\H\\`,\n * charset, formatting, `\\Z..\\`) and hex escapes (`\\X41\\`) decode to plain\n * characters that would re-emit canonicalized (`\\H\\` → `\\E\\H\\E\\`; `\\X41\\` → `A`),\n * not byte-verbatim. So tokenization also records the **original wire bytes** of\n * exactly those subcomponents in `RawComponent.rawSubcomponents`, which the\n * serializer emits verbatim. The decoded `subcomponents` surface is unchanged;\n * only emit consults the overlay. The MSH-1 / MSH-2 positional\n * placeholders (`fields[0]`, `fields[1]`) are intentionally NOT unescaped —\n * they hold the literal delimiter / encoding chars and participate in\n * serialization via the D-06 special-case path, not via `emitField`.\n */\n\nimport { escapeFidelityRaw, unescape } from \"./escapes.js\";\nimport { fieldWhitespaceTrimmed } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type {\n EncodingCharacters,\n Hl7Position,\n RawComponent,\n RawField,\n RawRepetition,\n RawSegment,\n} from \"./types.js\";\n\n/**\n * Decompose an ordered list of segment strings into the raw positional tree\n * consumed by `Hl7Message`. Honors custom encoding characters from `enc`.\n * Empty field (`||`) vs HL7 explicit null (`\"\"`) are distinguished via\n * `RawField.isNull`.\n *\n * When `trimFields` is true and a field value had non-trivial leading or\n * trailing whitespace (i.e. whitespace around non-whitespace content), a\n * `FIELD_WHITESPACE_TRIMMED` warning is emitted via `emit`. All-whitespace\n * fields and fields without surrounding whitespace do not emit. Escape\n * sequence expansion is deferred to Plan 04's on-access escape stage.\n *\n * @example\n * ```ts\n * import { tokenize, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const tree = tokenize(\n * [\"MSH|^~\\\\&|APP\", \"PID|1||Doe^Jane\"],\n * DEFAULT_ENCODING_CHARACTERS,\n * () => {},\n * true,\n * );\n * // tree[1].name === \"PID\"\n * // tree[1].fields[3].repetitions[0].components[0].subcomponents[0] === \"Doe\"\n * ```\n */\nexport function tokenize(\n segments: readonly string[],\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n trimFields: boolean,\n): readonly RawSegment[] {\n const out: RawSegment[] = [];\n for (let sIdx = 0; sIdx < segments.length; sIdx++) {\n const segStr = segments[sIdx];\n if (segStr === undefined) continue;\n\n // Preserve empty middle segments (from consecutive \\r) as zero-field,\n // empty-name RawSegment so segmentIndex stays stable downstream.\n if (segStr.length === 0) {\n out.push({ name: \"\", fields: [] });\n continue;\n }\n\n const firstSepIdx = segStr.indexOf(enc.field);\n const name = firstSepIdx === -1 ? segStr : segStr.slice(0, firstSepIdx);\n const rest = firstSepIdx === -1 ? \"\" : segStr.slice(firstSepIdx + 1);\n\n if (name === \"MSH\") {\n out.push(tokenizeMshSegment(segStr, enc, emit, sIdx, trimFields));\n } else {\n const namePlaceholder: RawField = {\n repetitions: [{ components: [{ subcomponents: [name] }] }],\n isNull: false,\n };\n const dataFields =\n rest.length === 0 ? [] : splitAndTokenizeFields(rest, enc, emit, sIdx, 0, trimFields);\n out.push({ name, fields: [namePlaceholder, ...dataFields] });\n }\n }\n return out;\n}\n\n/**\n * Tokenize an MSH segment. MSH is the one segment where the field separator\n * is encoded in-band as MSH-1: `MSH|^~\\&|APP|...`. We synthesize `fields[0]`\n * as a single-component holding the separator char and `fields[1]` as a\n * single-component holding the raw MSH-2 encoding chars string; the\n * remainder (MSH-3, MSH-4, ...) is parsed by `splitAndTokenizeFields` with\n * `fieldStartOffset = 2` so the 1-indexed `fieldIndex` on emitted warnings\n * matches the HL7 position (MSH-3 emits `fieldIndex: 3`).\n *\n * @internal\n */\nfunction tokenizeMshSegment(\n segStr: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n sIdx: number,\n trimFields: boolean,\n): RawSegment {\n const msh1: RawField = {\n repetitions: [{ components: [{ subcomponents: [enc.field] }] }],\n isNull: false,\n };\n\n const sepAfterMsh2 = segStr.indexOf(enc.field, 4);\n const msh2RawEnd = sepAfterMsh2 === -1 ? segStr.length : sepAfterMsh2;\n const msh2Raw = segStr.slice(4, msh2RawEnd);\n const msh2: RawField = {\n repetitions: [{ components: [{ subcomponents: [msh2Raw] }] }],\n isNull: false,\n };\n\n const remainder = sepAfterMsh2 === -1 ? \"\" : segStr.slice(sepAfterMsh2 + 1);\n const tailFields =\n remainder.length === 0 ? [] : splitAndTokenizeFields(remainder, enc, emit, sIdx, 2, trimFields);\n return { name: \"MSH\", fields: [msh1, msh2, ...tailFields] };\n}\n\n/**\n * Split a segment's post-name field region into `RawField[]` using the\n * caller-supplied field-index offset so warning positions stay on the HL7\n * 1-indexed convention. Non-MSH callers pass `fieldStartOffset = 0` so the\n * first data field (PID-1) emits `fieldIndex: 1`; MSH callers pass\n * `fieldStartOffset = 2` so the first tail field (MSH-3) emits\n * `fieldIndex: 3`.\n *\n * The returned array is DATA-ONLY — the caller is responsible for\n * prepending the `fields[0]` name/separator placeholder so the unified\n * 1-indexed convention holds on the final `RawSegment.fields`.\n *\n * @internal\n */\nfunction splitAndTokenizeFields(\n region: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n sIdx: number,\n fieldStartOffset: number,\n trimFields: boolean,\n): RawField[] {\n const fields = region.split(enc.field);\n const out: RawField[] = [];\n for (let fIdx = 0; fIdx < fields.length; fIdx++) {\n const raw = fields[fIdx];\n if (raw === undefined) continue;\n out.push(\n tokenizeField(\n raw,\n enc,\n emit,\n { segmentIndex: sIdx, fieldIndex: fieldStartOffset + fIdx + 1 },\n trimFields,\n ),\n );\n }\n return out;\n}\n\n/**\n * Tokenize a single field string into a `RawField`. Handles the empty\n * (`\"\"`-the-JS-empty-string) vs explicit-null (`\"\"`-the-HL7-literal) split\n * per PARSE-06, then performs optional whitespace trim with warning\n * emission, then delegates repetition splitting.\n *\n * @internal\n */\nfunction tokenizeField(\n raw: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n trimFields: boolean,\n): RawField {\n if (raw === \"\") return { repetitions: [], isNull: false };\n if (raw === '\"\"') return { repetitions: [], isNull: true };\n\n let value = raw;\n if (trimFields) {\n const trimmed = raw.trim();\n if (trimmed.length > 0 && trimmed !== raw) {\n const trimStart = raw.length - raw.trimStart().length;\n const trimEnd = raw.length - raw.trimEnd().length;\n emit(fieldWhitespaceTrimmed(position, trimStart, trimEnd));\n value = trimmed;\n }\n }\n\n const reps = value.split(enc.repetition);\n const repetitions: RawRepetition[] = [];\n for (let rIdx = 0; rIdx < reps.length; rIdx++) {\n const rep = reps[rIdx];\n if (rep === undefined) continue;\n repetitions.push(\n tokenizeRepetition(rep, enc, emit, { ...position, repetitionIndex: rIdx + 1 }),\n );\n }\n return { repetitions, isNull: false };\n}\n\n/** @internal */\nfunction tokenizeRepetition(\n raw: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n): RawRepetition {\n const comps = raw.split(enc.component);\n const components: RawComponent[] = [];\n for (let cIdx = 0; cIdx < comps.length; cIdx++) {\n const c = comps[cIdx];\n if (c === undefined) continue;\n components.push(tokenizeComponent(c, enc, emit, { ...position, componentIndex: cIdx + 1 }));\n }\n return { components };\n}\n\n/**\n * Tokenize a single component into its subcomponents, running each\n * subcomponent string through `unescape` so the raw tree stores DECODED\n * values (inverse of `reescape` at emit time). This is load-bearing for\n * SER-02 structural round-trip equivalence — without it, the raw tree would\n * store literal `\\F\\` / `\\E\\` / `\\.br\\` sequences and emit would double-\n * escape them into `\\E\\F\\E\\` / etc.\n *\n * `UNKNOWN_ESCAPE_SEQUENCE` warnings from `unescape` propagate through the\n * `emit` callback with the full positional context (segment, field, rep,\n * component, subcomponent all 1-indexed).\n *\n * @internal\n */\nfunction tokenizeComponent(\n raw: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n): RawComponent {\n const subs = raw.split(enc.subcomponent);\n const decoded: string[] = [];\n // Escape-fidelity overlay (HL7-ESC): the original wire bytes for any\n // subcomponent whose decoded form does not re-escape back to those exact\n // bytes (recognize-and-preserve escapes like `\\H\\`; hex escapes like\n // `\\X41\\`). Stays `undefined`-per-entry for the common case, and the whole\n // array is dropped when nothing needs it — so a plain message's raw tree is\n // shaped exactly as before this overlay existed.\n let rawSubcomponents: (string | undefined)[] | undefined;\n for (let sIdx = 0; sIdx < subs.length; sIdx++) {\n const sub = subs[sIdx];\n if (sub === undefined) {\n decoded.push(\"\");\n continue;\n }\n const decodedSub = unescape(sub, enc, emit, { ...position, subcomponentIndex: sIdx + 1 });\n decoded.push(decodedSub);\n // Only escape-bearing subcomponents can ever need the overlay — the\n // `includes(enc.escape)` guard keeps this off the hot path for plain data.\n if (sub.includes(enc.escape)) {\n const fidelity = escapeFidelityRaw(sub, decodedSub, enc);\n if (fidelity !== undefined) {\n (rawSubcomponents ??= new Array<string | undefined>(subs.length).fill(undefined))[sIdx] =\n fidelity;\n }\n }\n }\n return rawSubcomponents === undefined\n ? { subcomponents: decoded }\n : { subcomponents: decoded, rawSubcomponents };\n}\n","/**\n * Message-type & structure awareness (roadmap Phase G) — a conservative\n * **misroute / truncation safety net**, NOT an abstract-message-syntax\n * validator.\n *\n * It answers one question per message: **\"for this trigger event, are the\n * core segment groups the spec marks Required actually present?\"** When an\n * expected group is entirely absent (e.g. an `ORU^R01` carrying no `OBR`/`OBX`\n * result group — the classic signature of a truncated or misrouted feed), the\n * parser emits a single additive Tier-2 `MISSING_EXPECTED_GROUP` warning. It\n * never throws, never refuses, never rewrites the message.\n *\n * Design constraints (all accuracy-driven, to guarantee ZERO spec\n * false-positives):\n *\n * - **Per trigger event, never per family.** The claim that an ADT family\n * shares one shape is false — events diverge by version and trigger. Every\n * definition keys on the (messageCode, triggerEvent) pair.\n * - **Required (R) anchors only.** A group is modelled only when its anchor\n * segment is genuinely Required by the v2.5.1 abstract syntax for that\n * event. Optional groups (e.g. PID in ORU, RXA in VXU, OBR in OML) are\n * deliberately excluded so a conformant-but-sparse message never warns.\n * - **Presence is liberal.** A group counts as present if ANY of its anchor\n * segments appears — the conservative direction (it suppresses a warning\n * rather than inventing one).\n * - **Unrecognized = silent.** A message whose type has no definition here\n * produces an unrecognized structure summary and zero structural warnings.\n *\n * Spec traceability: HL7 v2.5.1 — Ch. 3 (ADT), Ch. 4 (orders), Ch. 6\n * (financial — DFT), Ch. 7 (observation — ORU), Ch. 9 (MDM), Ch. 10\n * (scheduling — SIU), Ch. 2 (ACK), CDC IG (VXU). Per-entry sourcing lives in\n * `docs-content/spec-notes-structure.md`.\n *\n * Zero runtime deps — pure data + pure functions.\n */\n\n/**\n * One expected segment group for a recognized trigger event. The group is\n * considered **present** when at least one of its `anchorSegments` appears in\n * the parsed message; its total absence is what signals a truncated or\n * misrouted message.\n */\nexport interface ExpectedSegmentGroup {\n /** Human-readable group label, e.g. `\"result\"`, `\"patient\"`, `\"order\"`. */\n readonly name: string;\n /**\n * The segment name(s) whose presence proves this group is present. Only\n * segments the HL7 v2.5.1 abstract syntax marks **Required (R)** for the\n * owning trigger event appear here, so a conformant message can never lack\n * all of them.\n */\n readonly anchorSegments: readonly string[];\n}\n\n/**\n * The expected structure of one recognized message type, keyed on the\n * (messageCode, triggerEvent) pair. A definition with an empty `triggerEvents`\n * list matches on `messageCode` alone (used for `ACK`, which carries no\n * trigger event in MSH-9.2).\n */\nexport interface MessageStructureDefinition {\n /** MSH-9.1 message code, e.g. `\"ORU\"`. */\n readonly messageCode: string;\n /**\n * The MSH-9.2 trigger events this definition applies to, e.g. `[\"R01\"]`.\n * An empty list means \"match on message code alone\" (e.g. `ACK`).\n */\n readonly triggerEvents: readonly string[];\n /** The Required (R) segment groups expected for these events. */\n readonly expectedGroups: readonly ExpectedSegmentGroup[];\n}\n\n/**\n * The conservative, Required-only expected-group registry. Each entry's spec\n * source is recorded in `docs-content/spec-notes-structure.md`. Deliberately\n * narrow: it recognizes the common message types' **core Required groups\n * only** and is NOT a conformance validator. Frozen (data, not config).\n *\n * @example\n * ```ts\n * import { MESSAGE_STRUCTURE_DEFINITIONS } from \"@cosyte/hl7\";\n * const oru = MESSAGE_STRUCTURE_DEFINITIONS.find((d) => d.messageCode === \"ORU\");\n * console.log(oru?.expectedGroups[0]?.name); // \"result\"\n * ```\n */\nexport const MESSAGE_STRUCTURE_DEFINITIONS: readonly MessageStructureDefinition[] = Object.freeze([\n // ── ADT (Ch. 3): patient identification (PID) + visit (PV1) are Required\n // for these admit/transfer/discharge/register/update/cancel events.\n // EVN is intentionally excluded — real senders omit it freely, making it\n // a weak (false-positive-prone) signal.\n Object.freeze({\n messageCode: \"ADT\",\n triggerEvents: Object.freeze([\"A01\", \"A02\", \"A03\", \"A04\", \"A05\", \"A08\", \"A11\", \"A13\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n Object.freeze({ name: \"visit\", anchorSegments: Object.freeze([\"PV1\"]) }),\n ]),\n }),\n // ── ORU^R01 (Ch. 7): the OBR/OBX result group is the Required payload.\n // PID is excluded (the patient-result group's PID is R within the group,\n // but a result-only relay can legitimately omit it at the top — keep the\n // anchor on the result segments themselves, the true truncation signal).\n Object.freeze({\n messageCode: \"ORU\",\n triggerEvents: Object.freeze([\"R01\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"result\", anchorSegments: Object.freeze([\"OBR\", \"OBX\"]) }),\n ]),\n }),\n // ── Orders (Ch. 4): ORC is the Required common-order segment across the\n // order message family. OBR is excluded — it is Optional in several of\n // these (OML/OMG/OMI carry it inside an optional observation-request\n // group), so anchoring only on ORC avoids a false positive.\n Object.freeze({\n messageCode: \"ORM\",\n triggerEvents: Object.freeze([\"O01\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OML\",\n triggerEvents: Object.freeze([\"O21\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OMG\",\n triggerEvents: Object.freeze([\"O19\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OMP\",\n triggerEvents: Object.freeze([\"O09\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OMI\",\n triggerEvents: Object.freeze([\"O23\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n // ── SIU scheduling (Ch. 10): SCH (schedule activity) is Required for every\n // S12–S26 event. The patient group (PID) is Optional in the SIU abstract\n // syntax, so it is excluded.\n Object.freeze({\n messageCode: \"SIU\",\n triggerEvents: Object.freeze([\n \"S12\",\n \"S13\",\n \"S14\",\n \"S15\",\n \"S16\",\n \"S17\",\n \"S18\",\n \"S19\",\n \"S20\",\n \"S21\",\n \"S22\",\n \"S23\",\n \"S24\",\n \"S26\",\n ]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"schedule\", anchorSegments: Object.freeze([\"SCH\"]) }),\n ]),\n }),\n // ── MDM (Ch. 9): document management — PID + the TXA document header are\n // Required for T02 (original document) and T06 (document addendum).\n Object.freeze({\n messageCode: \"MDM\",\n triggerEvents: Object.freeze([\"T02\", \"T06\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n Object.freeze({ name: \"document\", anchorSegments: Object.freeze([\"TXA\"]) }),\n ]),\n }),\n // ── DFT^P03 (Ch. 6): financial transaction — PID + at least one FT1\n // financial-transaction segment are Required.\n Object.freeze({\n messageCode: \"DFT\",\n triggerEvents: Object.freeze([\"P03\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n Object.freeze({ name: \"financial\", anchorSegments: Object.freeze([\"FT1\"]) }),\n ]),\n }),\n // ── VXU^V04 (CDC IG): immunization update — PID is Required. RXA is\n // excluded: it lives in the Optional order group of the CDC IG, so a\n // query-shaped VXU with no administered vaccine must not warn.\n Object.freeze({\n messageCode: \"VXU\",\n triggerEvents: Object.freeze([\"V04\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n ]),\n }),\n // ── ACK (Ch. 2): a general acknowledgment — MSA (message acknowledgment) is\n // Required. Matched on message code alone (no trigger event in MSH-9.2).\n Object.freeze({\n messageCode: \"ACK\",\n triggerEvents: Object.freeze([]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"acknowledgment\", anchorSegments: Object.freeze([\"MSA\"]) }),\n ]),\n }),\n]);\n\n/**\n * The presence verdict for one expected group of a recognized message type.\n */\nexport interface StructureGroup {\n /** The group label from its `ExpectedSegmentGroup`, e.g. `\"result\"`. */\n readonly name: string;\n /** The anchor segment name(s) whose presence would satisfy this group. */\n readonly anchorSegments: readonly string[];\n /** `true` when at least one anchor segment is present in the message. */\n readonly present: boolean;\n}\n\n/**\n * The structure summary for a parsed message — the data behind\n * `Hl7Message.structure`. For an unrecognized type, `recognized` is `false`,\n * `expectedGroups` is empty, and `missingGroups` is empty (the safety net is\n * deliberately silent on types it does not model).\n */\nexport interface MessageStructure {\n /** `true` when a `MESSAGE_STRUCTURE_DEFINITIONS` entry matched the type. */\n readonly recognized: boolean;\n /** MSH-9.1 message code observed on the message (empty string if absent). */\n readonly messageCode: string;\n /** MSH-9.2 trigger event observed on the message (empty string if absent). */\n readonly triggerEvent: string;\n /** Per-expected-group presence verdicts (empty when unrecognized). */\n readonly expectedGroups: readonly StructureGroup[];\n /** Names of the expected groups that are entirely absent (the warnings). */\n readonly missingGroups: readonly string[];\n}\n\n/**\n * Find the structure definition for a (messageCode, triggerEvent) pair, or\n * `undefined` when the type is not modelled. A definition with an empty\n * `triggerEvents` list matches on message code alone.\n *\n * @internal\n */\nfunction findDefinition(\n messageCode: string,\n triggerEvent: string,\n): MessageStructureDefinition | undefined {\n for (const def of MESSAGE_STRUCTURE_DEFINITIONS) {\n if (def.messageCode !== messageCode) continue;\n if (def.triggerEvents.length === 0 || def.triggerEvents.includes(triggerEvent)) {\n return def;\n }\n }\n return undefined;\n}\n\n/**\n * Analyze a parsed message's structure against the conservative expected-group\n * registry. Pure: it takes the message code, trigger event, and the set of\n * segment names actually present, and returns a `MessageStructure` summary. It\n * decides nothing about whether to warn — the caller (parser) emits one\n * `MISSING_EXPECTED_GROUP` warning per name in `missingGroups`.\n *\n * @param messageCode - MSH-9.1 (e.g. `\"ORU\"`); empty string if absent.\n * @param triggerEvent - MSH-9.2 (e.g. `\"R01\"`); empty string if absent.\n * @param presentSegmentNames - the set of segment names present in the message.\n *\n * @example\n * ```ts\n * import { analyzeMessageStructure } from \"@cosyte/hl7\";\n * const s = analyzeMessageStructure(\"ORU\", \"R01\", new Set([\"MSH\", \"PID\"]));\n * console.log(s.recognized); // true\n * console.log(s.missingGroups); // [\"result\"] (no OBR/OBX)\n * ```\n */\nexport function analyzeMessageStructure(\n messageCode: string,\n triggerEvent: string,\n presentSegmentNames: ReadonlySet<string>,\n): MessageStructure {\n const def = findDefinition(messageCode, triggerEvent);\n if (def === undefined) {\n return Object.freeze({\n recognized: false,\n messageCode,\n triggerEvent,\n expectedGroups: Object.freeze([]),\n missingGroups: Object.freeze([]),\n });\n }\n\n const groups: StructureGroup[] = [];\n const missing: string[] = [];\n for (const expected of def.expectedGroups) {\n const present = expected.anchorSegments.some((name) => presentSegmentNames.has(name));\n groups.push(\n Object.freeze({\n name: expected.name,\n anchorSegments: expected.anchorSegments,\n present,\n }),\n );\n if (!present) missing.push(expected.name);\n }\n\n return Object.freeze({\n recognized: true,\n messageCode,\n triggerEvent,\n expectedGroups: Object.freeze(groups),\n missingGroups: Object.freeze(missing),\n });\n}\n","/**\n * Dot-path tokenizer and resolver for the `@cosyte/hl7` structural\n * model. Parses strings like `PID.5.1`, `OBX[2].5`, `PID.3[0].1` into a\n * discriminated-token descriptor, then resolves that descriptor against a\n * `readonly RawSegment[]` tree to produce the decoded leaf string (or\n * `undefined` on missing path). Zero runtime deps — a hand-rolled linear scan\n * (analog: `src/parser/dates.ts::matchTokenFormat`).\n *\n * Indexing conventions (locked in Phase 3 CONTEXT.md):\n * - `[N]` is ALWAYS 0-indexed — applies to segment repeats AND field repeats (D-01).\n * - Dot-numbers are ALWAYS 1-indexed — matches HL7 spec and Phase 2's 1-indexed\n * `RawSegment.fields` (D-02). `PID.5` → `fields[5]`.\n * - MSH.1 / MSH.2 are the separator char and encoding-chars string, both\n * stored at `fields[0]` / `fields[1]` by Phase 2 tokenize.ts (D-05).\n * - Missing subcomponent on a single-sub component returns the component\n * string (depth-collapse, D-04).\n * - Leaf reads return the subcomponent verbatim: the tokenizer (parser-02)\n * already unescaped it once on parse, so the stored value is decoded and a\n * second `unescape` here would double-decode it (HL7-VALUE-REDECODE).\n */\n\nimport type { EncodingCharacters, RawSegment } from \"../parser/types.js\";\n\n/**\n * Parsed representation of a dot-path string. Produced by `parsePath`,\n * consumed by `resolvePath`. All numeric indices are normalized to the\n * internal convention (segmentIndex = 0-based occurrence, fieldIndex =\n * 1-based HL7 field number, repetitionIndex = 0-based rep, componentIndex\n * and subcomponentIndex = 1-based HL7 positions).\n *\n * @example\n * ```ts\n * import { parsePath } from \"@cosyte/hl7\";\n * parsePath(\"OBX[2].5.1\");\n * // { segmentType: \"OBX\", segmentIndex: 2, fieldIndex: 5,\n * // repetitionIndex: 0, componentIndex: 1 }\n * ```\n */\nexport interface DotPath {\n /** 3-char segment identifier (e.g. `\"PID\"`, `\"OBX\"`, `\"ZPI\"`). */\n readonly segmentType: string;\n /** 0-based occurrence of this segment type in the message. */\n readonly segmentIndex: number;\n /** 1-based HL7 field number; maps to `RawSegment.fields[fieldIndex]`. */\n readonly fieldIndex: number;\n /** 0-based repetition index; defaults to 0 when `[N]` is omitted. */\n readonly repetitionIndex?: number;\n /** 1-based HL7 component position (within a repetition). */\n readonly componentIndex?: number;\n /** 1-based HL7 subcomponent position (within a component). */\n readonly subcomponentIndex?: number;\n}\n\n/** Mutable local view for building a `DotPath` with `exactOptionalPropertyTypes` discipline. @internal */\ninterface MutableDotPath {\n segmentType: string;\n segmentIndex: number;\n fieldIndex: number;\n repetitionIndex?: number;\n componentIndex?: number;\n subcomponentIndex?: number;\n}\n\n/** Segment-name shape — `[A-Z][A-Z0-9]{2}` (D-19 symmetry with addSegment). Matches standard HL7 v2 segment names (PID, PV1, OBX, NK1, DG1, IN1…) and Z-segment customs (ZPI, ZX1…). @internal */\nconst SEGMENT_NAME_RE = /^[A-Z][A-Z0-9]{2}$/u;\n\n/**\n * Parse an HL7 dot-path string into a `DotPath` descriptor. Accepts shapes\n * like `SEG`, `SEG[n]`, `SEG.N`, `SEG.N[r]`, `SEG.N.C`, `SEG.N.C.S`, and all\n * combinations up to `SEG[n].N[r].C.S`. Throws `TypeError` with the offending\n * path string on any malformed input.\n *\n * @example\n * ```ts\n * import { parsePath } from \"@cosyte/hl7\";\n * parsePath(\"PID.5.1\"); // { segmentType: \"PID\", segmentIndex: 0, fieldIndex: 5, componentIndex: 1 }\n * parsePath(\"OBX[2].5\"); // { segmentType: \"OBX\", segmentIndex: 2, fieldIndex: 5 }\n * parsePath(\"PID.3[1].1\"); // { segmentType: \"PID\", segmentIndex: 0, fieldIndex: 3, repetitionIndex: 1, componentIndex: 1 }\n * ```\n */\nexport function parsePath(path: string): DotPath {\n if (path.length === 0) {\n throw new TypeError(`Invalid HL7 dot-path: \"\" (empty).`);\n }\n\n // 1. Segment name — must be 3 chars matching [A-Z][A-Z0-9]{2}.\n if (path.length < 3) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (segment name too short).`);\n }\n const segmentType = path.slice(0, 3);\n if (!SEGMENT_NAME_RE.test(segmentType)) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (segment name must match [A-Z][A-Z0-9]{2}).`,\n );\n }\n let i = 3;\n\n const out: MutableDotPath = {\n segmentType,\n segmentIndex: 0,\n fieldIndex: 0,\n };\n\n // 2. Optional [n] segment occurrence.\n if (i < path.length && path.charAt(i) === \"[\") {\n const { value, next } = readBracket(path, i);\n out.segmentIndex = value;\n i = next;\n }\n\n // If the path ends here, the caller only asked for a segment — the\n // resolver can't produce a string value from a segment-only DotPath,\n // but we accept the shape so callers can probe structure.\n if (i === path.length) {\n // fieldIndex defaults to 0 — sentinel meaning \"no field component\".\n return freezeDotPath(out);\n }\n\n // 3. Expect `.` then a field number (1-indexed), plus optional `[r]`.\n if (path.charAt(i) !== \".\") {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (expected '.' after segment at position ${String(i)}).`,\n );\n }\n i += 1;\n if (i === path.length) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (trailing dot).`);\n }\n {\n const { value, next } = readDigits(path, i);\n out.fieldIndex = value;\n i = next;\n }\n if (i < path.length && path.charAt(i) === \"[\") {\n const { value, next } = readBracket(path, i);\n out.repetitionIndex = value;\n i = next;\n }\n\n // 4. Optional `.C` component (1-indexed).\n if (i < path.length) {\n if (path.charAt(i) !== \".\") {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (unexpected '${path.charAt(i)}' at position ${String(i)}).`,\n );\n }\n i += 1;\n if (i === path.length) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (trailing dot).`);\n }\n const { value, next } = readDigits(path, i);\n out.componentIndex = value;\n i = next;\n }\n\n // 5. Optional `.S` subcomponent (1-indexed).\n if (i < path.length) {\n if (path.charAt(i) !== \".\") {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (unexpected '${path.charAt(i)}' at position ${String(i)}).`,\n );\n }\n i += 1;\n if (i === path.length) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (trailing dot).`);\n }\n const { value, next } = readDigits(path, i);\n out.subcomponentIndex = value;\n i = next;\n }\n\n // 6. Any trailing content → malformed (e.g. `PID.5.1.1.1`, `PID.5xyz`).\n if (i !== path.length) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (trailing content at position ${String(i)} — too deep or malformed).`,\n );\n }\n\n return freezeDotPath(out);\n}\n\n/**\n * Resolve a dot-path string against a raw segment tree to its decoded\n * leaf value. Returns `undefined` whenever the path does not resolve (missing\n * segment, out-of-range field/component/subcomponent/repetition), and never\n * throws on a missing value. Throws `TypeError` only when `path` itself is\n * malformed — callers relying on \"never throws\" should pre-validate or wrap\n * in try/catch.\n *\n * @example\n * ```ts\n * import { parseHL7, resolvePath } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * resolvePath(\"PID.5.1\", msg.rawSegments, msg.encodingCharacters); // \"Smith\"\n * resolvePath(\"NOT.9\", msg.rawSegments, msg.encodingCharacters); // undefined\n * ```\n */\nexport function resolvePath(\n path: string,\n segments: readonly RawSegment[],\n _enc: EncodingCharacters,\n): string | undefined {\n const parsed = parsePath(path);\n\n // A segment-only path (no field specified) has no string value.\n if (parsed.fieldIndex === 0) return undefined;\n\n const found = findSegment(segments, parsed.segmentType, parsed.segmentIndex);\n if (found === undefined) return undefined;\n\n const { seg } = found;\n\n // MSH indexing is offset by -1 relative to the internal `fields[]` array:\n // Phase 2 tokenize placed the field-separator char at `fields[0]` and the\n // encoding-chars string at `fields[1]`, so MSH-1 → fields[0], MSH-2 →\n // fields[1], MSH-3 → fields[2], ..., MSH-12 → fields[11]. All other\n // segments use a straight 1:1 mapping (PID.5 → fields[5]) because\n // `fields[0]` is the segment-name placeholder (D-02, D-05 in\n // 03-CONTEXT.md; verified by test/parser-tokenize.test.ts:29-36).\n const rawFieldIndex = parsed.segmentType === \"MSH\" ? parsed.fieldIndex - 1 : parsed.fieldIndex;\n const field = seg.fields[rawFieldIndex];\n if (field === undefined) return undefined;\n\n const repIndex = parsed.repetitionIndex ?? 0;\n const rep = field.repetitions[repIndex];\n if (rep === undefined) return undefined;\n\n const compIndex = (parsed.componentIndex ?? 1) - 1;\n const comp = rep.components[compIndex];\n if (comp === undefined) return undefined;\n\n const subIndex = (parsed.subcomponentIndex ?? 1) - 1;\n const sub = comp.subcomponents[subIndex];\n\n if (sub !== undefined) {\n // The tokenizer already unescaped every subcomponent on parse (parser-02),\n // so the stored value is decoded — return it directly. A second unescape\n // would double-decode a value whose own bytes look like an escape (wire\n // `\\E\\F\\E\\` → decoded `\\F\\`, which a second pass would wrongly turn into\n // `|`). Emit fidelity is handled separately by the raw overlay (HL7-ESC).\n return sub;\n }\n\n // D-04 depth-collapse: when the caller asked for subcomponent 1 and\n // the component has exactly one subcomponent, returning\n // `comp.subcomponents[0]` already covered that case above. The edge\n // case here is when `subIndex > subcomponents.length - 1`: we fall\n // through to `undefined`. No additional branch needed.\n return undefined;\n}\n\n/**\n * Locate the `occurrence`-th segment of `segmentType` in document order.\n * Returns the matched `RawSegment`.\n *\n * @internal\n */\nfunction findSegment(\n segments: readonly RawSegment[],\n segmentType: string,\n occurrence: number,\n): { readonly seg: RawSegment } | undefined {\n let seen = 0;\n for (const s of segments) {\n if (s === undefined) continue;\n if (s.name === segmentType) {\n if (seen === occurrence) return { seg: s };\n seen++;\n }\n }\n return undefined;\n}\n\n/**\n * Consume a run of ASCII digits from `path` starting at `start`. Returns the\n * parsed non-negative integer and the next cursor position. Throws\n * `TypeError` when `path[start]` is not a digit (e.g. after a trailing dot\n * with no number, or a negative sign).\n *\n * @internal\n */\nfunction readDigits(path: string, start: number): { value: number; next: number } {\n let j = start;\n while (j < path.length) {\n const ch = path.charCodeAt(j);\n if (ch < 0x30 || ch > 0x39) break;\n j += 1;\n }\n if (j === start) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (expected digit at position ${String(start)}).`,\n );\n }\n const slice = path.slice(start, j);\n // Safe: we just verified every char is 0-9.\n return { value: parseInt(slice, 10), next: j };\n}\n\n/**\n * Consume a `[N]` bracket expression from `path` starting at `start` (which\n * must be the `[`). Returns the non-negative integer and the next cursor\n * position. Throws `TypeError` on empty brackets, non-digit content, missing\n * close bracket, or negative index.\n *\n * @internal\n */\nfunction readBracket(path: string, start: number): { value: number; next: number } {\n // Caller guarantees path.charAt(start) === \"[\"\n const close = path.indexOf(\"]\", start + 1);\n if (close === -1) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (unclosed '[' at position ${String(start)}).`,\n );\n }\n const inner = path.slice(start + 1, close);\n if (inner.length === 0) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (empty brackets).`);\n }\n if (!/^\\d+$/u.test(inner)) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (bracket content \"${inner}\" is not a non-negative integer).`,\n );\n }\n return { value: parseInt(inner, 10), next: close + 1 };\n}\n\n/**\n * Return a `DotPath` from a mutable builder, honoring\n * `exactOptionalPropertyTypes` — optional keys are only present on the\n * returned object when their builder value is defined.\n *\n * @internal\n */\nfunction freezeDotPath(m: MutableDotPath): DotPath {\n const base: {\n segmentType: string;\n segmentIndex: number;\n fieldIndex: number;\n repetitionIndex?: number;\n componentIndex?: number;\n subcomponentIndex?: number;\n } = {\n segmentType: m.segmentType,\n segmentIndex: m.segmentIndex,\n fieldIndex: m.fieldIndex,\n };\n if (m.repetitionIndex !== undefined) base.repetitionIndex = m.repetitionIndex;\n if (m.componentIndex !== undefined) base.componentIndex = m.componentIndex;\n if (m.subcomponentIndex !== undefined) base.subcomponentIndex = m.subcomponentIndex;\n return base;\n}\n","/**\n * HL7 emit primitives for the `@cosyte/hl7` serializer pipeline —\n * walks a `RawField` / `RawSegment` tree and produces spec-clean HL7 text\n * by joining repetitions, components, and subcomponents with the active\n * delimiters and re-escaping user content via `reescape`.\n *\n * Decisions honored:\n * - D-02: trailing empty components and subcomponents are stripped;\n * `RawField.isNull === true` is preserved as the two-character literal `\"\"`.\n * - D-04: a subcomponent with no fidelity overlay passes through\n * `reescape(sub, enc)` — the 5 active delimiters + `\\n` (via `\\.br\\`) + a\n * decoded CR (via `\\X0D\\`) are re-escaped; other already-decoded text passes\n * through as plain characters. A subcomponent whose parse recorded original\n * wire bytes in `RawComponent.rawSubcomponents` (HL7-ESC — a recognize-and-\n * preserve escape like `\\H\\`/`\\Z..\\`, or a hex escape like `\\X41\\`) is\n * emitted from that overlay **verbatim**, so those families round-trip\n * byte-for-byte instead of canonicalizing.\n * - D-06 guard: `emitSegment` throws when called with an MSH segment —\n * MSH must be routed through `to-string.ts`'s special-case path, which\n * inlines MSH-1 and MSH-2 instead of running them through `emitField`\n * (running MSH-2 through `emitField` would re-escape the encoding chars\n * and produce garbage). The throw is a deliberate deviation from D-07\n * purity — it catches programmer misuse at the call site instead of\n * silently corrupting wire output.\n * - D-07: pure for all non-MSH inputs — never warns, never throws.\n *\n * Not part of the public API (no re-export from `src/index.ts`). Phase 6\n * profile hooks may compose around `emitSegment` / `emitField`.\n * @internal\n */\n\nimport { reescape } from \"../parser/escapes.js\";\nimport type { EncodingCharacters, RawField, RawRepetition, RawSegment } from \"../parser/types.js\";\n\n/**\n * Emit a single HL7 field as its spec-clean string fragment. Joins\n * repetitions with `enc.repetition`; each repetition renders its\n * components (joined with `enc.component`), each component renders its\n * subcomponents (joined with `enc.subcomponent`), and each subcomponent\n * runs through `reescape` (D-04).\n *\n * D-02 rules:\n * - `field.isNull === true` returns the two-character string `\"\"` (literal\n * quote-quote — HL7 explicit null), regardless of repetitions content.\n * - Trailing empty subcomponents inside a component are stripped.\n * - Trailing empty components inside a repetition are stripped.\n * - A field with zero repetitions renders as the empty string.\n *\n * @internal\n */\nexport function emitField(field: RawField, enc: EncodingCharacters): string {\n if (field.isNull) return '\"\"';\n if (field.repetitions.length === 0) return \"\";\n const repStrings: string[] = [];\n for (const rep of field.repetitions) {\n repStrings.push(emitRepetition(rep, enc));\n }\n return repStrings.join(enc.repetition);\n}\n\n/** @internal */\nfunction emitRepetition(rep: RawRepetition, enc: EncodingCharacters): string {\n const compStrings: string[] = [];\n for (const comp of rep.components) {\n const overlay = comp.rawSubcomponents;\n const subStrings: string[] = [];\n for (let i = 0; i < comp.subcomponents.length; i++) {\n // Escape-fidelity overlay (HL7-ESC): when the tokenizer recorded the\n // subcomponent's original wire bytes (a preserve-or-hex escape whose\n // decoded form does not re-escape byte-verbatim), emit them verbatim —\n // otherwise re-escape the decoded value. Delimiter escapes have no\n // overlay and take the reescape path, exactly as before.\n const raw = overlay?.[i];\n subStrings.push(raw ?? reescape(comp.subcomponents[i] ?? \"\", enc));\n }\n // D-02 trailing-empty strip at subcomponent level.\n while (subStrings.length > 0 && subStrings[subStrings.length - 1] === \"\") {\n subStrings.pop();\n }\n compStrings.push(subStrings.join(enc.subcomponent));\n }\n // D-02 trailing-empty strip at component level.\n while (compStrings.length > 0 && compStrings[compStrings.length - 1] === \"\") {\n compStrings.pop();\n }\n return compStrings.join(enc.component);\n}\n\n/**\n * Emit a single non-MSH HL7 segment as its spec-clean string fragment:\n * `<seg.name>` + `enc.field` + `<fields[1..N] joined by enc.field>`.\n *\n * **IMPORTANT — MSH guard:** If `seg.name === \"MSH\"` this function\n * THROWS. MSH requires D-06's special-case emission (MSH-1 = single\n * delimiter char, MSH-2 = 4 literal encoding chars — neither is routed\n * through `emitField`, because running MSH-2 through `emitField` would\n * re-escape the encoding chars and produce garbage output). The only\n * correct caller for MSH is `to-string.ts::emitMessage`, which inlines\n * MSH-1/MSH-2 before handing MSH-3..N off to `emitField`. This guard\n * is a deliberate deviation from D-07 \"never throws\" — it catches\n * programmer misuse loudly at the call site rather than silently\n * corrupting wire output.\n *\n * For non-MSH segments (PID, OBX, etc.) this function is pure: it\n * skips `fields[0]` (name placeholder) and joins `fields[1..N]` via\n * `emitField` with `enc.field` separators.\n *\n * @internal\n */\nexport function emitSegment(seg: RawSegment, enc: EncodingCharacters): string {\n if (seg.name === \"MSH\") {\n throw new Error(\n \"emitSegment: MSH must be routed through to-string.ts's MSH path per D-06 \" +\n \"(special-case MSH-1/MSH-2 encoding-char emission). Running MSH through \" +\n \"emitSegment would re-escape the encoding chars and produce garbage output.\",\n );\n }\n const parts: string[] = [seg.name];\n for (let i = 1; i < seg.fields.length; i++) {\n const f = seg.fields[i];\n parts.push(f === undefined ? \"\" : emitField(f, enc));\n }\n return parts.join(enc.field);\n}\n","/**\n * Internal helpers shared across the 10 composite parsers (XPN, XAD, CX, CWE,\n * CE, XTN, PL, TS, NM, HD). Centralizes the \"read subcomponent, return undefined\n * on absent\" pattern so composites stay short and every composite handles\n * missing/empty components identically.\n *\n * Subcomponents are returned VERBATIM: the tokenizer (parser-02) already\n * unescaped each one on parse, so the stored value is decoded — a second\n * `unescape` here would double-decode a value whose own bytes look like an\n * escape (HL7-VALUE-REDECODE). The `enc` params are retained for signature\n * uniformity across the composite read path.\n *\n * Not part of the public API — never re-exported from `src/index.ts`.\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\n/**\n * Read `subcomponents[index]` from a component and return it (already decoded\n * by the tokenizer — see the module header). Returns `undefined` when:\n * - `component` is `undefined` (missing component).\n * - `index` is out of range.\n * - the subcomponent is the empty string `\"\"`.\n *\n * The empty-string → undefined mapping is deliberate: composite interfaces\n * use OPTIONAL fields, which must be OMITTED when absent\n * (exactOptionalPropertyTypes). Callers use the `undefined` return as the\n * signal to skip assignment.\n *\n * @internal\n */\nexport function readSubcomponent(\n component: RawComponent | undefined,\n index: number,\n _enc: EncodingCharacters,\n): string | undefined {\n if (component === undefined) return undefined;\n const sub = component.subcomponents[index];\n if (sub === undefined || sub === \"\") return undefined;\n // The tokenizer already unescaped every subcomponent on parse (parser-02), so\n // the stored value is decoded — return it directly. A second unescape would\n // double-decode a value whose own bytes look like an escape (wire `\\E\\F\\E\\` →\n // decoded `\\F\\`, which a second pass would wrongly turn into `|`). Emit\n // fidelity is handled separately by the raw overlay (HL7-ESC). `_enc` is\n // retained for signature uniformity across the composite read helpers.\n return sub;\n}\n\n/**\n * Read the first subcomponent of `components[index]` and return it (already\n * decoded by the tokenizer). Shorthand for\n * `readSubcomponent(rep.components[index], 0, enc)`. Most composite fields\n * are single-subcomponent values — this helper keeps composite parsers\n * declarative.\n *\n * @internal\n */\nexport function readComponent(\n rep: RawRepetition,\n index: number,\n enc: EncodingCharacters,\n): string | undefined {\n return readSubcomponent(rep.components[index], 0, enc);\n}\n\n/**\n * Read every component at or beyond `fromIndex` — the components a fixed-shape\n * composite parser does NOT model — so a coded element that grew across HL7\n * versions (e.g. the v2.7 CWE second-alternate triplet + coding-system OIDs at\n * components 10–22) is never silently truncated. Each entry is the\n * first-subcomponent value (already decoded), positionally aligned: an absent\n * interior component is preserved as `\"\"` so a caller can map an index back to\n * its HL7 component number (`fromIndex + i`).\n *\n * Trailing empties are stripped (D-02 parity), and the whole result is\n * `undefined` when there is nothing beyond `fromIndex` or every extra component\n * is empty — so the optional `extraComponents` key is OMITTED rather than set\n * to an empty array (exactOptionalPropertyTypes). The returned array is frozen.\n *\n * @internal\n */\nexport function readExtraComponents(\n rep: RawRepetition,\n fromIndex: number,\n enc: EncodingCharacters,\n): readonly string[] | undefined {\n const total = rep.components.length;\n if (total <= fromIndex) return undefined;\n\n const collected: string[] = [];\n let lastContentAt = -1;\n for (let i = fromIndex; i < total; i++) {\n const value = readComponent(rep, i, enc);\n if (value !== undefined) {\n lastContentAt = collected.length;\n collected.push(value);\n } else {\n collected.push(\"\");\n }\n }\n\n if (lastContentAt === -1) return undefined;\n return Object.freeze(collected.slice(0, lastContentAt + 1));\n}\n","/**\n * CE — HL7 v2 Coded Element composite. 6-component coded-element shape\n * parsed from a `RawRepetition` on demand by `Field.asCe()` (wired in Plan\n * 04). Fields are OMITTED when absent (exactOptionalPropertyTypes) — NEVER\n * set to `undefined`.\n *\n * CE is the older, simpler sibling of CWE — 6 components, no version ids,\n * no originalText. Still common in OBX.3 and similar observation-identifier\n * slots on older messages. CE was deprecated at HL7 v2.5 and withdrawn at\n * v2.6 in favor of CWE; the two are read uniformly here — reading a\n * CWE-shaped value through `asCe()` preserves components 7+ on\n * `extraComponents` rather than dropping them, so neither accessor is lossy.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent, readExtraComponents } from \"./_shared.js\";\n\n/**\n * HL7 v2 Coded Element (CE) — coded element per HL7 Chapter 2. All 6\n * components are optional. Fields are OMITTED when the underlying component\n * is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. identifier (e.g. \"GLU\")\n * 2. text (human-readable, e.g. \"Glucose\")\n * 3. nameOfCodingSystem (e.g. \"LN\" for LOINC)\n * 4. alternateIdentifier\n * 5. alternateText\n * 6. nameOfAlternateCodingSystem\n *\n * Components 7+ (present when a CWE-shaped value is read through the CE\n * accessor — e.g. version ids, originalText) are surfaced verbatim on\n * `extraComponents` rather than dropped.\n *\n * @example\n * ```ts\n * import type { CE } from \"@cosyte/hl7\";\n * const code: CE = { identifier: \"GLU\", text: \"Glucose\", nameOfCodingSystem: \"LN\" };\n * ```\n */\nexport interface CE {\n readonly identifier?: string;\n readonly text?: string;\n readonly nameOfCodingSystem?: string;\n readonly alternateIdentifier?: string;\n readonly alternateText?: string;\n readonly nameOfAlternateCodingSystem?: string;\n /**\n * Components beyond the modeled 6 (HL7 component 7 onward), preserved\n * verbatim and in order. Non-empty only when a CWE-shaped value is read\n * through the CE accessor; OMITTED otherwise. An absent interior component\n * is preserved as `\"\"` so `extraComponents[i]` maps to HL7 component\n * `7 + i`.\n */\n readonly extraComponents?: readonly string[];\n}\n\n/**\n * Parse an HL7 v2 CE repetition into a structured `CE` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseCe, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"GLU\"] },\n * { subcomponents: [\"Glucose\"] },\n * { subcomponents: [\"LN\"] },\n * ] };\n * const ce = parseCe(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(ce.identifier); // \"GLU\"\n * ```\n */\nexport function parseCe(rep: RawRepetition, enc: EncodingCharacters): CE {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<CE> = {};\n\n const identifier = readComponent(rep, 0, enc);\n if (identifier !== undefined) out.identifier = identifier;\n\n const text = readComponent(rep, 1, enc);\n if (text !== undefined) out.text = text;\n\n const nameOfCodingSystem = readComponent(rep, 2, enc);\n if (nameOfCodingSystem !== undefined) out.nameOfCodingSystem = nameOfCodingSystem;\n\n const alternateIdentifier = readComponent(rep, 3, enc);\n if (alternateIdentifier !== undefined) out.alternateIdentifier = alternateIdentifier;\n\n const alternateText = readComponent(rep, 4, enc);\n if (alternateText !== undefined) out.alternateText = alternateText;\n\n const nameOfAlternateCodingSystem = readComponent(rep, 5, enc);\n if (nameOfAlternateCodingSystem !== undefined) {\n out.nameOfAlternateCodingSystem = nameOfAlternateCodingSystem;\n }\n\n const extraComponents = readExtraComponents(rep, 6, enc);\n if (extraComponents !== undefined) out.extraComponents = extraComponents;\n\n return out;\n}\n","/**\n * CWE — HL7 v2 Coded with Exceptions composite. 9-component coded-element\n * shape parsed from a `RawRepetition` on demand by `Field.asCwe()` (wired in\n * Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes) —\n * NEVER set to `undefined`.\n *\n * Note: full HL7 v2.6+ CWE has 22 components. v1 of this library ships the 9\n * core components — identifier, text, coding-system trio + version ids, and\n * originalText — which cover the common HL7 v2.5 use cases. v2 may restore\n * the full shape. Components 10+ that a newer (v2.7+) sender supplies — the\n * second-alternate triplet and the coding-system / value-set OIDs — are NOT\n * dropped: they are preserved verbatim on `extraComponents` so the typed view\n * is lossless across versions.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent, readExtraComponents } from \"./_shared.js\";\n\n/**\n * HL7 v2 Coded with Exceptions (CWE) — coded element per HL7 Chapter 2. All\n * 9 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. identifier (e.g. \"GLU\")\n * 2. text (human-readable, e.g. \"Glucose\")\n * 3. nameOfCodingSystem (e.g. \"LN\" for LOINC, \"SCT\" for SNOMED CT)\n * 4. alternateIdentifier\n * 5. alternateText\n * 6. nameOfAlternateCodingSystem\n * 7. codingSystemVersionId\n * 8. alternateCodingSystemVersionId\n * 9. originalText\n *\n * Components 10+ (present only on v2.7+ senders) are surfaced verbatim, in\n * order, on `extraComponents` — never silently truncated.\n *\n * @example\n * ```ts\n * import type { CWE } from \"@cosyte/hl7\";\n * const code: CWE = { identifier: \"GLU\", text: \"Glucose\", nameOfCodingSystem: \"LN\" };\n * ```\n */\nexport interface CWE {\n readonly identifier?: string;\n readonly text?: string;\n readonly nameOfCodingSystem?: string;\n readonly alternateIdentifier?: string;\n readonly alternateText?: string;\n readonly nameOfAlternateCodingSystem?: string;\n readonly codingSystemVersionId?: string;\n readonly alternateCodingSystemVersionId?: string;\n readonly originalText?: string;\n /**\n * Components beyond the modeled 9 (HL7 component 10 onward), preserved\n * verbatim and in order for forward-compatibility with v2.7+ senders that\n * carry the second-alternate triplet or coding-system / value-set OIDs.\n * OMITTED when the element has no components past the 9th. An absent interior\n * component is preserved as `\"\"` so `extraComponents[i]` maps to HL7\n * component `10 + i`.\n */\n readonly extraComponents?: readonly string[];\n}\n\n/**\n * Parse an HL7 v2 CWE repetition into a structured `CWE` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseCwe, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"GLU\"] },\n * { subcomponents: [\"Glucose\"] },\n * { subcomponents: [\"LN\"] },\n * ] };\n * const cwe = parseCwe(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(cwe.identifier); // \"GLU\"\n * ```\n */\nexport function parseCwe(rep: RawRepetition, enc: EncodingCharacters): CWE {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<CWE> = {};\n\n const identifier = readComponent(rep, 0, enc);\n if (identifier !== undefined) out.identifier = identifier;\n\n const text = readComponent(rep, 1, enc);\n if (text !== undefined) out.text = text;\n\n const nameOfCodingSystem = readComponent(rep, 2, enc);\n if (nameOfCodingSystem !== undefined) out.nameOfCodingSystem = nameOfCodingSystem;\n\n const alternateIdentifier = readComponent(rep, 3, enc);\n if (alternateIdentifier !== undefined) out.alternateIdentifier = alternateIdentifier;\n\n const alternateText = readComponent(rep, 4, enc);\n if (alternateText !== undefined) out.alternateText = alternateText;\n\n const nameOfAlternateCodingSystem = readComponent(rep, 5, enc);\n if (nameOfAlternateCodingSystem !== undefined) {\n out.nameOfAlternateCodingSystem = nameOfAlternateCodingSystem;\n }\n\n const codingSystemVersionId = readComponent(rep, 6, enc);\n if (codingSystemVersionId !== undefined) out.codingSystemVersionId = codingSystemVersionId;\n\n const alternateCodingSystemVersionId = readComponent(rep, 7, enc);\n if (alternateCodingSystemVersionId !== undefined) {\n out.alternateCodingSystemVersionId = alternateCodingSystemVersionId;\n }\n\n const originalText = readComponent(rep, 8, enc);\n if (originalText !== undefined) out.originalText = originalText;\n\n const extraComponents = readExtraComponents(rep, 9, enc);\n if (extraComponents !== undefined) out.extraComponents = extraComponents;\n\n return out;\n}\n","/**\n * HD — HL7 v2 Hierarchic Designator composite. 3-component structured\n * identifier (namespace + universal id + universal id type) parsed from a\n * `RawRepetition` on demand. Fields are OMITTED when absent\n * (exactOptionalPropertyTypes) — NEVER set to `undefined`.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Hierarchic Designator (HD) — per HL7 Chapter 2 data type. All 3\n * components are optional. Fields are OMITTED when the underlying component\n * is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. namespaceId — application- or facility-scoped identifier (e.g. \"EPIC\").\n * 2. universalId — globally-unique id (e.g. an OID or UUID string).\n * 3. universalIdType — classifier for `universalId` (ISO, GUID, UUID, DNS,\n * URI, HL7, HCD, Random, etc.).\n *\n * @example\n * ```ts\n * import type { HD } from \"@cosyte/hl7\";\n * const authority: HD = { namespaceId: \"EPIC\", universalId: \"1.2.840.114350\", universalIdType: \"ISO\" };\n * ```\n */\nexport interface HD {\n readonly namespaceId?: string;\n readonly universalId?: string;\n readonly universalIdType?: string;\n}\n\n/**\n * Parse an HL7 v2 HD repetition into a structured `HD` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseHd, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"EPIC\"] },\n * { subcomponents: [\"1.2.840.114350\"] },\n * { subcomponents: [\"ISO\"] },\n * ] };\n * const hd = parseHd(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(hd.namespaceId); // \"EPIC\"\n * console.log(hd.universalIdType); // \"ISO\"\n * ```\n */\nexport function parseHd(rep: RawRepetition, enc: EncodingCharacters): HD {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<HD> = {};\n\n const namespaceId = readComponent(rep, 0, enc);\n if (namespaceId !== undefined) out.namespaceId = namespaceId;\n\n const universalId = readComponent(rep, 1, enc);\n if (universalId !== undefined) out.universalId = universalId;\n\n const universalIdType = readComponent(rep, 2, enc);\n if (universalIdType !== undefined) out.universalIdType = universalIdType;\n\n return out;\n}\n","/**\n * CX — HL7 v2 Extended Composite ID (with check digit) composite.\n * 10-component structured-identifier shape parsed from a `RawRepetition` on\n * demand by `Field.asCx()` (wired in Plan 04). Fields are OMITTED when\n * absent (exactOptionalPropertyTypes) — NEVER set to `undefined`.\n *\n * Component 4 (`assigningAuthority`) is the ONE nested-composite field in\n * this plan: its subcomponents form a 3-field HD (namespaceId, universalId,\n * universalIdType). To reuse `parseHd` without duplicating logic, the parser\n * synthesises a `RawRepetition` whose components wrap the subcomponents of\n * CX component 4.\n *\n * Component 6 (`assigningFacility`) is simplified to a flat `string` in v1\n * — the HL7 spec treats it as HD-shaped, but v1 favours simplicity. Callers\n * who need the full HD can parse the raw string separately.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\nimport { parseHd, type HD } from \"./hd.js\";\n\n/**\n * HL7 v2 Extended Composite ID (CX) — structured identifier per HL7 Chapter\n * 2. All 10 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes). `assigningAuthority`\n * uses the nested `HD` shape; `assigningFacility` is flattened to a plain\n * string in v1.\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. idNumber\n * 2. checkDigit\n * 3. checkDigitScheme (ISO 7064, M10, M11, NPI)\n * 4. assigningAuthority (nested HD — 3 subcomponents form a HD composite)\n * 5. identifierTypeCode (MR, SSN, DL, MC, ...)\n * 6. assigningFacility (v1: flattened to string; spec is HD-shaped)\n * 7. effectiveDate (raw HL7 TS string)\n * 8. expirationDate (raw HL7 TS string)\n * 9. assigningJurisdiction (v1: flattened to string)\n * 10. assigningAgencyOrDepartment (v1: flattened to string)\n *\n * @example\n * ```ts\n * import type { CX } from \"@cosyte/hl7\";\n * const mrn: CX = {\n * idNumber: \"123456\",\n * assigningAuthority: { namespaceId: \"EPIC\", universalId: \"1.2.840.114350\", universalIdType: \"ISO\" },\n * identifierTypeCode: \"MR\",\n * };\n * ```\n */\nexport interface CX {\n readonly idNumber?: string;\n readonly checkDigit?: string;\n readonly checkDigitScheme?: string;\n readonly assigningAuthority?: HD;\n readonly identifierTypeCode?: string;\n readonly assigningFacility?: string;\n readonly effectiveDate?: string;\n readonly expirationDate?: string;\n readonly assigningJurisdiction?: string;\n readonly assigningAgencyOrDepartment?: string;\n}\n\n/**\n * Parse CX component 4 (assigningAuthority) from its subcomponents into an\n * `HD`. The 3 HD subfields live as subcomponents of the CX component; we\n * build a synthetic `RawRepetition` where each synthetic component wraps one\n * subcomponent of the CX component as its own single subcomponent. This\n * lets `parseHd` consume the value via its existing `(rep, enc)` signature\n * without reimplementing the read.\n *\n * Returns `undefined` when the source component is missing or every\n * subcomponent is the empty string — prevents stub empty HD objects from\n * leaking into CX output (T-03-02-02 mitigation).\n *\n * @internal\n */\nfunction parseAssigningAuthority(\n comp: RawComponent | undefined,\n enc: EncodingCharacters,\n): HD | undefined {\n if (comp === undefined) return undefined;\n if (comp.subcomponents.every((s) => s === \"\")) return undefined;\n const synthetic: RawRepetition = {\n components: comp.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const hd = parseHd(synthetic, enc);\n return Object.keys(hd).length === 0 ? undefined : hd;\n}\n\n/**\n * Parse an HL7 v2 CX repetition into a structured `CX` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Component 4\n * (`assigningAuthority`) is parsed as a nested `HD`; see component table in\n * the `CX` interface JSDoc for the v1 simplifications on components 6/9/10.\n *\n * @example\n * ```ts\n * import { parseCx, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"123\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"EPIC\", \"1.2.840.114350\", \"ISO\"] },\n * { subcomponents: [\"MR\"] },\n * ] };\n * const cx = parseCx(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(cx.idNumber); // \"123\"\n * console.log(cx.assigningAuthority?.namespaceId); // \"EPIC\"\n * ```\n */\nexport function parseCx(rep: RawRepetition, enc: EncodingCharacters): CX {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<CX> = {};\n\n const idNumber = readComponent(rep, 0, enc);\n if (idNumber !== undefined) out.idNumber = idNumber;\n\n const checkDigit = readComponent(rep, 1, enc);\n if (checkDigit !== undefined) out.checkDigit = checkDigit;\n\n const checkDigitScheme = readComponent(rep, 2, enc);\n if (checkDigitScheme !== undefined) out.checkDigitScheme = checkDigitScheme;\n\n const assigningAuthority = parseAssigningAuthority(rep.components[3], enc);\n if (assigningAuthority !== undefined) out.assigningAuthority = assigningAuthority;\n\n const identifierTypeCode = readComponent(rep, 4, enc);\n if (identifierTypeCode !== undefined) out.identifierTypeCode = identifierTypeCode;\n\n const assigningFacility = readComponent(rep, 5, enc);\n if (assigningFacility !== undefined) out.assigningFacility = assigningFacility;\n\n const effectiveDate = readComponent(rep, 6, enc);\n if (effectiveDate !== undefined) out.effectiveDate = effectiveDate;\n\n const expirationDate = readComponent(rep, 7, enc);\n if (expirationDate !== undefined) out.expirationDate = expirationDate;\n\n const assigningJurisdiction = readComponent(rep, 8, enc);\n if (assigningJurisdiction !== undefined) out.assigningJurisdiction = assigningJurisdiction;\n\n const assigningAgencyOrDepartment = readComponent(rep, 9, enc);\n if (assigningAgencyOrDepartment !== undefined) {\n out.assigningAgencyOrDepartment = assigningAgencyOrDepartment;\n }\n\n return out;\n}\n","/**\n * NM — HL7 v2 Numeric composite. Parses the raw HL7 numeric string into a\n * `number` via the stricter `Number(raw)` (not `parseFloat`, which tolerates\n * trailing garbage like \"12abc\" → 12). `NaN` is normalized to `undefined`\n * per the same no-throw discipline as TS/DTM (D-24 analogous).\n *\n * The raw string is preserved verbatim on the composite so callers needing\n * to round-trip or render with the original precision/formatting can.\n *\n * Zero runtime deps — pure function over the raw tree + `unescape` + stdlib\n * `Number`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\n/**\n * HL7 v2 Numeric (NM) composite. Carries both the raw HL7 numeric string\n * and the parsed JS `number`. `.value` is `undefined` when the raw string\n * is empty or not fully numeric — NEVER throws.\n *\n * Unlike most composites in this phase, both `raw` and `value` are\n * ALWAYS-PRESENT keys (not optional) — `value` is explicitly typed as\n * `number | undefined` so callers can destructure uniformly.\n *\n * @example\n * ```ts\n * import type { NM } from \"@cosyte/hl7\";\n * const glucose: NM = { raw: \"120\", value: 120 };\n * const bad: NM = { raw: \"N/A\", value: undefined };\n * ```\n */\nexport interface NM {\n readonly raw: string;\n readonly value: number | undefined;\n}\n\n/**\n * Parse an HL7 v2 NM repetition into `{ raw, value }`. Uses `Number(raw)`\n * for strict numeric parsing — trailing non-numeric characters produce\n * `NaN`, normalized to `undefined`. Empty raw also produces `undefined`.\n *\n * `Number(\"\")` is `0` in JS — which is the wrong answer for an empty HL7\n * numeric field. The explicit empty-string check below returns\n * `{ raw: \"\", value: undefined }` so empty inputs match missing inputs.\n *\n * @example\n * ```ts\n * import { parseNm, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [{ subcomponents: [\"120.5\"] }] };\n * const nm = parseNm(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(nm.value); // 120.5\n * ```\n */\nexport function parseNm(rep: RawRepetition, _enc: EncodingCharacters): NM {\n const comp = rep.components[0];\n // The tokenizer already unescaped every subcomponent on parse (parser-02), so\n // the stored value is decoded — use it directly, never a second unescape (that\n // would double-decode a value whose bytes look like an escape). `_enc` is kept\n // for composite-parser signature uniformity.\n const raw = comp?.subcomponents[0] ?? \"\";\n if (raw === \"\") return { raw, value: undefined };\n const n = Number(raw);\n const value = Number.isNaN(n) ? undefined : n;\n return { raw, value };\n}\n","/**\n * PL — HL7 v2 Person Location composite. 11-component structured-location\n * shape (v1 trimmed from the HL7 v2.5 full 12-component PL — slot 12\n * `entityIdentifier` is rarely used; v2 may restore the full shape) parsed\n * from a `RawRepetition` on demand by `Field.asPl()` (wired in Plan 04).\n * Fields are OMITTED when absent (exactOptionalPropertyTypes) — NEVER set\n * to `undefined`.\n *\n * Component 4 (`facility`) is the ONE nested-composite field in this\n * parser: its subcomponents form a 3-field HD (namespaceId, universalId,\n * universalIdType) — same synthesis pattern used in `parseCx` for\n * `assigningAuthority`. To reuse `parseHd` without duplicating logic, the\n * parser synthesises a `RawRepetition` whose components wrap the\n * subcomponents of PL component 4.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\nimport { parseHd, type HD } from \"./hd.js\";\n\n/**\n * HL7 v2 Person Location (PL) — structured location per HL7 Chapter 2. All\n * 11 v1 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes). `facility` uses the\n * nested `HD` shape; `assigningAuthorityForLocation` is flattened to a\n * plain string in v1 (HL7 spec treats it as HD-shaped).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. pointOfCare — e.g. \"ICU\", \"ED\"\n * 2. room\n * 3. bed\n * 4. facility — nested HD (3 subcomponents form an HD composite)\n * 5. locationStatus — O=Occupied, U=Unoccupied, K=Contaminated, C=Closed,\n * H=Housekeeping, I=Isolated\n * 6. personLocationType — C=Clinic, D=Department, H=Home, N=Nursing Unit,\n * O=Office, R=Revenue Location\n * 7. building\n * 8. floor\n * 9. locationDescription — free-text\n * 10. comprehensiveLocationId\n * 11. assigningAuthorityForLocation (v1: flattened to string)\n *\n * @example\n * ```ts\n * import type { PL } from \"@cosyte/hl7\";\n * const bed: PL = {\n * pointOfCare: \"ICU\",\n * room: \"101\",\n * bed: \"A\",\n * facility: { namespaceId: \"HOSP\", universalId: \"1.2.3\", universalIdType: \"UUID\" },\n * };\n * ```\n */\nexport interface PL {\n readonly pointOfCare?: string;\n readonly room?: string;\n readonly bed?: string;\n readonly facility?: HD;\n readonly locationStatus?: string;\n readonly personLocationType?: string;\n readonly building?: string;\n readonly floor?: string;\n readonly locationDescription?: string;\n readonly comprehensiveLocationId?: string;\n readonly assigningAuthorityForLocation?: string;\n}\n\n/**\n * Parse PL component 4 (facility) from its subcomponents into an `HD`. The\n * 3 HD subfields live as subcomponents of the PL component; we build a\n * synthetic `RawRepetition` where each synthetic component wraps one\n * subcomponent of the PL component as its own single subcomponent. This\n * lets `parseHd` consume the value via its existing `(rep, enc)` signature\n * without reimplementing the read.\n *\n * Returns `undefined` when the source component is missing or every\n * subcomponent is the empty string — prevents stub empty HD objects from\n * leaking into PL output (T-03-03 analogue of CX's T-03-02-02 mitigation).\n *\n * @internal\n */\nfunction parseFacility(comp: RawComponent | undefined, enc: EncodingCharacters): HD | undefined {\n if (comp === undefined) return undefined;\n if (comp.subcomponents.every((s) => s === \"\")) return undefined;\n const synthetic: RawRepetition = {\n components: comp.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const hd = parseHd(synthetic, enc);\n return Object.keys(hd).length === 0 ? undefined : hd;\n}\n\n/**\n * Parse an HL7 v2 PL repetition into a structured `PL` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Component 4\n * (`facility`) is parsed as a nested `HD`; see component table in the `PL`\n * interface JSDoc for the v1 simplifications.\n *\n * @example\n * ```ts\n * import { parsePl, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"ICU\"] },\n * { subcomponents: [\"101\"] },\n * { subcomponents: [\"A\"] },\n * { subcomponents: [\"HOSP\", \"1.2.3\", \"UUID\"] },\n * ] };\n * const pl = parsePl(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(pl.pointOfCare); // \"ICU\"\n * console.log(pl.facility?.namespaceId); // \"HOSP\"\n * ```\n */\nexport function parsePl(rep: RawRepetition, enc: EncodingCharacters): PL {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<PL> = {};\n\n const pointOfCare = readComponent(rep, 0, enc);\n if (pointOfCare !== undefined) out.pointOfCare = pointOfCare;\n\n const room = readComponent(rep, 1, enc);\n if (room !== undefined) out.room = room;\n\n const bed = readComponent(rep, 2, enc);\n if (bed !== undefined) out.bed = bed;\n\n const facility = parseFacility(rep.components[3], enc);\n if (facility !== undefined) out.facility = facility;\n\n const locationStatus = readComponent(rep, 4, enc);\n if (locationStatus !== undefined) out.locationStatus = locationStatus;\n\n const personLocationType = readComponent(rep, 5, enc);\n if (personLocationType !== undefined) out.personLocationType = personLocationType;\n\n const building = readComponent(rep, 6, enc);\n if (building !== undefined) out.building = building;\n\n const floor = readComponent(rep, 7, enc);\n if (floor !== undefined) out.floor = floor;\n\n const locationDescription = readComponent(rep, 8, enc);\n if (locationDescription !== undefined) out.locationDescription = locationDescription;\n\n const comprehensiveLocationId = readComponent(rep, 9, enc);\n if (comprehensiveLocationId !== undefined) out.comprehensiveLocationId = comprehensiveLocationId;\n\n const assigningAuthorityForLocation = readComponent(rep, 10, enc);\n if (assigningAuthorityForLocation !== undefined) {\n out.assigningAuthorityForLocation = assigningAuthorityForLocation;\n }\n\n return out;\n}\n","/**\n * SN — HL7 v2 Structured Numeric composite (HL7 Chapter 2A). Parses an OBX-5\n * value declared as `OBX-2 = SN` into its four positional components so a\n * comparator or a range/ratio is preserved as TYPED data instead of being\n * flattened to a string (where everything past the first component is lost).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. comparator (ST) — `>` `<` `>=` `<=` `=` `<>`; absent ⇒ `=`\n * 2. num1 (NM)\n * 3. separatorOrSuffix (ST) — `-` (range), `:` / `/` (ratio), `+` (suffix), `.`\n * 4. num2 (NM)\n *\n * Usage examples (the literal OBX-5 string ⇒ what this parses):\n * `>^100` ⇒ greater-than 100 → { comparator: \">\", num1: 100 }\n * `<^10` ⇒ less-than 10 → { comparator: \"<\", num1: 10 }\n * `^100^-^200` ⇒ range 100–200 → { num1: 100, separatorOrSuffix: \"-\", num2: 200 }\n * `^1^:^128` ⇒ titer/ratio 1:128 → { num1: 1, separatorOrSuffix: \":\", num2: 128 }\n *\n * Safety: `num1`/`num2` are parsed with the same strict `Number()` discipline\n * as NM — non-numeric input becomes `undefined`, NEVER `NaN` and never a\n * silently wrong number. The comparator is surfaced ONLY when SN.1 is a\n * recognized operator, so a non-operator value in the comparator slot is never\n * passed off as a real relation.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * The canonical HL7 SN comparator operator set (HL7 Ch 2A SN.1). An absent\n * comparator means `=` per the spec; a value outside this set is treated as\n * non-conformant and is not surfaced as a comparator (fail-safe).\n *\n * @internal\n */\nconst SN_COMPARATORS: ReadonlySet<string> = new Set([\">\", \"<\", \">=\", \"<=\", \"=\", \"<>\"]);\n\n/**\n * HL7 v2 Structured Numeric (SN) composite. `num1` and `num2` are\n * ALWAYS-PRESENT keys (typed `number | undefined`) so callers can destructure\n * uniformly, mirroring `NM`; `comparator` and `separatorOrSuffix` are OMITTED\n * when absent (`exactOptionalPropertyTypes`).\n *\n * An absent `comparator` means the default `=` relation per HL7 Chapter 2A.\n * This library surfaces the structure only — it does not evaluate the\n * inequality, validate the unit, or convert values.\n *\n * @example\n * ```ts\n * import type { SN } from \"@cosyte/hl7\";\n * const gfr: SN = { comparator: \">\", num1: 90, num2: undefined }; // >90\n * const range: SN = { num1: 100, separatorOrSuffix: \"-\", num2: 200 }; // 100-200\n * ```\n */\nexport interface SN {\n /** SN.1 comparator — one of `>` `<` `>=` `<=` `=` `<>`. Omitted ⇒ default `=`. */\n readonly comparator?: string;\n /** SN.2 first numeric value. `undefined` when absent or non-numeric (never `NaN`). */\n readonly num1: number | undefined;\n /** SN.3 separator/suffix — `-` (range), `:`/`/` (ratio), `+` (suffix), `.`. Omitted when absent. */\n readonly separatorOrSuffix?: string;\n /** SN.4 second numeric value. `undefined` when absent or non-numeric (never `NaN`). */\n readonly num2: number | undefined;\n}\n\n/** Strict numeric coercion mirroring NM: empty/non-numeric ⇒ undefined, never NaN. @internal */\nfunction numericOrUndefined(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n return Number.isNaN(n) ? undefined : n;\n}\n\n/**\n * Parse an HL7 v2 SN repetition into a structured `SN`, or `undefined` when the\n * field carries no usable structured-numeric content (empty, or so malformed\n * that no comparator, number, or separator can be recovered). Components are\n * returned verbatim (already decoded by the tokenizer); `num1`/`num2` use strict `Number()` parsing.\n *\n * Fail-safe: a non-operator value in the comparator slot (SN.1) is dropped\n * rather than surfaced as a relation, and a non-numeric SN.2/SN.4 becomes\n * `undefined` — the parser never emits a confident wrong comparator or number.\n *\n * @example\n * ```ts\n * import { parseSn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\">\"] },\n * { subcomponents: [\"90\"] },\n * ] };\n * const sn = parseSn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(sn?.comparator, sn?.num1); // \">\" 90\n * ```\n */\nexport function parseSn(rep: RawRepetition, enc: EncodingCharacters): SN | undefined {\n const rawComparator = readComponent(rep, 0, enc);\n const num1 = numericOrUndefined(readComponent(rep, 1, enc));\n const separatorOrSuffix = readComponent(rep, 2, enc);\n const num2 = numericOrUndefined(readComponent(rep, 3, enc));\n\n const comparator =\n rawComparator !== undefined && SN_COMPARATORS.has(rawComparator) ? rawComparator : undefined;\n\n // Malformed / empty SN: nothing usable recovered → undefined (never a wrong number).\n if (\n comparator === undefined &&\n num1 === undefined &&\n separatorOrSuffix === undefined &&\n num2 === undefined\n ) {\n return undefined;\n }\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<SN> = { num1, num2 };\n if (comparator !== undefined) out.comparator = comparator;\n if (separatorOrSuffix !== undefined) out.separatorOrSuffix = separatorOrSuffix;\n return out as SN;\n}\n","/**\n * HL7 v2 TS/DTM datetime handling for the `@cosyte/hl7` parser pipeline.\n *\n * Phase N (datetime precision + timezone fidelity) reworked this module from a\n * `Date`-coercing helper into a **fidelity-first** parser. The HL7 v2 Ch. 2A\n * DTM datatype is `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`, where the\n * number of populated characters (excluding the offset) sets the precision and\n * a missing offset \"defaults to that of the local time zone of the sender\" —\n * NOT UTC and NOT the parser's zone. The old behavior (zero-fill truncations,\n * assume-UTC on a missing offset, eager `Date`) is an architectural defect\n * [S-DTM-IMPL]: it silently shifts a day-only birth date (`|19880705|`) by a\n * day in any negative-offset zone.\n *\n * This module therefore:\n * - `parseDtm(raw)` decodes the DTM into typed **parts** (`DtmParts`) —\n * precision preserved, no zero-fill, no `Date`, no UTC assumption.\n * - `formatDtm(parts)` reconstructs the DTM string from parts (round-trip).\n * - `dtmToDate(parts, opts)` materializes an absolute `Date` **only on\n * explicit caller request**, refusing to guess a zone for an offset-less\n * value unless the caller supplies one.\n * - `parseDtmCascade(raw, opts)` is the lenient wrapper (strict DTM → user\n * formats → built-in fallbacks) used by non-composite callers such as\n * `msg.meta.timestamp`; it emits `TIMESTAMP_FALLBACK_FORMAT` on a fallback.\n *\n * Zero runtime deps — only the JS stdlib `Date` / `Date.UTC` APIs and\n * hand-rolled regex / token matchers. No date-fns, no luxon, no moment.\n */\n\nimport { timestampFallbackFormat } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Stated precision of a parsed HL7 DTM value — the number of populated\n * characters (excluding the timezone offset) determines which level applies.\n * A value's precision is preserved verbatim: `|1970|` is `\"year\"`, never\n * silently promoted to a full timestamp.\n *\n * @example\n * ```ts\n * import { parseDtm } from \"@cosyte/hl7\";\n * console.log(parseDtm(\"1970\").precision); // \"year\"\n * console.log(parseDtm(\"198807050000\").precision); // \"minute\"\n * ```\n */\nexport type DtmPrecision = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\" | \"fraction\";\n\n/**\n * Parsed HL7 v2 TS/DTM value — the raw string plus its structural parts, with\n * the stated **precision** and **timezone fidelity** preserved. This is the\n * shape of the `TS` composite (`field.asTs()`) and every helper datetime.\n *\n * The parts are only populated when `valid` is `true`. `month`/`day`/… are\n * **spec-native** (`month` is 1–12, NOT the JS `Date` 0–11). `offsetMinutes`\n * is present iff `hasTimezone` is `true` and is signed minutes east of UTC\n * (`+0500` → `300`, `-0430` → `-270`). A missing offset is **flagged**\n * (`hasTimezone: false`), never resolved to UTC — the consumer decides how to\n * localize with {@link dtmToDate}.\n *\n * @example\n * ```ts\n * import type { DtmParts } from \"@cosyte/hl7\";\n * const dob: DtmParts = {\n * raw: \"19880705\", valid: true, precision: \"day\",\n * year: 1988, month: 7, day: 5, hasTimezone: false,\n * };\n * ```\n */\nexport interface DtmParts {\n /** The original HL7 string, exactly as it appeared (already unescaped). */\n readonly raw: string;\n /**\n * `true` when `raw` is a well-formed, in-range HL7 DTM (or a matched\n * fallback format). `false` for empty, malformed, or calendar-out-of-range\n * input — in which case only `raw` and `hasTimezone: false` are meaningful.\n */\n readonly valid: boolean;\n /** Stated precision; absent when `valid` is `false`. */\n readonly precision?: DtmPrecision;\n /** Four-digit year. */\n readonly year?: number;\n /** Month, 1–12 (spec-native, NOT JS 0–11). */\n readonly month?: number;\n /** Day of month, 1–31. */\n readonly day?: number;\n /** Hour, 0–23. */\n readonly hour?: number;\n /** Minute, 0–59. */\n readonly minute?: number;\n /** Second, 0–59. */\n readonly second?: number;\n /**\n * Fractional-second digits exactly as populated (no leading dot), e.g.\n * `\"5\"` (0.5 s), `\"0500\"` (0.05 s). Preserved verbatim — never rounded.\n */\n readonly fractionalSeconds?: string;\n /** `true` iff an explicit `+/-ZZZZ` offset was present. */\n readonly hasTimezone: boolean;\n /** Signed minutes east of UTC; present iff `hasTimezone` is `true`. */\n readonly offsetMinutes?: number;\n /**\n * The fallback format that matched (`parseDtmCascade` only), e.g.\n * `\"MM/DD/YYYY\"` or `\"ISO-8601\"`. Absent for a strict HL7 DTM parse.\n */\n readonly matchedFormat?: string;\n}\n\n/**\n * Ordered list of built-in timestamp formats {@link parseDtmCascade} falls\n * back to when neither the strict HL7 DTM match nor any user-supplied format\n * succeeds. ISO-8601 is tried first (most constrained); `MM/DD/YYYY HH:mm:ss`\n * last (it overlaps the date-only form).\n *\n * @example\n * ```ts\n * import { BUILTIN_DATE_FALLBACKS } from \"@cosyte/hl7\";\n * console.log(BUILTIN_DATE_FALLBACKS);\n * // [\"ISO-8601\", \"YYYY-MM-DD\", \"MM/DD/YYYY\", \"MM/DD/YYYY HH:mm:ss\"]\n * ```\n */\nexport const BUILTIN_DATE_FALLBACKS: readonly string[] = [\n \"ISO-8601\",\n \"YYYY-MM-DD\",\n \"MM/DD/YYYY\",\n \"MM/DD/YYYY HH:mm:ss\",\n] as const;\n\n/**\n * Every date-format token the library's format-string matcher and\n * `defineProfile()` D-08 validator recognize. Re-exported so profile authors\n * can introspect the valid token set. `SSSS` (fractional seconds) is\n * recognised by the D-08 validator only.\n *\n * @example\n * ```ts\n * import { SUPPORTED_DATE_TOKENS } from \"@cosyte/hl7\";\n * console.log(SUPPORTED_DATE_TOKENS);\n * // [\"YYYY\", \"MM\", \"DD\", \"HH\", \"mm\", \"ss\", \"SSSS\"]\n * ```\n */\nexport const SUPPORTED_DATE_TOKENS: readonly string[] = [\n \"YYYY\",\n \"MM\",\n \"DD\",\n \"HH\",\n \"mm\",\n \"ss\",\n \"SSSS\",\n] as const;\n\n/**\n * The empty / unparseable result — `valid: false`, no parts, no timezone.\n * Frozen and shared to avoid per-call allocation on the common miss path.\n *\n * @internal\n */\nconst INVALID_PARTS_BASE = { valid: false as const, hasTimezone: false as const };\n\n/**\n * The frozen invalid/unparseable result for a raw string — `valid: false`, no\n * parts, no timezone. Frozen so every public `DtmParts` is immutable uniformly\n * (matching the composite path and `batch.ts`).\n *\n * @internal\n */\nfunction invalidDtm(raw: string): DtmParts {\n return Object.freeze({ raw, ...INVALID_PARTS_BASE });\n}\n\n/**\n * HL7 v2 DTM shape: `YYYY[MM[DD[HH[MM[SS[.SSSS]]]]]]` with an optional trailing\n * `+/-ZZZZ` offset. No separators between digit groups.\n *\n * @internal\n */\nconst DTM_PATTERN =\n /^(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(?:\\.(\\d{1,4}))?(?:([+-])(\\d{2})(\\d{2}))?$/u;\n\n/**\n * Parse an HL7 v2 TS/DTM string into typed {@link DtmParts}, **preserving the\n * stated precision and timezone fidelity**. Never zero-fills a truncation,\n * never coerces to a `Date`, and never assumes UTC for a missing offset.\n *\n * Returns `{ raw, valid: false, hasTimezone: false }` (no parts) for empty,\n * malformed, or calendar-out-of-range input — never throws. A fractional\n * component is only accepted at full second precision.\n *\n * @example\n * ```ts\n * import { parseDtm } from \"@cosyte/hl7\";\n *\n * parseDtm(\"1970\");\n * // { raw: \"1970\", valid: true, precision: \"year\", year: 1970, hasTimezone: false }\n *\n * parseDtm(\"20250102153045.5-0500\");\n * // precision \"fraction\", fractionalSeconds \"5\", hasTimezone true, offsetMinutes -300\n *\n * parseDtm(\"not-a-date\");\n * // { raw: \"not-a-date\", valid: false, hasTimezone: false }\n * ```\n */\nexport function parseDtm(raw: string): DtmParts {\n if (raw === \"\") return invalidDtm(raw);\n\n const match = DTM_PATTERN.exec(raw);\n if (match === null) return invalidDtm(raw);\n\n const [, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr, fracStr, sign, offHh, offMm] =\n match;\n if (yearStr === undefined) return invalidDtm(raw);\n\n // A fractional component is only meaningful at full second precision.\n if (fracStr !== undefined && secondStr === undefined) return invalidDtm(raw);\n\n const year = parseInt(yearStr, 10);\n const month = monthStr !== undefined ? parseInt(monthStr, 10) : undefined;\n const day = dayStr !== undefined ? parseInt(dayStr, 10) : undefined;\n const hour = hourStr !== undefined ? parseInt(hourStr, 10) : undefined;\n const minute = minuteStr !== undefined ? parseInt(minuteStr, 10) : undefined;\n const second = secondStr !== undefined ? parseInt(secondStr, 10) : undefined;\n\n // Calendar-range validation — out-of-range is invalid, never a wrong guess.\n if (\n (month !== undefined && (month < 1 || month > 12)) ||\n (day !== undefined && (day < 1 || day > 31)) ||\n (hour !== undefined && hour > 23) ||\n (minute !== undefined && minute > 59) ||\n (second !== undefined && second > 59)\n ) {\n return invalidDtm(raw);\n }\n\n let hasTimezone = false;\n let offsetMinutes: number | undefined;\n if (sign !== undefined && offHh !== undefined && offMm !== undefined) {\n const offHours = parseInt(offHh, 10);\n const offMins = parseInt(offMm, 10);\n // Offsets range roughly ±14:00; accept up to ±24:00, reject nonsense minutes.\n if (offHours > 24 || offMins > 59) return invalidDtm(raw);\n hasTimezone = true;\n offsetMinutes = (sign === \"-\" ? -1 : 1) * (offHours * 60 + offMins);\n }\n\n const precision: DtmPrecision =\n fracStr !== undefined\n ? \"fraction\"\n : second !== undefined\n ? \"second\"\n : minute !== undefined\n ? \"minute\"\n : hour !== undefined\n ? \"hour\"\n : day !== undefined\n ? \"day\"\n : month !== undefined\n ? \"month\"\n : \"year\";\n\n return Object.freeze({\n raw,\n valid: true,\n precision,\n year,\n ...(month !== undefined ? { month } : {}),\n ...(day !== undefined ? { day } : {}),\n ...(hour !== undefined ? { hour } : {}),\n ...(minute !== undefined ? { minute } : {}),\n ...(second !== undefined ? { second } : {}),\n ...(fracStr !== undefined ? { fractionalSeconds: fracStr } : {}),\n hasTimezone,\n ...(offsetMinutes !== undefined ? { offsetMinutes } : {}),\n });\n}\n\n/**\n * Reconstruct the HL7 DTM string from {@link DtmParts}. The inverse of\n * {@link parseDtm} for a strict HL7 parse — `formatDtm(parseDtm(s)) === s` for\n * any well-formed `s`, including the byte-preserving `-0000` (which HL7, unlike\n * RFC 3339, treats as UTC but whose sign we retain for exact round-trip).\n * Returns the raw string unchanged when `parts.valid` is `false`.\n *\n * Emits exactly the populated precision — no zero-fill — so a year-only value\n * re-serializes to four characters, never `YYYY0101`.\n *\n * @example\n * ```ts\n * import { parseDtm, formatDtm } from \"@cosyte/hl7\";\n * formatDtm(parseDtm(\"198807050000\")); // \"198807050000\"\n * formatDtm(parseDtm(\"1970\")); // \"1970\"\n * ```\n */\nexport function formatDtm(parts: DtmParts): string {\n if (!parts.valid || parts.year === undefined) return parts.raw;\n\n const pad = (n: number, width: number): string => n.toString().padStart(width, \"0\");\n let out = pad(parts.year, 4);\n if (parts.month !== undefined) out += pad(parts.month, 2);\n if (parts.day !== undefined) out += pad(parts.day, 2);\n if (parts.hour !== undefined) out += pad(parts.hour, 2);\n if (parts.minute !== undefined) out += pad(parts.minute, 2);\n if (parts.second !== undefined) out += pad(parts.second, 2);\n if (parts.fractionalSeconds !== undefined) out += `.${parts.fractionalSeconds}`;\n if (parts.hasTimezone && parts.offsetMinutes !== undefined) {\n const total = parts.offsetMinutes;\n // `Object.is(total, -0)` catches a `-0000` offset (parsed as -0) so it\n // re-serializes byte-exact as `-0000`, not `+0000`.\n const sign = total < 0 || Object.is(total, -0) ? \"-\" : \"+\";\n const abs = Math.abs(total);\n out += `${sign}${pad(Math.floor(abs / 60), 2)}${pad(abs % 60, 2)}`;\n }\n return out;\n}\n\n/**\n * Options controlling how {@link dtmToDate} resolves a missing timezone.\n *\n * @example\n * ```ts\n * import { parseDtm, dtmToDate } from \"@cosyte/hl7\";\n * // Treat an offset-less value as UTC (an explicit caller choice):\n * dtmToDate(parseDtm(\"20250102\"), { assumeOffsetMinutes: 0 });\n * // ...or as US Eastern standard time (UTC-05:00):\n * dtmToDate(parseDtm(\"20250102\"), { assumeOffsetMinutes: -300 });\n * ```\n */\nexport interface DtmToDateOptions {\n /**\n * Offset (signed minutes east of UTC) to assume when the value carries **no**\n * timezone. Without it, an offset-less value resolves to `undefined` —\n * {@link dtmToDate} never guesses a zone. Ignored when the value already has\n * an offset. Pass `0` to explicitly treat a naive value as UTC.\n */\n readonly assumeOffsetMinutes?: number;\n}\n\n/**\n * Materialize an absolute-instant JS `Date` from {@link DtmParts} — **only on\n * explicit caller request**. Truncated fields fill to their lowest legal value\n * (month → January, day → 1, time → 0) *for instant construction only*; the\n * value's stated `precision` still tells the truth.\n *\n * Timezone resolution is honest:\n * - has an offset → the exact instant, using that offset;\n * - no offset + `assumeOffsetMinutes` supplied → that offset is applied;\n * - no offset + nothing supplied → `undefined` (never a silent UTC guess).\n *\n * Returns `undefined` for an invalid value or an unresolvable zone; never\n * throws.\n *\n * @example\n * ```ts\n * import { parseDtm, dtmToDate } from \"@cosyte/hl7\";\n *\n * dtmToDate(parseDtm(\"20250102153045-0500\"))?.toISOString();\n * // \"2025-01-02T20:30:45.000Z\" — exact, offset-derived\n *\n * dtmToDate(parseDtm(\"20250102\")); // undefined — refuses to guess the zone\n * dtmToDate(parseDtm(\"20250102\"), { assumeOffsetMinutes: 0 })?.toISOString();\n * // \"2025-01-02T00:00:00.000Z\" — caller explicitly assumed UTC\n * ```\n */\nexport function dtmToDate(parts: DtmParts, options: DtmToDateOptions = {}): Date | undefined {\n if (!parts.valid || parts.year === undefined) return undefined;\n\n const offset = parts.hasTimezone ? parts.offsetMinutes : options.assumeOffsetMinutes;\n if (offset === undefined) return undefined;\n\n let ms = 0;\n if (parts.fractionalSeconds !== undefined) {\n ms = parseInt((parts.fractionalSeconds + \"000\").slice(0, 3), 10);\n }\n\n // Build via setUTCFullYear so a 1–99 AD year is NOT remapped to 1900–1999 by\n // `Date.UTC`'s legacy two-digit-year behavior (ECMA-262) — a spec-valid\n // 4-digit DTM year like `0050` must stay year 50.\n const utc = new Date(0);\n utc.setUTCFullYear(parts.year, (parts.month ?? 1) - 1, parts.day ?? 1);\n utc.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, ms);\n // The value is expressed in `offset`; shift to UTC by subtracting it.\n const candidate = new Date(utc.getTime() - offset * 60_000);\n return isNaN(candidate.getTime()) ? undefined : candidate;\n}\n\n/**\n * Options passed to {@link parseDtmCascade}. `emit` and `position` are needed\n * only when the caller wants `TIMESTAMP_FALLBACK_FORMAT` warnings to surface.\n *\n * @internal\n */\nexport interface ParseDtmCascadeOptions {\n readonly userFormats?: readonly string[];\n readonly emit?: (warning: Hl7ParseWarning) => void;\n readonly position?: Hl7Position;\n}\n\n/**\n * Lenient datetime parse for non-composite callers (e.g. `msg.meta.timestamp`):\n *\n * 1. Strict HL7 DTM via {@link parseDtm} — no warning (spec-preferred).\n * 2. User-supplied formats, in order — first match wins, emits\n * `TIMESTAMP_FALLBACK_FORMAT`.\n * 3. Built-in {@link BUILTIN_DATE_FALLBACKS}, in order — emits on match.\n *\n * Always returns {@link DtmParts}; a fallback match sets `matchedFormat` and\n * `valid: true` with the parts it could recover. A total miss returns an\n * invalid result (no throw, no warning — nothing fell back to).\n *\n * @internal\n */\nexport function parseDtmCascade(raw: string, opts: ParseDtmCascadeOptions): DtmParts {\n if (raw === \"\") return invalidDtm(raw);\n\n const strict = parseDtm(raw);\n if (strict.valid) return strict;\n\n for (const format of opts.userFormats ?? []) {\n const matched = matchTokenParts(raw, format);\n if (matched !== undefined) {\n emitFallback(opts, format);\n return Object.freeze({ ...matched, raw, matchedFormat: format });\n }\n }\n\n for (const builtin of BUILTIN_DATE_FALLBACKS) {\n const matched = builtin === \"ISO-8601\" ? parseIsoParts(raw) : matchTokenParts(raw, builtin);\n if (matched !== undefined) {\n emitFallback(opts, builtin);\n return Object.freeze({ ...matched, raw, matchedFormat: builtin });\n }\n }\n\n return invalidDtm(raw);\n}\n\n/**\n * Emit a `TIMESTAMP_FALLBACK_FORMAT` warning when both an `emit` callback and a\n * `position` are supplied.\n *\n * @internal\n */\nfunction emitFallback(opts: ParseDtmCascadeOptions, matchedFormat: string): void {\n if (opts.emit !== undefined && opts.position !== undefined) {\n opts.emit(timestampFallbackFormat(opts.position, matchedFormat));\n }\n}\n\n/**\n * Token set recognised by the minimal format-string matcher. `MM` is month and\n * `mm` is minute (case-sensitive, moment.js-style).\n *\n * @internal\n */\nconst TOKENS = [\"YYYY\", \"MM\", \"DD\", \"HH\", \"mm\", \"ss\"] as const;\n\n/** @internal Digit-width of each token. */\nconst TOKEN_LENGTHS: Readonly<Record<(typeof TOKENS)[number], number>> = {\n YYYY: 4,\n MM: 2,\n DD: 2,\n HH: 2,\n mm: 2,\n ss: 2,\n};\n\n/**\n * Minimal format-string matcher over the tokens `YYYY MM DD HH mm ss`. Anything\n * else in `format` is a literal. Returns fidelity {@link DtmParts} (no offset —\n * these formats carry none) or `undefined` on mismatch. Parsing is strictly\n * linear so untrusted format strings cannot cause exponential backtracking.\n *\n * @internal\n */\nfunction matchTokenParts(input: string, format: string): DtmParts | undefined {\n type Token = (typeof TOKENS)[number];\n type Part =\n | { readonly kind: \"token\"; readonly token: Token }\n | { readonly kind: \"lit\"; readonly value: string };\n\n const parts: Part[] = [];\n let i = 0;\n while (i < format.length) {\n let matched: Token | undefined;\n for (const t of TOKENS) {\n if (format.slice(i, i + t.length) === t) {\n matched = t;\n break;\n }\n }\n if (matched !== undefined) {\n parts.push({ kind: \"token\", token: matched });\n i += matched.length;\n } else {\n parts.push({ kind: \"lit\", value: format.charAt(i) });\n i += 1;\n }\n }\n\n const got: Partial<Record<Token, number>> = {};\n let j = 0;\n for (const p of parts) {\n if (p.kind === \"lit\") {\n if (input.charAt(j) !== p.value) return undefined;\n j += 1;\n } else {\n const len = TOKEN_LENGTHS[p.token];\n const chunk = input.slice(j, j + len);\n if (chunk.length !== len || !/^\\d+$/u.test(chunk)) return undefined;\n got[p.token] = parseInt(chunk, 10);\n j += len;\n }\n }\n if (j !== input.length) return undefined; // trailing chars = mismatch\n\n return buildFallbackParts({\n year: got.YYYY,\n month: got.MM,\n day: got.DD,\n hour: got.HH,\n minute: got.mm,\n second: got.ss,\n });\n}\n\n/**\n * Parse an ISO-8601 string into fidelity {@link DtmParts} behind a strict shape\n * guard (requires at least `YYYY-MM-DD` so raw HL7 digit strings never match\n * here). Preserves an explicit `Z`/`+HH:MM` offset as timezone fidelity.\n *\n * @internal\n */\nfunction parseIsoParts(raw: string): DtmParts | undefined {\n const iso =\n /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?(Z|[+-]\\d{2}:?\\d{2})?)?$/u.exec(\n raw,\n );\n if (iso === null) return undefined;\n const [, y, mo, d, h, mi, s, frac, tz] = iso;\n\n let hasTimezone = false;\n let offsetMinutes: number | undefined;\n if (tz !== undefined) {\n hasTimezone = true;\n if (tz === \"Z\") {\n offsetMinutes = 0;\n } else {\n const sign = tz.startsWith(\"-\") ? -1 : 1;\n const digits = tz.slice(1).replace(\":\", \"\");\n offsetMinutes =\n sign * (parseInt(digits.slice(0, 2), 10) * 60 + parseInt(digits.slice(2), 10));\n }\n }\n\n return buildFallbackParts({\n year: y !== undefined ? parseInt(y, 10) : undefined,\n month: mo !== undefined ? parseInt(mo, 10) : undefined,\n day: d !== undefined ? parseInt(d, 10) : undefined,\n hour: h !== undefined ? parseInt(h, 10) : undefined,\n minute: mi !== undefined ? parseInt(mi, 10) : undefined,\n second: s !== undefined ? parseInt(s, 10) : undefined,\n fractionalSeconds: frac,\n hasTimezone,\n offsetMinutes,\n });\n}\n\n/**\n * Assemble validated {@link DtmParts} from a fallback match, computing the\n * precision from which fields are present and range-checking each. Returns\n * `undefined` when any field is out of range.\n *\n * @internal\n */\nfunction buildFallbackParts(f: {\n year: number | undefined;\n month?: number | undefined;\n day?: number | undefined;\n hour?: number | undefined;\n minute?: number | undefined;\n second?: number | undefined;\n fractionalSeconds?: string | undefined;\n hasTimezone?: boolean | undefined;\n offsetMinutes?: number | undefined;\n}): DtmParts | undefined {\n if (f.year === undefined) return undefined;\n if (\n (f.month !== undefined && (f.month < 1 || f.month > 12)) ||\n (f.day !== undefined && (f.day < 1 || f.day > 31)) ||\n (f.hour !== undefined && f.hour > 23) ||\n (f.minute !== undefined && f.minute > 59) ||\n (f.second !== undefined && f.second > 59)\n ) {\n return undefined;\n }\n\n const precision: DtmPrecision =\n f.fractionalSeconds !== undefined\n ? \"fraction\"\n : f.second !== undefined\n ? \"second\"\n : f.minute !== undefined\n ? \"minute\"\n : f.hour !== undefined\n ? \"hour\"\n : f.day !== undefined\n ? \"day\"\n : f.month !== undefined\n ? \"month\"\n : \"year\";\n\n return {\n raw: \"\", // caller overwrites with the real raw string\n valid: true,\n precision,\n year: f.year,\n ...(f.month !== undefined ? { month: f.month } : {}),\n ...(f.day !== undefined ? { day: f.day } : {}),\n ...(f.hour !== undefined ? { hour: f.hour } : {}),\n ...(f.minute !== undefined ? { minute: f.minute } : {}),\n ...(f.second !== undefined ? { second: f.second } : {}),\n ...(f.fractionalSeconds !== undefined ? { fractionalSeconds: f.fractionalSeconds } : {}),\n hasTimezone: f.hasTimezone ?? false,\n ...(f.offsetMinutes !== undefined ? { offsetMinutes: f.offsetMinutes } : {}),\n };\n}\n","/**\n * TS/DTM — HL7 v2 Time Stamp composite. Delegates parsing to the Phase 2\n * helper `src/parser/dates.ts::parseDtm` (D-10 \"zero duplicate date logic\").\n *\n * Phase N (datetime precision + timezone fidelity) reshaped this composite from\n * the old `{ raw, date }` (which zero-filled truncations and assumed UTC for a\n * missing offset — an architectural defect) to the fidelity-preserving\n * {@link DtmParts}: raw string + typed parts + stated precision + timezone\n * presence, with **no eager `Date`**. Callers that need an absolute instant\n * opt in explicitly via `dtmToDate(ts, opts)` — which refuses to guess a zone\n * for an offset-less value rather than silently defaulting to UTC.\n *\n * Zero runtime deps — delegates to `parseDtm` + `unescape`.\n */\n\nimport { parseDtm } from \"../../parser/dates.js\";\nimport type { DtmParts } from \"../../parser/dates.js\";\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\n/**\n * HL7 v2 Time Stamp (TS) / Date Time (DTM) composite — the raw HL7 string plus\n * its parsed parts, preserving the **stated precision** and **timezone\n * fidelity**. This is a {@link DtmParts}: `valid` is `false` (with no parts)\n * for unparseable input — NEVER throws (TYPES-04 no-throw guarantee).\n *\n * There is deliberately **no `date` field**: a day-only value coerced to a JS\n * `Date` at UTC midnight silently shifts the calendar day in negative-offset\n * zones. To obtain an absolute instant, call `dtmToDate(ts)` explicitly (and\n * supply `assumeOffsetMinutes` for an offset-less value).\n *\n * @example\n * ```ts\n * import type { TS } from \"@cosyte/hl7\";\n * import { dtmToDate } from \"@cosyte/hl7\";\n * const dob: TS = { raw: \"19880705\", valid: true, precision: \"day\",\n * year: 1988, month: 7, day: 5, hasTimezone: false };\n * console.log(dob.precision); // \"day\" — not a full timestamp\n * console.log(dtmToDate(dob)); // undefined — refuses to guess the zone\n * ```\n */\nexport type TS = DtmParts;\n\n/**\n * Parse an HL7 v2 TS/DTM repetition into fidelity {@link TS} parts. Delegates\n * to `parseDtm` — the same structural parser that backs every timestamp in the\n * library. No user `dateFormats` at this layer; non-composite callers (e.g.\n * `msg.meta.timestamp`) that know `ParseOptions.dateFormats` use\n * `parseDtmCascade` directly.\n *\n * The result is frozen so the immutability guarantee holds for callers that\n * destructure or retain it.\n *\n * @example\n * ```ts\n * import { parseTs, DEFAULT_ENCODING_CHARACTERS, dtmToDate } from \"@cosyte/hl7\";\n * const rep = { components: [{ subcomponents: [\"20250102153045-0500\"] }] };\n * const ts = parseTs(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(ts.raw); // \"20250102153045-0500\"\n * console.log(ts.precision, ts.hasTimezone); // \"second\" true\n * console.log(dtmToDate(ts)?.toISOString()); // \"2025-01-02T20:30:45.000Z\"\n * ```\n */\nexport function parseTs(rep: RawRepetition, _enc: EncodingCharacters): TS {\n const comp = rep.components[0];\n // The tokenizer already unescaped every subcomponent on parse (parser-02), so\n // the stored value is decoded — use it directly, never a second unescape (that\n // would double-decode a value whose bytes look like an escape). `_enc` is kept\n // for composite-parser signature uniformity.\n const raw = comp?.subcomponents[0] ?? \"\";\n // `parseDtm` already returns a frozen `DtmParts`.\n return parseDtm(raw);\n}\n","/**\n * XAD — HL7 v2 Extended Address composite. 12-component structured address\n * shape parsed from a `RawRepetition` on demand by `Field.asXad()` (wired in\n * Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes) —\n * NEVER set to `undefined`.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Extended Address (XAD) — structured postal address per HL7 Chapter\n * 2. All 12 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. street — street address (house number + street name).\n * 2. otherDesignation — apartment number, suite, floor, etc.\n * 3. city\n * 4. stateOrProvince\n * 5. zipOrPostalCode\n * 6. country (ISO-3166 3-letter, e.g. \"USA\", \"CAN\")\n * 7. addressType (H=Home, B=Business, M=Mailing, O=Office, P=Permanent, ...)\n * 8. otherGeographicDesignation\n * 9. countyParishCode\n * 10. censusTract\n * 11. addressRepresentationCode\n * 12. addressValidityRange\n *\n * @example\n * ```ts\n * import type { XAD } from \"@cosyte/hl7\";\n * const addr: XAD = { street: \"123 Main St\", city: \"Boston\", stateOrProvince: \"MA\" };\n * ```\n */\nexport interface XAD {\n readonly street?: string;\n readonly otherDesignation?: string;\n readonly city?: string;\n readonly stateOrProvince?: string;\n readonly zipOrPostalCode?: string;\n readonly country?: string;\n readonly addressType?: string;\n readonly otherGeographicDesignation?: string;\n readonly countyParishCode?: string;\n readonly censusTract?: string;\n readonly addressRepresentationCode?: string;\n readonly addressValidityRange?: string;\n}\n\n/**\n * Parse an HL7 v2 XAD repetition into a structured `XAD` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseXad, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"123 Main St\"] },\n * { subcomponents: [\"Apt 4\"] },\n * { subcomponents: [\"Boston\"] },\n * { subcomponents: [\"MA\"] },\n * { subcomponents: [\"02101\"] },\n * ] };\n * const addr = parseXad(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(addr.city); // \"Boston\"\n * ```\n */\nexport function parseXad(rep: RawRepetition, enc: EncodingCharacters): XAD {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XAD> = {};\n\n const street = readComponent(rep, 0, enc);\n if (street !== undefined) out.street = street;\n\n const otherDesignation = readComponent(rep, 1, enc);\n if (otherDesignation !== undefined) out.otherDesignation = otherDesignation;\n\n const city = readComponent(rep, 2, enc);\n if (city !== undefined) out.city = city;\n\n const stateOrProvince = readComponent(rep, 3, enc);\n if (stateOrProvince !== undefined) out.stateOrProvince = stateOrProvince;\n\n const zipOrPostalCode = readComponent(rep, 4, enc);\n if (zipOrPostalCode !== undefined) out.zipOrPostalCode = zipOrPostalCode;\n\n const country = readComponent(rep, 5, enc);\n if (country !== undefined) out.country = country;\n\n const addressType = readComponent(rep, 6, enc);\n if (addressType !== undefined) out.addressType = addressType;\n\n const otherGeographicDesignation = readComponent(rep, 7, enc);\n if (otherGeographicDesignation !== undefined) {\n out.otherGeographicDesignation = otherGeographicDesignation;\n }\n\n const countyParishCode = readComponent(rep, 8, enc);\n if (countyParishCode !== undefined) out.countyParishCode = countyParishCode;\n\n const censusTract = readComponent(rep, 9, enc);\n if (censusTract !== undefined) out.censusTract = censusTract;\n\n const addressRepresentationCode = readComponent(rep, 10, enc);\n if (addressRepresentationCode !== undefined) {\n out.addressRepresentationCode = addressRepresentationCode;\n }\n\n const addressValidityRange = readComponent(rep, 11, enc);\n if (addressValidityRange !== undefined) out.addressValidityRange = addressValidityRange;\n\n return out;\n}\n","/**\n * XCN — HL7 v2 Extended Composite ID Number and Name for Persons. Common in\n * OBR-16 (ordering provider), PV1-7 (attending doctor), PV1-8 (referring\n * doctor), and other fields that identify a human clinician.\n *\n * Structurally XCN is XPN (person-name) components with an `idNumber` prefix\n * and an `assigningAuthority` nested-HD at component 9. v1 ships the 13\n * most-used components (HL7 v2.5 defines 23); additional components may be\n * restored in v2 if vendor-quirk fixtures require them.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n * Parser is silent (D-09 composite-parser silence).\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\nimport { parseHd, type HD } from \"./hd.js\";\n\n/**\n * HL7 v2 Extended Composite ID Number and Name for Persons (XCN) — per HL7\n * Chapter 2.A.88. All 13 v1 components are optional. Fields are OMITTED when\n * the underlying component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. idNumber — e.g. employee ID, NPI digits, DEA number (CX-1 analogue)\n * 2. familyName (XPN-1)\n * 3. givenName (XPN-2)\n * 4. secondName — second and further given names (XPN-3)\n * 5. suffix — Jr., III, etc. (XPN-4)\n * 6. prefix — Dr., Mrs., etc. (XPN-5)\n * 7. degree — MD, PhD, etc. (XPN-6)\n * 8. sourceTable\n * 9. assigningAuthority — nested HD (CX-4 analogue)\n * 10. nameTypeCode — L=Legal, M=Maiden, N=Nickname, ... (XPN-7)\n * 11. identifierCheckDigit\n * 12. checkDigitScheme — ISO 7064, M10, M11, NPI\n * 13. identifierTypeCode — \"NPI\", \"DN\" (DEA number), ... (CX-5 analogue)\n *\n * @example\n * ```ts\n * import type { XCN } from \"@cosyte/hl7\";\n * const orderingProvider: XCN = {\n * idNumber: \"1234567890\",\n * familyName: \"Smith\",\n * givenName: \"Jane\",\n * identifierTypeCode: \"NPI\",\n * };\n * ```\n */\nexport interface XCN {\n readonly idNumber?: string;\n readonly familyName?: string;\n readonly givenName?: string;\n readonly secondName?: string;\n readonly suffix?: string;\n readonly prefix?: string;\n readonly degree?: string;\n readonly sourceTable?: string;\n readonly assigningAuthority?: HD;\n readonly nameTypeCode?: string;\n readonly identifierCheckDigit?: string;\n readonly checkDigitScheme?: string;\n readonly identifierTypeCode?: string;\n}\n\n/**\n * Parse XCN component 9 (assigningAuthority) from its subcomponents into an\n * `HD`. The 3 HD subfields live as subcomponents of the XCN component; we\n * build a synthetic `RawRepetition` where each synthetic component wraps one\n * subcomponent of the XCN component as its own single subcomponent. This\n * lets `parseHd` consume the value via its existing `(rep, enc)` signature\n * without reimplementing the read.\n *\n * Returns `undefined` when the source component is missing or every\n * subcomponent is the empty string — prevents stub empty HD objects from\n * leaking into XCN output (mirrors the CX/PL convention).\n *\n * @internal\n */\nfunction parseAssigningAuthority(\n comp: RawComponent | undefined,\n enc: EncodingCharacters,\n): HD | undefined {\n if (comp === undefined) return undefined;\n if (comp.subcomponents.every((s) => s === \"\")) return undefined;\n const synthetic: RawRepetition = {\n components: comp.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const hd = parseHd(synthetic, enc);\n return Object.keys(hd).length === 0 ? undefined : hd;\n}\n\n/**\n * Parse an HL7 v2 XCN repetition into a structured `XCN` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Component 9\n * (`assigningAuthority`) is parsed as a nested `HD`; see component table in\n * the `XCN` interface JSDoc for the v1 trimming.\n *\n * @example\n * ```ts\n * import { parseXcn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"1234567890\"] },\n * { subcomponents: [\"Smith\"] },\n * { subcomponents: [\"Jane\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"HOSP\", \"1.2.3\", \"ISO\"] },\n * { subcomponents: [\"L\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"NPI\"] },\n * ] };\n * const xcn = parseXcn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(xcn.idNumber); // \"1234567890\"\n * console.log(xcn.familyName); // \"Smith\"\n * console.log(xcn.assigningAuthority?.namespaceId); // \"HOSP\"\n * console.log(xcn.identifierTypeCode); // \"NPI\"\n * ```\n */\nexport function parseXcn(rep: RawRepetition, enc: EncodingCharacters): XCN {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XCN> = {};\n\n const idNumber = readComponent(rep, 0, enc);\n if (idNumber !== undefined) out.idNumber = idNumber;\n\n const familyName = readComponent(rep, 1, enc);\n if (familyName !== undefined) out.familyName = familyName;\n\n const givenName = readComponent(rep, 2, enc);\n if (givenName !== undefined) out.givenName = givenName;\n\n const secondName = readComponent(rep, 3, enc);\n if (secondName !== undefined) out.secondName = secondName;\n\n const suffix = readComponent(rep, 4, enc);\n if (suffix !== undefined) out.suffix = suffix;\n\n const prefix = readComponent(rep, 5, enc);\n if (prefix !== undefined) out.prefix = prefix;\n\n const degree = readComponent(rep, 6, enc);\n if (degree !== undefined) out.degree = degree;\n\n const sourceTable = readComponent(rep, 7, enc);\n if (sourceTable !== undefined) out.sourceTable = sourceTable;\n\n const assigningAuthority = parseAssigningAuthority(rep.components[8], enc);\n if (assigningAuthority !== undefined) out.assigningAuthority = assigningAuthority;\n\n const nameTypeCode = readComponent(rep, 9, enc);\n if (nameTypeCode !== undefined) out.nameTypeCode = nameTypeCode;\n\n const identifierCheckDigit = readComponent(rep, 10, enc);\n if (identifierCheckDigit !== undefined) out.identifierCheckDigit = identifierCheckDigit;\n\n const checkDigitScheme = readComponent(rep, 11, enc);\n if (checkDigitScheme !== undefined) out.checkDigitScheme = checkDigitScheme;\n\n const identifierTypeCode = readComponent(rep, 12, enc);\n if (identifierTypeCode !== undefined) out.identifierTypeCode = identifierTypeCode;\n\n return out;\n}\n","/**\n * XPN — HL7 v2 Extended Person Name composite. 14-component structured-name\n * shape parsed from a `RawRepetition` on demand by `Field.asXpn()` (wired in\n * Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes) —\n * NEVER set to `undefined`.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Extended Person Name (XPN) — structured name per HL7 Chapter 2. All\n * 14 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. familyName\n * 2. givenName\n * 3. secondName (or \"second and further given names\")\n * 4. suffix (e.g. Jr., III)\n * 5. prefix (e.g. Dr., Mrs.)\n * 6. degree (e.g. MD, PhD)\n * 7. nameTypeCode (L=Legal, M=Maiden, N=Nickname, S=Coded Pseudo-Name, ...)\n * 8. nameRepresentationCode\n * 9. nameContext (flattened to string in v1 — CWE nesting is out of scope)\n * 10. nameValidityRange\n * 11. nameAssemblyOrder (F=family first, G=given first)\n * 12. effectiveDate (raw HL7 TS string — caller may parse via parseDtm)\n * 13. expirationDate\n * 14. professionalSuffix\n *\n * @example\n * ```ts\n * import type { XPN } from \"@cosyte/hl7\";\n * const name: XPN = { familyName: \"Smith\", givenName: \"Jane\", prefix: \"Mrs.\" };\n * ```\n */\nexport interface XPN {\n readonly familyName?: string;\n readonly givenName?: string;\n readonly secondName?: string;\n readonly suffix?: string;\n readonly prefix?: string;\n readonly degree?: string;\n readonly nameTypeCode?: string;\n readonly nameRepresentationCode?: string;\n readonly nameContext?: string;\n readonly nameValidityRange?: string;\n readonly nameAssemblyOrder?: string;\n readonly effectiveDate?: string;\n readonly expirationDate?: string;\n readonly professionalSuffix?: string;\n}\n\n/**\n * Parse an HL7 v2 XPN repetition into a structured `XPN` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseXpn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"Smith\"] },\n * { subcomponents: [\"Jane\"] },\n * ] };\n * const xpn = parseXpn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(xpn.familyName); // \"Smith\"\n * console.log(xpn.givenName); // \"Jane\"\n * ```\n */\nexport function parseXpn(rep: RawRepetition, enc: EncodingCharacters): XPN {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XPN> = {};\n\n const familyName = readComponent(rep, 0, enc);\n if (familyName !== undefined) out.familyName = familyName;\n\n const givenName = readComponent(rep, 1, enc);\n if (givenName !== undefined) out.givenName = givenName;\n\n const secondName = readComponent(rep, 2, enc);\n if (secondName !== undefined) out.secondName = secondName;\n\n const suffix = readComponent(rep, 3, enc);\n if (suffix !== undefined) out.suffix = suffix;\n\n const prefix = readComponent(rep, 4, enc);\n if (prefix !== undefined) out.prefix = prefix;\n\n const degree = readComponent(rep, 5, enc);\n if (degree !== undefined) out.degree = degree;\n\n const nameTypeCode = readComponent(rep, 6, enc);\n if (nameTypeCode !== undefined) out.nameTypeCode = nameTypeCode;\n\n const nameRepresentationCode = readComponent(rep, 7, enc);\n if (nameRepresentationCode !== undefined) out.nameRepresentationCode = nameRepresentationCode;\n\n const nameContext = readComponent(rep, 8, enc);\n if (nameContext !== undefined) out.nameContext = nameContext;\n\n const nameValidityRange = readComponent(rep, 9, enc);\n if (nameValidityRange !== undefined) out.nameValidityRange = nameValidityRange;\n\n const nameAssemblyOrder = readComponent(rep, 10, enc);\n if (nameAssemblyOrder !== undefined) out.nameAssemblyOrder = nameAssemblyOrder;\n\n const effectiveDate = readComponent(rep, 11, enc);\n if (effectiveDate !== undefined) out.effectiveDate = effectiveDate;\n\n const expirationDate = readComponent(rep, 12, enc);\n if (expirationDate !== undefined) out.expirationDate = expirationDate;\n\n const professionalSuffix = readComponent(rep, 13, enc);\n if (professionalSuffix !== undefined) out.professionalSuffix = professionalSuffix;\n\n return out;\n}\n","/**\n * XTN — HL7 v2 Extended Telecommunication Number composite. 12-component\n * structured telecom shape (v1 trimmed from the HL7 v2.5 full 14-component\n * XTN — slots 13/14 are rarely-used legacy fields; v2 may restore the full\n * shape) parsed from a `RawRepetition` on demand by `Field.asXtn()` (wired\n * in Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes)\n * — NEVER set to `undefined`.\n *\n * Zero runtime deps — pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Extended Telecommunication Number (XTN) — structured telecom per\n * HL7 Chapter 2. All 12 v1 components are optional. Fields are OMITTED when\n * the underlying component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. telephoneNumber — formatted or unformatted phone number\n * 2. telecommunicationUseCode — PRN=Primary Residence, WPN=Work, NET=Internet,\n * ORN=Other Residence, BPN=Beeper, VHN=Vacation Home, ASN=Answering\n * Service, EMR=Emergency, ...\n * 3. telecommunicationEquipmentType — PH=Phone, FX=Fax, MD=Modem,\n * CP=Cellular Phone, BP=Beeper, Internet, X.400, TDD, TTY\n * 4. emailAddress\n * 5. countryCode (e.g. \"+1\")\n * 6. areaCityCode\n * 7. localNumber\n * 8. extension\n * 9. anyText — free-text note\n * 10. extensionPrefix (e.g. \"x\")\n * 11. speedDialCode\n * 12. unformattedTelephoneNumber\n *\n * @example\n * ```ts\n * import type { XTN } from \"@cosyte/hl7\";\n * const phone: XTN = {\n * telephoneNumber: \"(555) 555-1234\",\n * telecommunicationUseCode: \"WPN\",\n * telecommunicationEquipmentType: \"PH\",\n * };\n * ```\n */\nexport interface XTN {\n readonly telephoneNumber?: string;\n readonly telecommunicationUseCode?: string;\n readonly telecommunicationEquipmentType?: string;\n readonly emailAddress?: string;\n readonly countryCode?: string;\n readonly areaCityCode?: string;\n readonly localNumber?: string;\n readonly extension?: string;\n readonly anyText?: string;\n readonly extensionPrefix?: string;\n readonly speedDialCode?: string;\n readonly unformattedTelephoneNumber?: string;\n}\n\n/**\n * Parse an HL7 v2 XTN repetition into a structured `XTN` object. Components\n * are returned verbatim (already decoded once by the tokenizer — never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Components past\n * position 12 are silently ignored in v1.\n *\n * @example\n * ```ts\n * import { parseXtn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"555-1234\"] },\n * { subcomponents: [\"PRN\"] },\n * { subcomponents: [\"PH\"] },\n * ] };\n * const xtn = parseXtn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(xtn.telephoneNumber); // \"555-1234\"\n * ```\n */\nexport function parseXtn(rep: RawRepetition, enc: EncodingCharacters): XTN {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XTN> = {};\n\n const telephoneNumber = readComponent(rep, 0, enc);\n if (telephoneNumber !== undefined) out.telephoneNumber = telephoneNumber;\n\n const telecommunicationUseCode = readComponent(rep, 1, enc);\n if (telecommunicationUseCode !== undefined)\n out.telecommunicationUseCode = telecommunicationUseCode;\n\n const telecommunicationEquipmentType = readComponent(rep, 2, enc);\n if (telecommunicationEquipmentType !== undefined) {\n out.telecommunicationEquipmentType = telecommunicationEquipmentType;\n }\n\n const emailAddress = readComponent(rep, 3, enc);\n if (emailAddress !== undefined) out.emailAddress = emailAddress;\n\n const countryCode = readComponent(rep, 4, enc);\n if (countryCode !== undefined) out.countryCode = countryCode;\n\n const areaCityCode = readComponent(rep, 5, enc);\n if (areaCityCode !== undefined) out.areaCityCode = areaCityCode;\n\n const localNumber = readComponent(rep, 6, enc);\n if (localNumber !== undefined) out.localNumber = localNumber;\n\n const extension = readComponent(rep, 7, enc);\n if (extension !== undefined) out.extension = extension;\n\n const anyText = readComponent(rep, 8, enc);\n if (anyText !== undefined) out.anyText = anyText;\n\n const extensionPrefix = readComponent(rep, 9, enc);\n if (extensionPrefix !== undefined) out.extensionPrefix = extensionPrefix;\n\n const speedDialCode = readComponent(rep, 10, enc);\n if (speedDialCode !== undefined) out.speedDialCode = speedDialCode;\n\n const unformattedTelephoneNumber = readComponent(rep, 11, enc);\n if (unformattedTelephoneNumber !== undefined) {\n out.unformattedTelephoneNumber = unformattedTelephoneNumber;\n }\n\n return out;\n}\n","/**\n * `Field` — wrapper over a `RawField` exposing HL7 null/empty discrimination\n * (`isNull`), the raw repetitions tree, and a convenience `value` getter that\n * reads the first subcomponent of the first component of the first\n * repetition. Constructed internally by `Segment.field(n)`; user code never\n * calls `new Field(...)` directly.\n *\n * Typed composite coercions (`asXpn`, `asXad`, `asCx`, `asCwe`, `asCe`,\n * `asXtn`, `asPl`, `asTs`, `asNm`, `asHd`) delegate to the corresponding\n * composite parsers from `./types/*`. Coercions are lazy and NOT memoized\n * in v1 (D-09) — each call re-parses the first repetition. Empty fields\n * return empty typed objects (`{}` for optional-field composites,\n * `{ raw: \"\", date: undefined }` / `{ raw: \"\", value: undefined }` for\n * the TS/NM scalar composites).\n */\n\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport { emitField } from \"../serialize/emit-field.js\";\nimport type { EncodingCharacters, Hl7Position, RawField, RawRepetition } from \"../parser/types.js\";\nimport { parseCe, type CE } from \"./types/ce.js\";\nimport { parseCwe, type CWE } from \"./types/cwe.js\";\nimport { parseCx, type CX } from \"./types/cx.js\";\nimport { parseHd, type HD } from \"./types/hd.js\";\nimport { parseNm, type NM } from \"./types/nm.js\";\nimport { parsePl, type PL } from \"./types/pl.js\";\nimport { parseSn, type SN } from \"./types/sn.js\";\nimport { parseTs, type TS } from \"./types/ts.js\";\nimport { parseXad, type XAD } from \"./types/xad.js\";\nimport { parseXcn, type XCN } from \"./types/xcn.js\";\nimport { parseXpn, type XPN } from \"./types/xpn.js\";\nimport { parseXtn, type XTN } from \"./types/xtn.js\";\n\n/** Default position used by the shared empty-Field sentinel. @internal */\nconst DEFAULT_POSITION: Hl7Position = { segmentIndex: 0 };\n\n/**\n * Wrapper over a `RawField` exposing HL7 null/empty discrimination\n * (`isNull`), the repetitions tree, and a decoded `value` getter.\n * `seg.field(3) === seg.field(3)` — Field instances are referentially stable\n * per segment position (D-12).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * console.log(pid5?.value); // \"Smith\" — decoded at parse\n * console.log(pid5?.isNull); // false — HL7 explicit null is \"\", absent is not\n * console.log(pid5?.repetitions.length); // 1\n * ```\n */\nexport class Field {\n /** HL7 null indicator — `true` iff the underlying field was the two-char literal `\"\"`. */\n public readonly isNull: boolean;\n\n /** Reference to the underlying `RawField.repetitions` (no defensive copy). */\n public readonly repetitions: readonly RawRepetition[];\n\n /** The 5 encoding characters for this message. Exposed for composite parsers (Plan 04). @internal */\n public readonly enc: EncodingCharacters;\n\n /** Position of this field in the parent message — used for position-aware error messages. @internal */\n public readonly position: Hl7Position;\n\n /** The full `RawField` this wrapper wraps. Exposed for composite parsers (Plan 02/03/04). @internal */\n public readonly raw: RawField;\n\n /**\n * Construct a new `Field`. Called internally by `Segment.field(n)`; user\n * code should obtain `Field` instances via `msg.segments(type)[i].field(n)`.\n * @internal\n */\n public constructor(raw: RawField, enc: EncodingCharacters, position: Hl7Position) {\n this.raw = raw;\n this.isNull = raw.isNull;\n this.repetitions = raw.repetitions;\n this.enc = enc;\n this.position = position;\n }\n\n /**\n * First-repetition, first-component, first-subcomponent value as a decoded\n * string — unescaped ONCE by the tokenizer on parse, returned verbatim here\n * (never re-unescaped, HL7-VALUE-REDECODE). Returns `\"\"` when the field is\n * empty or HL7 null. Equivalent to `msg.get('SEG.N')` for a top-level access.\n *\n * @example\n * ```ts\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * // wire \"Smith\\F\\Jr\" was decoded at parse → the field separator escape:\n * console.log(pid5?.value); // \"Smith|Jr\"\n * ```\n */\n public get value(): string {\n const rep = this.repetitions[0];\n if (rep === undefined) return \"\";\n const comp = rep.components[0];\n if (comp === undefined) return \"\";\n const sub = comp.subcomponents[0];\n if (sub === undefined) return \"\";\n // The tokenizer already unescaped every subcomponent on parse (parser-02),\n // so the stored value is decoded — return it directly. Re-unescaping here\n // would double-decode a value whose own bytes look like an escape (a wire\n // `\\E\\F\\E\\` decodes to `\\F\\`, which a second pass would wrongly turn into\n // `|`). Emit fidelity is handled separately by the raw overlay (HL7-ESC).\n return sub;\n }\n\n /**\n * The field's **canonical wire text** — the full field re-serialized with\n * the active delimiters and re-escaped content (repetitions, components,\n * and subcomponents included). Contrast with {@link value}, which\n * returns only the first subcomponent of the first component of the first\n * repetition (decoded once at parse — never re-unescaped).\n *\n * Use this when a field must be compared or echoed as a whole — e.g.\n * correlating an ACK's MSA-2 against the inbound MSH-10, where a\n * vendor-quirk control id containing an unescaped delimiter (`ID^X`) must\n * not be truncated to its first component.\n *\n * **Byte-verbatim for parsed content (HL7-ESC).** The parse pipeline stores\n * *decoded* content, but also records the original wire bytes of any escape\n * whose decode is not byte-faithful (`RawComponent.rawSubcomponents`), so\n * re-serialization preserves the sender's exact escape bytes: hex escapes\n * stay hex (`A\\X41\\B`, casing intact), and recognize-and-preserve sequences\n * (`\\H\\`, `\\N\\`, formatting/charset/vendor escapes) re-emit **verbatim**\n * rather than as escaped literal text. Delimiter/newline escapes and plain\n * content round-trip byte-exact via the re-escape path. The only remaining\n * canonicalization is structural: trailing insignificant empties are\n * stripped (D-02), and a field built by hand (not parsed) re-escapes its\n * decoded value since it has no overlay.\n *\n * **MSH-1/MSH-2 caveat.** Like {@link value}, calling this on MSH-1 or\n * MSH-2 (the delimiter-definition fields) re-escapes the encoding\n * characters themselves and produces garbage — those two fields are only\n * meaningful through `Hl7Message.encodingCharacters`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(\"MSH|^~\\\\&|A|B|C|D|20260101||ADT^A01|ID^X|P|2.5\\r\");\n * msg.segments(\"MSH\")[0]?.field(10).value; // \"ID\" (first component only)\n * msg.segments(\"MSH\")[0]?.field(10).text; // \"ID^X\" (verbatim wire text)\n * ```\n */\n public get text(): string {\n return emitField(this.raw, this.enc);\n }\n\n /**\n * Return a synthetic empty `Field` sentinel — used by `Segment.field(n)` to\n * honor MODEL-05's \"never throws on missing\" contract. The returned Field\n * has `isNull === false`, `repetitions === []`, and `value === \"\"`.\n * Referentially stable across calls (same instance returned each time).\n *\n * The `enc` argument is accepted for API symmetry but ignored — the\n * synthetic field carries no content, so unescape would be a no-op\n * regardless of the active encoding characters.\n *\n * @example\n * ```ts\n * const empty = Field.empty(msg.encodingCharacters);\n * console.log(empty.value); // \"\"\n * ```\n * @internal\n */\n public static empty(_enc: EncodingCharacters): Field {\n return EMPTY_FIELD;\n }\n\n /**\n * Coerce this field's first repetition to a typed `XPN` (Extended Person\n * Name). Absent components are OMITTED from the result\n * (`exactOptionalPropertyTypes`). Not memoized in v1 — each call re-parses\n * (D-09).\n *\n * @example\n * ```ts\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * const name = pid5?.asXpn();\n * console.log(name?.familyName, name?.givenName);\n * ```\n */\n public asXpn(): XPN {\n return parseXpn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `XAD` (Extended Address).\n *\n * @example\n * ```ts\n * const addr = msg.segments(\"PID\")[0]?.field(11)?.asXad();\n * console.log(addr?.street, addr?.city, addr?.stateOrProvince);\n * ```\n */\n public asXad(): XAD {\n return parseXad(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `CX` (Extended Composite\n * ID). `assigningAuthority` is a nested `HD`.\n *\n * @example\n * ```ts\n * const mrn = msg.segments(\"PID\")[0]?.field(3)?.asCx();\n * console.log(mrn?.idNumber, mrn?.assigningAuthority?.namespaceId);\n * ```\n */\n public asCx(): CX {\n return parseCx(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `CWE` (Coded With\n * Exceptions).\n *\n * @example\n * ```ts\n * const code = msg.segments(\"OBX\")[0]?.field(3)?.asCwe();\n * console.log(code?.identifier, code?.text);\n * ```\n */\n public asCwe(): CWE {\n return parseCwe(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `CE` (Coded Element).\n *\n * @example\n * ```ts\n * const code = msg.segments(\"OBX\")[0]?.field(3)?.asCe();\n * console.log(code?.identifier, code?.text);\n * ```\n */\n public asCe(): CE {\n return parseCe(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `XTN` (Extended\n * Telecommunication Number).\n *\n * @example\n * ```ts\n * const phone = msg.segments(\"PID\")[0]?.field(13)?.asXtn();\n * console.log(phone?.telephoneNumber);\n * ```\n */\n public asXtn(): XTN {\n return parseXtn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `PL` (Person Location).\n * `facility` is a nested `HD`.\n *\n * @example\n * ```ts\n * const loc = msg.segments(\"PV1\")[0]?.field(3)?.asPl();\n * console.log(loc?.pointOfCare, loc?.room, loc?.facility?.namespaceId);\n * ```\n */\n public asPl(): PL {\n return parsePl(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `TS` (Time Stamp) — the\n * fidelity `DtmParts` (raw + parts + precision + timezone). `valid` is\n * `false` on unparseable input (no throw). Build an absolute instant only on\n * explicit request via `dtmToDate(ts)`.\n *\n * @example\n * ```ts\n * const ts = msg.segments(\"MSH\")[0]?.field(7)?.asTs();\n * console.log(ts?.raw, ts?.precision, ts?.hasTimezone);\n * ```\n */\n public asTs(): TS {\n return parseTs(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `NM` (Numeric).\n * `{ raw, value }` — `value` is `undefined` on non-numeric input.\n *\n * @example\n * ```ts\n * const nm = msg.segments(\"OBX\")[0]?.field(5)?.asNm();\n * console.log(nm?.value);\n * ```\n */\n public asNm(): NM {\n return parseNm(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `SN` (Structured Numeric),\n * or `undefined` when the field carries no usable structured-numeric content.\n * Use for an OBX-5 whose OBX-2 value type is `SN` (a comparator like `>90`,\n * a range like `100-200`, or a ratio like `1:128`). `num1`/`num2` are\n * `number | undefined` (never `NaN`); the comparator is surfaced only when\n * SN.1 is a recognized operator.\n *\n * @example\n * ```ts\n * const sn = msg.segments(\"OBX\")[0]?.field(5)?.asSn();\n * console.log(sn?.comparator, sn?.num1); // \">\" 90\n * ```\n */\n public asSn(): SN | undefined {\n return parseSn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `HD` (Hierarchic\n * Designator).\n *\n * @example\n * ```ts\n * const sending = msg.segments(\"MSH\")[0]?.field(3)?.asHd();\n * console.log(sending?.namespaceId);\n * ```\n */\n public asHd(): HD {\n return parseHd(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `XCN` (Extended Composite\n * ID Number and Name for Persons). `assigningAuthority` is a nested `HD`.\n * Common on OBR-16 (ordering provider), PV1-7 (attending doctor), PV1-8\n * (referring doctor). Empty field → `{}` (never throws).\n *\n * @example\n * ```ts\n * const orderedBy = msg.segments(\"OBR\")[0]?.field(16)?.asXcn();\n * console.log(orderedBy?.idNumber, orderedBy?.familyName, orderedBy?.identifierTypeCode);\n * ```\n */\n public asXcn(): XCN {\n return parseXcn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n}\n\nconst EMPTY_RAW_FIELD: RawField = Object.freeze({\n repetitions: Object.freeze([]),\n isNull: false,\n});\n\nconst EMPTY_FIELD = new Field(EMPTY_RAW_FIELD, DEFAULT_ENCODING_CHARACTERS, DEFAULT_POSITION);\n\n/**\n * Synthetic empty repetition — feeds composite parsers for empty fields so\n * they return `{}` / empty typed objects instead of throwing. Shared across\n * every `.asXxx()` coercion. Frozen so no parser can mutate the sentinel.\n * @internal\n */\nconst EMPTY_REP: RawRepetition = Object.freeze({\n components: Object.freeze([]),\n});\n","/**\n * `Segment` — wrapper class over a `RawSegment` that exposes `field(n)` with\n * referentially stable `Field` instances (D-12). Constructed internally by\n * `Hl7Message.segments(type)` / `Hl7Message.allSegments()`; user code never\n * calls `new Segment(...)` directly.\n *\n * The wrapper does NOT copy `raw.fields` — it holds a reference so mutations\n * through Plan 04's `setField` / `addSegment` / `removeSegment` stay visible.\n */\n\nimport { Field } from \"./field.js\";\nimport type { EncodingCharacters, RawField, RawSegment } from \"../parser/types.js\";\n\n/**\n * Wrapper over a `RawSegment` exposing typed per-position `Field` instances.\n * `seg.field(3) === seg.field(3)` — referential stability is guaranteed per\n * segment instance.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const pid = msg.segments(\"PID\")[0];\n * if (pid !== undefined) console.log(pid.field(5).value);\n * ```\n */\nexport class Segment {\n /** Segment name (3 chars, e.g. `\"PID\"`, `\"OBX\"`, `\"ZPI\"`). */\n public readonly type: string;\n\n /** Reference to the underlying `RawSegment.fields` — 1-indexed per HL7 convention. */\n public readonly fields: readonly RawField[];\n\n /** The 5 encoding characters for this message. Exposed for composite parsers. @internal */\n public readonly enc: EncodingCharacters;\n\n /** Absolute index of this segment in `Hl7Message.rawSegments[]`. Used for position tracking. @internal */\n public readonly absoluteIndex: number;\n\n /** The full `RawSegment` this wrapper wraps. Exposed for mutation methods (Plan 04). @internal */\n public readonly raw: RawSegment;\n\n /**\n * Lookup map from profile-declared field name → 1-indexed HL7 position.\n * Absent when no profile was applied to the parent message, or when the\n * applied profile does not declare `customSegments` for this segment's\n * type. Consumed by `get(name)` to resolve named-field access (PROF-07).\n * @internal\n */\n public readonly customFields: Readonly<Record<string, number>> | undefined;\n\n /** Lazy cache of Field wrappers — one per fields[] position. @internal */\n private _fieldWrappers: Field[] | undefined;\n\n /**\n * Construct a new `Segment`. Called internally by `Hl7Message`; user code\n * should obtain `Segment` instances via `msg.segments(type)` or\n * `msg.allSegments()`.\n *\n * The optional `customFields` parameter is the per-segment slice of the\n * applied profile's merged `customSegments` map (PROF-07 / D-16). When\n * supplied, `get(name)` resolves names against it; otherwise `get(name)`\n * always returns `undefined`.\n * @internal\n */\n public constructor(\n raw: RawSegment,\n enc: EncodingCharacters,\n absoluteIndex: number,\n customFields?: Readonly<Record<string, number>>,\n ) {\n this.raw = raw;\n this.type = raw.name;\n this.fields = raw.fields;\n this.enc = enc;\n this.absoluteIndex = absoluteIndex;\n this.customFields = customFields;\n }\n\n /**\n * Return the `Field` wrapper at HL7 position `n`. Indexing follows the HL7\n * 1-indexed convention — `seg.field(5)` on a PID segment maps to PID-5.\n * MSH segments use the same user-facing convention: `msh.field(1)` returns\n * the field-separator (MSH-1), `msh.field(2)` returns encoding chars\n * (MSH-2), `msh.field(3)` returns MSH-3, and so on — the internal\n * `fields[N-1]` offset for MSH segments is applied here (mirrors the\n * dot-path resolver in `dot-path.ts`, keeping `msg.segments('MSH')[0].field(3)`\n * and `msg.get('MSH.3')` in agreement).\n *\n * Returns a synthetic empty `Field` (`.isNull === false`, `.value === \"\"`)\n * when `n` is out of range — never throws (MODEL-05). Successive calls with\n * the same `n` return the same `Field` instance (D-12).\n *\n * @example\n * ```ts\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * console.log(pid5?.value); // \"Smith\"\n * const msh3 = msg.segments(\"MSH\")[0]?.field(3);\n * console.log(msh3?.value); // sending application (HL7 MSH-3)\n * ```\n */\n public field(n: number): Field {\n if (this._fieldWrappers === undefined) {\n // Build the full wrapper array. O(k) where k = fields.length; cached.\n this._fieldWrappers = this.fields.map(\n (rf, i) =>\n new Field(rf, this.enc, {\n segmentIndex: this.absoluteIndex,\n fieldIndex: i,\n }),\n );\n }\n // MSH offset: HL7 MSH-1 lives at fields[0] (separator), MSH-2 at fields[1]\n // (encoding chars), MSH-3 at fields[2], etc. Non-MSH segments use a\n // straight 1:1 mapping because fields[0] is the segment-name placeholder.\n const idx = this.type === \"MSH\" ? n - 1 : n;\n const f = this._fieldWrappers[idx];\n return f ?? Field.empty(this.enc);\n }\n\n /**\n * Return the `Field` at the profile-declared position for `name`, or\n * `undefined` when no custom mapping exists (PROF-07). Unlike `field(n)`,\n * missing names return `undefined` — NOT a synthetic empty Field — so\n * typos surface instead of silently resolving to an empty string (D-14).\n *\n * For segments without a profile-declared customSegments slice (most\n * non-Z segments, and any Z-segment whose host message had no profile\n * applied), this method always returns `undefined` (D-15 defense-in-depth\n * — D-05 already rejects standard-segment overlays at `defineProfile()`\n * time).\n *\n * When the declared position is out of range for the underlying\n * `RawSegment.fields`, `get(name)` returns `undefined` (NOT a\n * synthetic-empty Field) so callers can distinguish \"name not declared\"\n * from \"name declared but position missing in the raw message\" only at\n * the presence level (both collapse to `undefined` per D-14).\n *\n * @example\n * ```ts\n * const zpi = msg.allSegments().find((s) => s.type === \"ZPI\");\n * console.log(zpi?.get(\"encounterId\")?.value);\n * ```\n */\n public get(name: string): Field | undefined {\n const position = this.customFields?.[name];\n if (position === undefined) return undefined;\n // Delegate to field(n) for MSH-offset + wrapper-cache consistency.\n // field(n) returns Field.empty(enc) when out-of-range; we check whether\n // the field has content and return undefined for out-of-range so typos\n // surface (not a silent-empty read).\n const f = this.field(position);\n // Treat \"field has no repetitions AND not explicit-null\" as out-of-range.\n if (f.repetitions.length === 0 && !f.isNull) return undefined;\n return f;\n }\n}\n","/**\n * `allergies` — Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * AL1 segment in document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no AL1 present.\n * - D-06: NOT memoized — each call re-walks `msg.segments(\"AL1\")`.\n * - Phase N: `onsetDate` is the fidelity `TS` (precision + timezone preserved).\n * - D-22: never throws — empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"AL1\")`):\n * - `type` ← AL1-2 (IS — \"DA\"/\"FA\"/\"MA\"/\"EA\"/...)\n * - `code` ← AL1-3 (CWE)\n * - `severity` ← AL1-4 (IS — \"SV\"/\"MO\"/\"MI\")\n * - `reaction` ← AL1-5 (string / CWE first value)\n * - `onsetDate` ← AL1-6 (TS/DT → fidelity `TS`, Phase N)\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Allergy } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/**\n * Every AL1 as an `Allergy` entry in document order. D-05: returns `[]` when\n * no AL1 is present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const al of msg.allergies()) {\n * console.log(al.code?.identifier, al.severity, al.onsetDate?.raw);\n * }\n * ```\n *\n * @internal\n */\nexport function allergies(msg: Hl7Message): readonly Allergy[] {\n const out: Allergy[] = [];\n for (const al1 of msg.segments(\"AL1\")) {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<Allergy> = {};\n\n const type = stringOrUndefined(al1.field(2).value);\n if (type !== undefined) entry.type = type;\n\n const code = al1.field(3).asCwe();\n if (Object.keys(code).length > 0) entry.code = code;\n\n const severity = stringOrUndefined(al1.field(4).value);\n if (severity !== undefined) entry.severity = severity;\n\n const reaction = stringOrUndefined(al1.field(5).value);\n if (reaction !== undefined) entry.reaction = reaction;\n\n const onset = al1.field(6).asTs();\n if (onset.valid) entry.onsetDate = onset;\n\n out.push(Object.freeze(entry));\n }\n return Object.freeze(out);\n}\n","/**\n * `appointments` — Phase Q (scheduling breadth) implementation of the SIU\n * appointment extractor. Walks the message in document order and projects each\n * SCH (Scheduling Activity Information) segment into a typed {@link Appointment},\n * grouping the AIS/AIG/AIL/AIP resource segments that follow it positionally\n * under that SCH — the same open-a-group-on-the-anchor state machine\n * `immunizations()` uses for ORC→RXA→[RXR]. Covers the common SIU trigger\n * events (S12 new / S13 reschedule / S14 modify / S15 cancel / S26 no-show).\n *\n * Field map (HL7 v2 Ch. 10 — scheduling):\n * - SCH-1 placer appointment ID (EI; first component surfaced verbatim)\n * - SCH-2 filler appointment ID (EI; first component surfaced verbatim)\n * - SCH-11 appointment timing quantity (TQ) — TQ.4 start / TQ.5 end (DTM)\n * - SCH-25 filler status code (CWE — HL7 Table 0278): the appointment status\n * - AIS-3 universal service ID (CE) → resource kind \"service\"\n * - AIG-3 general resource ID (CE) → resource kind \"general\"\n * - AIL-3 location resource (PL / coded) → resource kind \"location\"\n * - AIP-3 personnel resource (XCN) → resource kind \"personnel\" (provider)\n *\n * Safety rules enforced here (Phase Q §Fail-safe):\n * - Never throws — a malformed SCH / AI* surfaces as omitted keys (HELPERS-07).\n * - The filler status code (SCH-25) is surfaced VERBATIM (provenance-only) — a\n * mis-keyed status is echoed exactly, never normalized or validated.\n * - Missing fields → keys omitted; `resources` is ALWAYS a (possibly empty) array.\n * - Output is frozen at the boundary (D-01); NOT memoized (D-06).\n *\n * Known limitations: this covers the appointment-level identifiers, status,\n * SCH-11 timing, and the AI* resource identifiers only — it is NOT a\n * scheduling-workflow state machine, and it does not resolve per-resource start\n * offsets/durations. See KNOWN-LIMITATIONS.md.\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { RawComponent } from \"../parser/types.js\";\nimport { parseDtm } from \"../parser/dates.js\";\nimport { readSubcomponent } from \"../model/types/_shared.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\n\nimport type { Appointment, AppointmentResource } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so an optional CWE key stays absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/** First repetition's component at `index` (or `undefined`). @internal */\nfunction componentAt(field: Field, index: number): RawComponent | undefined {\n return field.repetitions[0]?.components[index];\n}\n\n/** Read `field`'s first-repetition component `compIdx`, subcomponent `subIdx`, unescaped. @internal */\nfunction fieldSub(field: Field, compIdx: number, subIdx: number): string | undefined {\n return readSubcomponent(componentAt(field, compIdx), subIdx, field.enc);\n}\n\n/**\n * The AI* segment types that carry an appointment resource, mapped to the\n * `kind` surfaced on {@link AppointmentResource}. AIP is the personnel\n * (provider) resource; AIL the location. @internal\n */\nconst RESOURCE_KIND: Readonly<Record<string, AppointmentResource[\"kind\"]>> = Object.freeze({\n AIS: \"service\",\n AIG: \"general\",\n AIL: \"location\",\n AIP: \"personnel\",\n});\n\n/**\n * Build one {@link AppointmentResource} from an AI* segment. The resource id\n * lives at position 3 for all four segment types; AIP-3 is an `XCN` (personnel)\n * and is additionally surfaced as `person`, while AIS/AIG/AIL-3 surface as a\n * coded `code` (first component verbatim). Returns `undefined` when the segment\n * carries no resource id at all. @internal\n */\nfunction buildResource(seg: Segment): AppointmentResource | undefined {\n const kind = RESOURCE_KIND[seg.type];\n if (kind === undefined) return undefined;\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<AppointmentResource> = { kind };\n\n const field3 = seg.field(3);\n if (kind === \"personnel\") {\n const person: XCN = field3.asXcn();\n if (Object.keys(person).length > 0) out.person = person;\n }\n // Every AI*-3 is surfaced as a coded element too (provenance-only, first\n // component verbatim) so a uniform `code.identifier` is always available.\n const code = cweOrUndefined(field3);\n if (code !== undefined) out.code = code;\n\n // A resource with no id at all is not worth surfacing.\n if (out.code === undefined && out.person === undefined) return undefined;\n return Object.freeze(out) as AppointmentResource;\n}\n\n/** Build a frozen {@link Appointment} from one SCH + its attached AI* resources. @internal */\nfunction finalizeAppointment(sch: Segment, resources: readonly AppointmentResource[]): Appointment {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Appointment> = { resources: Object.freeze(resources.slice()) };\n\n // SCH-1 / SCH-2 appointment ids (EI) — first component surfaced verbatim.\n const placer = stringOrUndefined(sch.field(1).value);\n if (placer !== undefined) out.placerAppointmentId = placer;\n const filler = stringOrUndefined(sch.field(2).value);\n if (filler !== undefined) out.fillerAppointmentId = filler;\n\n // SCH-11 appointment timing quantity (TQ): TQ.4 start / TQ.5 end (DTM).\n const timing = sch.field(11);\n const startRaw = fieldSub(timing, 3, 0);\n if (startRaw !== undefined) out.startDateTime = parseDtm(startRaw);\n const endRaw = fieldSub(timing, 4, 0);\n if (endRaw !== undefined) out.endDateTime = parseDtm(endRaw);\n\n // SCH-25 filler status code (Table 0278) — verbatim/provenance-only.\n const status = cweOrUndefined(sch.field(25));\n if (status !== undefined) out.fillerStatusCode = status;\n\n return Object.freeze(out) as Appointment;\n}\n\n/**\n * Every SCH of an SIU message as a typed {@link Appointment}, with the\n * AIS/AIG/AIL/AIP resource segments that follow it grouped positionally under\n * that SCH (service / general resource / location / personnel). Document order.\n * Returns `[]` when no SCH is present. NOT memoized — each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * The filler status code (SCH-25, Table 0278) is surfaced verbatim; per-resource\n * offsets/durations and the full scheduling workflow are out of scope (see the\n * package known-limitations).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const appt of msg.appointments()) {\n * console.log(appt.fillerAppointmentId, appt.fillerStatusCode?.identifier);\n * console.log(appt.startDateTime?.raw, appt.endDateTime?.raw);\n * for (const r of appt.resources) console.log(r.kind, r.code?.identifier, r.person?.familyName);\n * }\n * ```\n *\n * @internal\n */\nexport function appointments(msg: Hl7Message): readonly Appointment[] {\n const out: Appointment[] = [];\n\n let currentSch: Segment | undefined;\n let resources: AppointmentResource[] = [];\n\n const closeCurrent = (): void => {\n if (currentSch !== undefined) out.push(finalizeAppointment(currentSch, resources));\n };\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"SCH\") {\n closeCurrent();\n currentSch = seg;\n resources = [];\n continue;\n }\n if (currentSch === undefined) continue; // AI* before any SCH — dropped.\n if (RESOURCE_KIND[seg.type] !== undefined) {\n const resource = buildResource(seg);\n if (resource !== undefined) resources.push(resource);\n }\n }\n\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `charges` — Phase Q (financial breadth) implementation of the DFT charge\n * extractor. Walks the message in document order and projects each FT1\n * (Financial Transaction) segment into a typed {@link Charge}. Flat, one FT1\n * per {@link Charge} (parity with `diagnoses()` / `allergies()`) — DFT^P03 posts\n * a list of financial transactions, each self-contained. Covers the common\n * DFT^P03 post-charges event.\n *\n * Field map (HL7 v2 Ch. 6 — financial management):\n * - FT1-4 transaction date (TS)\n * - FT1-6 transaction type (IS — Table 0017: CG charge / CD credit /\n * PY payment / AJ adjustment; verbatim)\n * - FT1-7 transaction code (CE — the institution charge/procedure code)\n * - FT1-10 transaction quantity (NM)\n * - FT1-11 transaction amount, extended (CP) — surfaced as canonical wire text\n * - FT1-12 transaction amount, unit (CP) — surfaced as canonical wire text\n * - FT1-19 diagnosis code(s) (CE, repeating) — billing diagnosis linkage\n *\n * Safety rules enforced here (Phase Q §Fail-safe):\n * - Never throws — a malformed FT1 surfaces as omitted keys (HELPERS-07).\n * - **No billing logic, no money-as-float.** The extended/unit amounts (CP)\n * are surfaced as their canonical wire text (`amountExtended`/`amountUnit`),\n * never parsed to a `number` — currency + price are preserved intact and no\n * rounding is ever introduced. `Field.text` is byte-exact for a plain numeric\n * amount (`150.00^USD`); it canonicalizes only escape sequences + trailing\n * empty components (D-02), which a CP amount does not carry. The transaction\n * type + code are provenance-only; nothing is validated, priced, or adjudicated.\n * - Missing fields → keys omitted; `diagnoses` is ALWAYS a (possibly empty)\n * array.\n * - Output is frozen at the boundary (D-01); NOT memoized (D-06).\n *\n * Known limitations: `charges()` surfaces billing-critical FT1 fields only. It\n * is NOT a claims/pricing engine — no charge validation, no adjudication, no\n * amount arithmetic. See KNOWN-LIMITATIONS.md.\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport { parseCwe, type CWE } from \"../model/types/cwe.js\";\n\nimport type { Charge } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so an optional CWE key stays absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Every repetition of a repeating coded field as a `CWE`, dropping empty\n * repetitions. Used for FT1-19 (diagnosis linkage, repeating CE). @internal\n */\nfunction repeatingCwe(field: Field): readonly CWE[] {\n const out: CWE[] = [];\n for (const rep of field.repetitions) {\n const cwe = parseCwe(rep, field.enc);\n if (Object.keys(cwe).length > 0) out.push(Object.freeze(cwe));\n }\n return out;\n}\n\n/** Build a frozen {@link Charge} from one FT1 segment. @internal */\nfunction finalizeCharge(ft1: Segment): Charge {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Charge> = { diagnoses: Object.freeze(repeatingCwe(ft1.field(19))) };\n\n // FT1-4 transaction date (fidelity TS, Phase N).\n const transactionDate = ft1.field(4).asTs();\n if (transactionDate.raw !== \"\") out.transactionDate = transactionDate;\n\n // FT1-6 transaction type (Table 0017) — verbatim.\n const transactionType = stringOrUndefined(ft1.field(6).value);\n if (transactionType !== undefined) out.transactionType = transactionType;\n\n // FT1-7 transaction code — institution charge/procedure code (CWE).\n const transactionCode = cweOrUndefined(ft1.field(7));\n if (transactionCode !== undefined) out.transactionCode = transactionCode;\n\n // FT1-10 transaction quantity (NM) — strict-parsed, never NaN.\n const quantity = ft1.field(10).asNm().value;\n if (quantity !== undefined) out.quantity = quantity;\n\n // FT1-11 / FT1-12 extended / unit amount (CP) — canonical wire text, never a float.\n const amountExtended = stringOrUndefined(ft1.field(11).text);\n if (amountExtended !== undefined) out.amountExtended = amountExtended;\n const amountUnit = stringOrUndefined(ft1.field(12).text);\n if (amountUnit !== undefined) out.amountUnit = amountUnit;\n\n return Object.freeze(out) as Charge;\n}\n\n/**\n * Every FT1 of a DFT message as a typed {@link Charge}, one per FT1 in document\n * order. Returns `[]` when no FT1 is present. NOT memoized — each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * Billing-critical fields are surfaced (transaction type/code, extended/unit\n * amount, diagnosis linkage); there is **no billing logic and no money-as-float**\n * — amounts are the canonical CP wire text (byte-exact for a plain numeric\n * amount), never a `number`. See {@link Charge}.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const charge of msg.charges()) {\n * console.log(charge.transactionType, charge.transactionCode?.identifier);\n * console.log(charge.amountExtended); // e.g. \"150.00^USD\" — wire text, never a number\n * for (const dx of charge.diagnoses) console.log(dx.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function charges(msg: Hl7Message): readonly Charge[] {\n const out: Charge[] = [];\n for (const seg of msg.allSegments()) {\n if (seg.type === \"FT1\") out.push(finalizeCharge(seg));\n }\n return Object.freeze(out);\n}\n","/**\n * `diagnoses` — Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * DG1 segment in document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no DG1 present.\n * - D-06: NOT memoized — each call re-walks `msg.segments(\"DG1\")`.\n * - Phase N: `dateTime` is the fidelity `TS` (precision + timezone preserved).\n * - D-22: never throws — empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"DG1\")`):\n * - `code` ← DG1-3 (CWE)\n * - `description` ← DG1-4 (ST)\n * - `dateTime` ← DG1-5 (TS/DT → fidelity `TS`, Phase N)\n * - `type` ← DG1-6 (IS — \"A\"=admit, \"W\"=working, \"F\"=final)\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Diagnosis } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/**\n * Every DG1 as a `Diagnosis` entry in document order. D-05: returns `[]` when\n * no DG1 is present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const dg of msg.diagnoses()) {\n * console.log(dg.code?.identifier, dg.description, dg.type);\n * }\n * ```\n *\n * @internal\n */\nexport function diagnoses(msg: Hl7Message): readonly Diagnosis[] {\n const out: Diagnosis[] = [];\n for (const dg1 of msg.segments(\"DG1\")) {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<Diagnosis> = {};\n\n const code = dg1.field(3).asCwe();\n if (Object.keys(code).length > 0) entry.code = code;\n\n const description = stringOrUndefined(dg1.field(4).value);\n if (description !== undefined) entry.description = description;\n\n const dt = dg1.field(5).asTs();\n if (dt.valid) entry.dateTime = dt;\n\n const type = stringOrUndefined(dg1.field(6).value);\n if (type !== undefined) entry.type = type;\n\n out.push(Object.freeze(entry));\n }\n return Object.freeze(out);\n}\n","/**\n * `groupNotes` / `notes` — Phase P implementation of NTE narrative grouping.\n * Groups **NTE** (Notes and Comments) segments to their parent **by position**:\n * an NTE inherits its meaning entirely from the segment that immediately\n * precedes it (HL7 v2 Ch. 2 — the NTE carries no link field, so attachment is\n * purely positional). In an ORU the grammar is\n * `{ [ORC] OBR [{NTE}] [{ [OBX] [{NTE}] }] }`, so a note after OBR is\n * order-level and a note after OBX is *that* result-level (Ch. 7).\n *\n * Recognized parents and where their notes surface:\n * - `PID` → the patient view (`msg.patient.notes`).\n * - `ORC` / `OBR` → the order (`order.notes`).\n * - `OBX` → that specific observation (`observation.notes`).\n *\n * Design decisions enforced here:\n * - **Positional, never guessed.** The parent is the nearest *preceding\n * non-NTE* segment (consecutive NTEs chain to the same parent). Any\n * non-NTE segment that is NOT a recognized parent (e.g. `PV1`, `AL1`,\n * `MSH`) resets the target — a subsequent NTE is then surfaced\n * message-level, not attached to an unrelated earlier parent (fail safe;\n * the spec's \"profile-specific placement outside the common patterns is\n * surfaced message-level, not guessed\").\n * - **Never dropped — even when the parent's helper projection is dropped.**\n * A note whose recognized parent is *not* surfaced by any helper falls to\n * the message-level `unattached` bucket rather than vanishing. Two such\n * cases: (1) a **later PID** in a multi-patient ORU (`msg.patient` is the\n * first PID only), and (2) an **ORC region that never opens an order** — a\n * trailing/dangling ORC with no following OBR. To handle the ORC↔order\n * relationship, notes seen after an `ORC` (before its OBR) are **buffered**\n * and flushed onto the OBR that opens the order (in document order, ahead of\n * the OBR's own notes) — exactly mirroring how `orders()` promotes a pending\n * ORC. Several ORCs before one OBR all flush to that order; nothing is lost.\n * - **Order preserved.** Note lines accumulate in document order per parent;\n * across parents the walk is `msg.allSegments()` order. Order-level notes\n * land on the OBR key in document order, so ORC-region notes precede\n * OBR-region notes without any hardcoded assumption about ORC-vs-OBR order.\n * - **Keyed by Segment reference.** `allSegments()` / `segments(type)` return\n * referentially-stable `Segment` instances from one master cache, so a\n * `Map<Segment, …>` lets `observations()` / `orders()` / `patient` look up\n * a parent's notes without re-implementing the positional walk.\n * - **NTE-3 (Comment, FT, repeating).** Each non-empty NTE-3 repetition is one\n * note line. The FULL repetition text is reassembled (all components /\n * subcomponents), HL7-unescaped — a non-conformant raw `^`/`&` in the FT\n * narrative tokenizes into components, so reading only the first would\n * truncate the note (silent clinical-text loss). NTE-1 (set id), NTE-2\n * (source of comment), and NTE-4 (comment type) are intentionally deferred —\n * FT formatting beyond the standard escape set is not specially rendered.\n * - NTE free-text is high-PHI-risk clinical narrative — it is payload; no\n * warning or log line echoes it.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\n\n/**\n * Sentinel target for notes seen in the ORC→OBR region: they belong to the\n * order the next OBR opens, so they are buffered and flushed onto that OBR\n * (mirroring `orders()` ORC promotion). @internal\n */\nconst ORDER_SINK = Symbol(\"order-sink\");\n\n/**\n * Positional grouping of every NTE segment's note lines. `byParent` maps a\n * recognized parent `Segment` (by reference) to its accumulated note lines;\n * `unattached` holds message-level notes with no recognized preceding parent.\n */\nexport interface NoteGrouping {\n /** Recognized parent segment → its note lines, in document order. */\n readonly byParent: ReadonlyMap<Segment, readonly string[]>;\n /** Message-level notes (no recognized preceding parent), in document order. */\n readonly unattached: readonly string[];\n}\n\n/**\n * Extract the note lines from one NTE segment: each non-empty NTE-3 (Comment,\n * FT) repetition as one line, decoded, in order. An NTE carrying no NTE-3\n * text yields `[]`.\n *\n * The FULL repetition text is reassembled — a lenient parser tokenizes a\n * non-conformant raw `^`/`&` in the FT narrative into components/subcomponents,\n * so reading only the first would silently truncate the note. Each leaf is\n * already decoded by the tokenizer (parser-02) — it is used verbatim, NOT\n * re-unescaped (a second decode would double-decode a value whose bytes look\n * like an escape, HL7-VALUE-REDECODE) — and components/subcomponents are\n * rejoined with the literal delimiters so both the conformant (`\\S\\`-escaped)\n * and quirky (raw-caret) forms read to the same text.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const nte = parseHL7(\"MSH|^~\\\\&|A|B|||1||ORU^R01|1|T|2.5\\rNTE|1||a~b\\r\").segments(\"NTE\")[0];\n * if (nte !== undefined) extractNoteLines(nte); // [\"a\", \"b\"]\n * ```\n *\n * @internal\n */\nexport function extractNoteLines(nte: Segment): string[] {\n const field = nte.field(3);\n const enc = field.enc;\n const lines: string[] = [];\n for (const rep of field.repetitions) {\n // Subcomponents are already decoded by the tokenizer — join them verbatim,\n // never a second `unescape` (HL7-VALUE-REDECODE).\n const text = rep.components\n .map((c) => c.subcomponents.join(enc.subcomponent))\n .join(enc.component);\n if (text !== \"\") lines.push(text);\n }\n return lines;\n}\n\n/**\n * Walk the message once and group NTE note lines to their positional parent.\n * The returned maps/arrays are frozen at the boundary. NOT memoized — each\n * caller (`observations()` / `orders()` / `buildPatient()` / `msg.notes()`)\n * re-walks, mirroring the non-memoized collection helpers.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const grouping = groupNotes(msg);\n * grouping.unattached; // message-level notes\n * grouping.byParent.get(msg.segments(\"OBX\")[0]!); // that OBX's notes\n * ```\n *\n * @internal\n */\nexport function groupNotes(msg: Hl7Message): NoteGrouping {\n const byParent = new Map<Segment, string[]>();\n const unattached: string[] = [];\n // Notes buffered in an ORC→OBR region; flushed onto the OBR that opens the\n // order, or to message level if no OBR follows (trailing/dangling ORC).\n let pendingOrderNotes: string[] = [];\n let sawPid = false;\n // Where the NEXT NTE's lines go: a recognized parent Segment (PID#1 / OBR /\n // OBX), the ORC sink, or `undefined` (message-level).\n let target: Segment | typeof ORDER_SINK | undefined;\n\n /** Append `lines` to a parent's accumulator (first write owns the array). */\n const attach = (parent: Segment, lines: string[]): void => {\n const existing = byParent.get(parent);\n if (existing === undefined) byParent.set(parent, lines);\n else existing.push(...lines);\n };\n\n for (const seg of msg.allSegments()) {\n const type = seg.type;\n\n if (type === \"NTE\") {\n const lines = extractNoteLines(seg);\n if (lines.length === 0) continue; // an empty NTE contributes nothing\n if (target === ORDER_SINK) pendingOrderNotes.push(...lines);\n else if (target === undefined) unattached.push(...lines);\n else attach(target, lines);\n continue;\n }\n\n if (type === \"OBR\") {\n // Open the order: seed its notes with the buffered ORC-region notes (in\n // document order, ahead of the OBR's own), then collect onto this OBR.\n if (pendingOrderNotes.length > 0) {\n attach(seg, pendingOrderNotes);\n pendingOrderNotes = []; // hand ownership to byParent; start a fresh buffer\n }\n target = seg;\n continue;\n }\n\n if (type === \"ORC\") {\n target = ORDER_SINK; // following notes belong to the order this ORC opens\n continue;\n }\n\n if (type === \"OBX\") {\n target = seg;\n continue;\n }\n\n if (type === \"PID\") {\n // Only the first PID is surfaced by `msg.patient`; a later PID's notes\n // have no dedicated surface, so route them to message level rather than\n // dropping them or mis-attaching them to the first patient.\n target = sawPid ? undefined : seg;\n sawPid = true;\n continue;\n }\n\n // Any other segment (MSH, PV1, AL1, …) re-scopes the immediate target to\n // message level (fail-safe — never guess). A buffered ORC region survives:\n // it still belongs to the order its OBR will open.\n target = undefined;\n }\n\n // A trailing ORC region that never opened an order → message level (never dropped).\n if (pendingOrderNotes.length > 0) unattached.push(...pendingOrderNotes);\n\n const frozenByParent = new Map<Segment, readonly string[]>();\n for (const [parent, lines] of byParent) frozenByParent.set(parent, Object.freeze(lines));\n\n return {\n byParent: frozenByParent,\n unattached: Object.freeze(unattached),\n };\n}\n\n/**\n * Message-level notes — surfaced verbatim in document order so nothing is ever\n * dropped. This bucket holds an NTE with **no recognized preceding parent**\n * (not immediately following a `PID` / `ORC` / `OBR` / `OBX`), plus the notes\n * whose recognized parent has **no surfaced projection**: a later `PID`'s notes\n * in a multi-patient ORU (`msg.patient` is the first PID only) and an ORC region\n * that never opens an order (a trailing/dangling `ORC` with no following OBR).\n * Notes that DO attach to a specific patient / order / result are exposed on\n * those helper outputs (`msg.patient?.notes`, `order.notes`, `observation.notes`)\n * — not here. D-05: returns `[]` when there are none. NOT memoized.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const note of msg.notes()) console.log(note); // message-level narrative\n * ```\n *\n * @internal\n */\nexport function notes(msg: Hl7Message): readonly string[] {\n return groupNotes(msg).unattached;\n}\n","/**\n * `observations` + `buildObservation` — Phase 4 Plan 03 (visit-and-observations)\n * implementation of HELPERS-04. Walks every OBX segment in document order and\n * projects each into a typed `Observation` discriminated by OBX-2\n * (`valueType`) per D-13. The per-segment builder `buildObservation` is\n * exported so Plan 04's `orders()` can reuse the same OBX → Observation\n * dispatch without duplicating the value-type switch (D-12 positional\n * grouping).\n *\n * Design decisions enforced here:\n * - D-05: `observations(msg)` always returns a readonly array — `[]` when\n * the message has no OBX segments.\n * - D-06: NOT memoized — each call re-walks `msg.segments(\"OBX\")`.\n * - D-11: document order (matches the segment iteration order).\n * - D-13: discriminated union on `valueType`:\n * - `\"NM\"` → `number | undefined` (via `Field.asNm()`)\n * - `\"SN\"` → `SN | undefined` (via `Field.asSn()`, structured numeric)\n * - `\"TS\" | \"DT\"` → `TS | undefined` (via `Field.asTs()`, fidelity per Phase N)\n * - `\"CWE\" | \"CE\"` → composite | undefined (via `Field.asCwe/asCe`)\n * - other (`ST`/`TX`/`FT`/`ID`/`IS`/unknown) → `string | undefined`\n * - D-15: common-field shape (setId, identifier, units, referenceRange,\n * abnormalFlags, status, observedDateTime).\n * - Phase N: datetime values are the fidelity `TS`, not a flat `Date`.\n * - D-22: never throws — empty or malformed input surfaces as `undefined`.\n * - D-01: each Observation and the outer array are frozen at the boundary.\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CE } from \"../model/types/ce.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport { groupNotes } from \"./notes.js\";\nimport type { Observation, ObservationBase } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so optional `units` keys stay absent when OBX-6 was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Build the common (valueType-agnostic) piece of an Observation from one OBX\n * Segment. Omits keys that are absent so the output stays\n * `exactOptionalPropertyTypes`-clean.\n *\n * @internal\n */\nfunction buildCommon(obx: Segment): ObservationBase {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n // `identifier` is always present (D-15) — always parse OBX-3, even if empty.\n const base: Mutable<ObservationBase> = {\n identifier: obx.field(3).asCwe(),\n };\n\n const setId = stringOrUndefined(obx.field(1).value);\n if (setId !== undefined) base.setId = setId;\n\n const units = cweOrUndefined(obx.field(6));\n if (units !== undefined) {\n base.units = units;\n // OBX-6 CWE.3 == \"UCUM\" (HL7 Table 0396): the unit is declared UCUM.\n // Present-but-not-UCUM units surface `false` (never coerced); the flag is\n // omitted entirely when OBX-6 is absent.\n base.unitsAreUcum = units.nameOfCodingSystem === \"UCUM\";\n }\n\n const referenceRange = stringOrUndefined(obx.field(7).value);\n if (referenceRange !== undefined) base.referenceRange = referenceRange;\n\n const abnormalFlags = stringOrUndefined(obx.field(8).value);\n if (abnormalFlags !== undefined) base.abnormalFlags = abnormalFlags;\n\n const status = stringOrUndefined(obx.field(11).value);\n if (status !== undefined) base.status = status;\n\n const observedDateTime = obx.field(14).asTs();\n if (observedDateTime.valid) base.observedDateTime = observedDateTime;\n\n return base as ObservationBase;\n}\n\n/**\n * Dispatch the OBX-5 value to the correct parser based on OBX-2 `valueType`\n * per D-13. The returned object is frozen at the boundary (D-01).\n *\n * @internal\n */\nfunction dispatchValue(valueType: string, valueField: Field, common: ObservationBase): Observation {\n switch (valueType) {\n case \"NM\": {\n const nm = valueField.asNm();\n return Object.freeze({\n ...common,\n valueType: \"NM\" as const,\n value: nm.value,\n });\n }\n case \"SN\": {\n // Structured numeric: preserve the comparator/range/ratio as typed data\n // instead of letting `<10` collapse to the bare string \"<\" (D-13). The\n // inner SN object is frozen too so the whole Observation is deeply\n // immutable at the boundary (D-01).\n const sn = valueField.asSn();\n return Object.freeze({\n ...common,\n valueType: \"SN\" as const,\n value: sn === undefined ? undefined : Object.freeze(sn),\n });\n }\n case \"TS\":\n case \"DT\": {\n const ts = valueField.asTs();\n return Object.freeze({\n ...common,\n valueType,\n value: ts.valid ? ts : undefined,\n });\n }\n case \"CWE\": {\n const cwe = valueField.asCwe();\n const value: CWE | undefined = Object.keys(cwe).length === 0 ? undefined : cwe;\n return Object.freeze({\n ...common,\n valueType: \"CWE\" as const,\n value,\n });\n }\n case \"CE\": {\n const ce = valueField.asCe();\n const value: CE | undefined = Object.keys(ce).length === 0 ? undefined : ce;\n return Object.freeze({\n ...common,\n valueType: \"CE\" as const,\n value,\n });\n }\n default: {\n const raw = valueField.value;\n const value = raw === \"\" ? undefined : raw;\n return Object.freeze({\n ...common,\n valueType,\n value,\n });\n }\n }\n}\n\n/**\n * Build a single `Observation` from one OBX `Segment`. Value is dispatched\n * by OBX-2 per D-13; common fields follow D-15. Exported so Plan 04's\n * `orders()` can reuse this per-segment builder when grouping OBX under OBR\n * positionally (D-12) — do NOT re-implement OBX → Observation construction\n * there.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const obx = msg.segments(\"OBX\")[0];\n * if (obx !== undefined) {\n * const obs = buildObservation(obx);\n * if (obs.valueType === \"NM\") console.log(obs.value);\n * }\n * ```\n */\nexport function buildObservation(obx: Segment, notes?: readonly string[]): Observation {\n const base = buildCommon(obx);\n // Phase P: attach positionally-grouped NTE note lines when present. The\n // `notes` array is already frozen by `groupNotes`; omit the key when empty so\n // the shape stays `exactOptionalPropertyTypes`-clean.\n const common: ObservationBase =\n notes !== undefined && notes.length > 0 ? { ...base, notes } : base;\n const valueType = obx.field(2).value;\n const valueField = obx.field(5);\n return dispatchValue(valueType, valueField, common);\n}\n\n/**\n * Every OBX segment as a typed `Observation` in document order (D-11). D-05:\n * returns `[]` when no OBX segments are present. D-06: NOT memoized — each\n * call re-walks `msg.segments(\"OBX\")`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const obs of msg.observations()) {\n * if (obs.valueType === \"NM\") console.log(obs.value); // number | undefined\n * else if (obs.valueType === \"TS\") console.log(obs.value?.raw, obs.value?.precision);\n * }\n * ```\n *\n * @internal\n */\nexport function observations(msg: Hl7Message): readonly Observation[] {\n const noteIndex = groupNotes(msg);\n const out: Observation[] = [];\n for (const obx of msg.segments(\"OBX\")) {\n out.push(buildObservation(obx, noteIndex.byParent.get(obx)));\n }\n return Object.freeze(out);\n}\n","/**\n * `documents` — Phase Q (document breadth) implementation of the MDM\n * document extractor. Walks the message in document order and projects each\n * TXA (Transcription Document Header) segment into a typed\n * {@link ClinicalDocument}, grouping the OBX narrative body that follows it\n * positionally under that TXA — the same open-a-group-on-the-anchor state\n * machine `immunizations()` uses for RXA→[OBX]. Covers the common MDM trigger\n * events (T02 original / T04 status change / T06 addendum).\n *\n * Field map (HL7 v2 Ch. 9 — medical records / MDM):\n * - TXA-2 document type (IS — Table 0270; verbatim)\n * - TXA-4 activity date/time (TS)\n * - TXA-12 unique document number (EI; first component surfaced verbatim)\n * - TXA-13 parent document number (EI; addendum/replacement link)\n * - TXA-17 document COMPLETION status (ID — Table 0271)\n * - TXA-19 document AVAILABILITY status (ID — Table 0273)\n * - OBX the transcribed narrative body, grouped under the TXA\n *\n * Safety rules enforced here (Phase Q §Fail-safe — the load-bearing one):\n * - **TXA-17 completion status and TXA-19 availability status are surfaced as\n * DISTINCT fields and NEVER conflated.** A document can be *available*\n * (TXA-19 = `AV`) before it is *authenticated / legally authenticated*\n * (TXA-17 = `AU`/`LA`); a still-*preliminary* completion is a different\n * axis from availability. Reading a preliminary document as final is the\n * clinical harm this split exists to prevent. Both are verbatim,\n * provenance-only — never validated, never merged, never defaulted.\n * - Never throws — a malformed TXA surfaces as omitted keys (HELPERS-07).\n * - Missing fields → keys omitted; `observations` is ALWAYS a (possibly\n * empty) array.\n * - Output is frozen at the boundary (D-01); NOT memoized (D-06).\n *\n * Known limitations: `documents()` surfaces the document header + narrative body\n * only. It does NOT verify authentication signatures (TXA-22), resolve the\n * parent-document chain, or interpret confidentiality. See KNOWN-LIMITATIONS.md.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\n\nimport { groupNotes } from \"./notes.js\";\nimport { buildObservation } from \"./observations.js\";\nimport type { ClinicalDocument, Observation } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Build a frozen {@link ClinicalDocument} from one TXA + its grouped OBX body. @internal */\nfunction finalizeDocument(txa: Segment, observations: readonly Observation[]): ClinicalDocument {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<ClinicalDocument> = { observations: Object.freeze(observations.slice()) };\n\n // TXA-2 document type (Table 0270) — verbatim.\n const documentType = stringOrUndefined(txa.field(2).value);\n if (documentType !== undefined) out.documentType = documentType;\n\n // TXA-4 activity date/time (fidelity TS, Phase N).\n const activity = txa.field(4).asTs();\n if (activity.raw !== \"\") out.activityDateTime = activity;\n\n // TXA-12 unique document number (EI) — first component verbatim.\n const uniqueDoc = stringOrUndefined(txa.field(12).value);\n if (uniqueDoc !== undefined) out.uniqueDocumentNumber = uniqueDoc;\n\n // TXA-13 parent document number (EI) — addendum/replacement link.\n const parentDoc = stringOrUndefined(txa.field(13).value);\n if (parentDoc !== undefined) out.parentDocumentNumber = parentDoc;\n\n // TXA-17 completion status (Table 0271) — DISTINCT from availability (TXA-19).\n const completion = stringOrUndefined(txa.field(17).value);\n if (completion !== undefined) out.completionStatus = completion;\n\n // TXA-19 availability status (Table 0273) — DISTINCT from completion (TXA-17).\n const availability = stringOrUndefined(txa.field(19).value);\n if (availability !== undefined) out.availabilityStatus = availability;\n\n return Object.freeze(out) as ClinicalDocument;\n}\n\n/**\n * Every TXA of an MDM message as a typed {@link ClinicalDocument}, with the OBX\n * narrative body grouped positionally under that TXA. Document order. Returns\n * `[]` when no TXA is present. NOT memoized — each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * TXA-17 completion status and TXA-19 availability status are surfaced as\n * **distinct** fields (`completionStatus` vs `availabilityStatus`) and are never\n * merged — a document can be available before it is authenticated, and reading a\n * preliminary document as final is the harm. See {@link ClinicalDocument}.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const doc of msg.documents()) {\n * console.log(doc.documentType, doc.completionStatus, doc.availabilityStatus);\n * for (const obx of doc.observations) console.log(obx.value); // narrative body\n * }\n * ```\n *\n * @internal\n */\nexport function documents(msg: Hl7Message): readonly ClinicalDocument[] {\n const noteIndex = groupNotes(msg); // Phase P: positional NTE grouping (by Segment ref)\n const out: ClinicalDocument[] = [];\n\n let currentTxa: Segment | undefined;\n let observations: Observation[] = [];\n\n const closeCurrent = (): void => {\n if (currentTxa !== undefined) out.push(finalizeDocument(currentTxa, observations));\n };\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"TXA\") {\n closeCurrent();\n currentTxa = seg;\n observations = [];\n continue;\n }\n if (currentTxa === undefined) continue; // OBX before any TXA — dropped (still on msg.observations()).\n if (seg.type === \"OBX\") {\n observations.push(buildObservation(seg, noteIndex.byParent.get(seg)));\n }\n }\n\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `identityEvents` — roadmap Phase K read-side helper that recognizes the ADT\n * patient-identity management trigger events and surfaces the MRG segment's\n * *prior* (non-surviving) identifiers alongside the PID/PV1 *surviving*\n * identifiers, each labelled by role.\n *\n * Spec traceability (HL7 v2 Ch. 3, Patient Administration):\n * - A18 \"The PID segment contains the surviving patient ID information. The\n * MRG segment contains the non-surviving information.\" The merge direction\n * is spec-explicit and constant: **MRG (prior) → PID (surviving)** — this\n * helper NEVER infers it from content and never reverses it.\n * - Merge family (§3.3.34–§3.3.42): A34/A35/A36 (v2.3-era merges), A39 merge\n * person, A40 merge patient identifier list, A41 merge account, A42 merge\n * visit; move family: A43 move patient info, A44 move account info; link\n * family: A24 link / A37 unlink (two PID groups, NO MRG); person add/update:\n * A28 / A31 (PID only, no MRG).\n * - MRG field map is **version-scoped** (v2.5.1 §3.4.10): MRG-1 prior patient\n * identifier list (CX, repeating), MRG-3 prior patient account number (CX),\n * MRG-4 prior patient ID (CX, backward-compat only — **withdrawn as of\n * v2.7** in favour of MRG-1), MRG-5 prior visit number (CX), MRG-7 prior\n * patient name (XPN). MRG-2 / MRG-6 (prior *alternate* patient/visit IDs,\n * also withdrawn v2.7) are deliberately not surfaced. On a v2.7+ message\n * (MSH-12) the withdrawn MRG-4 — and the symmetric withdrawn PID-2 — are\n * NOT read as identity fields.\n *\n * Fail-safe: a merge/move event missing either side of the MRG→PID pair\n * surfaces what is present plus a `MERGE_MISSING_PRIOR_OR_SURVIVOR` warning on\n * the event — the MRG is **never dropped** (an orphaned MRG yields its own\n * event) and the direction is **never guessed**. The helper never throws.\n *\n * PHI note: identifiers and names are the *payload* of the typed view (by\n * design — the consumer needs them to apply the merge), but warning messages\n * carry only structural facts (event code + missing role), never a value.\n *\n * Applying the merge (re-pointing stored data to the survivor) is the\n * consumer's / integration engine's job — this helper only surfaces it.\n */\n\nimport type { Hl7Position } from \"../parser/types.js\";\nimport type { Hl7ParseWarning } from \"../parser/warnings.js\";\nimport { mergeMissingPriorOrSurvivor } from \"../parser/warnings.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CX } from \"../model/types/cx.js\";\nimport { parseCx } from \"../model/types/cx.js\";\nimport type { XPN } from \"../model/types/xpn.js\";\n\n/**\n * Classification of a recognized identity trigger event.\n *\n * - `merge` — A18 / A34 / A35 / A36 / A39 / A40 / A41 / A42 (MRG expected)\n * - `move` — A43 / A44 (MRG expected)\n * - `link` / `unlink` — A24 / A37 (two PID groups, no MRG)\n * - `add` / `update` — A28 / A31 (person add/update, no MRG)\n *\n * @example\n * ```ts\n * import type { IdentityEventKind } from \"@cosyte/hl7\";\n * const kind: IdentityEventKind = \"merge\";\n * ```\n */\nexport type IdentityEventKind = \"merge\" | \"move\" | \"link\" | \"unlink\" | \"add\" | \"update\";\n\n/**\n * Role of one party in an identity event. `surviving` / `subject` / `linked`\n * parties are ONLY ever sourced from PID (+ PV1); `prior` parties are ONLY\n * ever sourced from MRG — the role-labelling invariant Phase K exists for.\n *\n * @example\n * ```ts\n * import type { IdentityRole } from \"@cosyte/hl7\";\n * const role: IdentityRole = \"surviving\";\n * ```\n */\nexport type IdentityRole = \"surviving\" | \"prior\" | \"linked\" | \"subject\";\n\n/**\n * One party (one patient identity) in an identity event, labelled by role\n * with its source segment recorded as provenance. Absent fields are OMITTED\n * (exactOptionalPropertyTypes). All arrays and the object itself are frozen.\n *\n * Field sources by `sourceSegment`:\n * - `\"PID\"`: `identifiers` = PID-3 repetitions, `legacyPatientId` = PID-2\n * (pre-v2.7 only), `accountNumber` = PID-18, `visitNumber` = PV1-19 (from\n * the group's PV1, when present), `name` = PID-5 (first repetition).\n * - `\"MRG\"`: `identifiers` = MRG-1 repetitions, `legacyPatientId` = MRG-4\n * (pre-v2.7 only), `accountNumber` = MRG-3, `visitNumber` = MRG-5,\n * `name` = MRG-7 (first repetition).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const ev = parseHL7(raw).identityEvents()[0];\n * if (ev?.prior) {\n * console.log(ev.prior.role); // \"prior\"\n * console.log(ev.prior.sourceSegment); // \"MRG\"\n * for (const cx of ev.prior.identifiers) console.log(cx.idNumber);\n * }\n * ```\n */\nexport interface IdentityParty {\n /** Role of this party in the event — the safety-critical label. */\n readonly role: IdentityRole;\n /** Segment this party was sourced from — provenance for the role label. */\n readonly sourceSegment: \"PID\" | \"MRG\";\n /** Identifier list (PID-3 / MRG-1), every non-empty CX repetition. */\n readonly identifiers: readonly CX[];\n /**\n * Legacy single patient ID (PID-2 / MRG-4). Backward-compat only; withdrawn\n * as of HL7 v2.7 — OMITTED (not read) when MSH-12 declares v2.7 or later.\n */\n readonly legacyPatientId?: CX;\n /** Patient account number (PID-18 / MRG-3). */\n readonly accountNumber?: CX;\n /** Visit number (PV1-19 for a PID party / MRG-5 for a prior party). */\n readonly visitNumber?: CX;\n /** Patient name (PID-5 / MRG-7, first repetition). */\n readonly name?: XPN;\n}\n\n/**\n * One recognized patient-identity event. For `merge` / `move` kinds the\n * `surviving` (PID/PV1-sourced) and `prior` (MRG-sourced) parties are also\n * exposed directly, with the spec-constant `direction: \"MRG_TO_PID\"` — the\n * prior identifiers are the ones being retired in favour of the surviving\n * ones, never the reverse (HL7 v2 Ch. 3, A18/A39/A40).\n *\n * `parties` is the complete role-labelled surface in document order — nothing\n * present in the message is dropped, including a nonconforming MRG in a\n * link/add message (surfaced as a `prior`-role party).\n *\n * `warnings` carries the event's own fail-safe warnings (currently\n * `MERGE_MISSING_PRIOR_OR_SURVIVOR`); they are scoped to the event and are\n * NOT appended to `Hl7Message.warnings` (a read-side helper never mutates\n * the message).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * for (const ev of parseHL7(raw).identityEvents()) {\n * if (ev.kind === \"merge\" && ev.prior && ev.surviving) {\n * // retire ev.prior.identifiers in favour of ev.surviving.identifiers\n * } else if (ev.warnings.length > 0) {\n * // incomplete pair — do NOT apply; route for review\n * }\n * }\n * ```\n */\nexport interface IdentityEvent {\n /** Trigger event code (MSH-9.2, falling back to EVN-1), e.g. `\"A40\"`. */\n readonly eventType: string;\n /** Classification of the trigger event. */\n readonly kind: IdentityEventKind;\n /** Every party in document order, role-labelled — the complete surface. */\n readonly parties: readonly IdentityParty[];\n /** The surviving party (merge/move) — ONLY ever sourced from PID/PV1. */\n readonly surviving?: IdentityParty;\n /** The prior (non-surviving) party (merge/move) — ONLY ever sourced from MRG. */\n readonly prior?: IdentityParty;\n /**\n * Spec-constant merge/move direction: the MRG (prior) identifiers merge\n * INTO the PID (surviving) identifiers. Present on `merge` / `move` events\n * only; never inferred from content.\n */\n readonly direction?: \"MRG_TO_PID\";\n /** Event-scoped fail-safe warnings (never PHI-bearing). */\n readonly warnings: readonly Hl7ParseWarning[];\n}\n\n/** Trigger-event → kind map for the recognized identity family. @internal */\nconst IDENTITY_TRIGGERS: ReadonlyMap<string, IdentityEventKind> = new Map<\n string,\n IdentityEventKind\n>([\n [\"A18\", \"merge\"], // merge patient information (backward-compat)\n [\"A34\", \"merge\"], // merge patient info - patient ID only\n [\"A35\", \"merge\"], // merge patient info - account number only\n [\"A36\", \"merge\"], // merge patient info - patient ID & account number\n [\"A39\", \"merge\"], // merge person - patient ID\n [\"A40\", \"merge\"], // merge patient - patient identifier list\n [\"A41\", \"merge\"], // merge account - patient account number\n [\"A42\", \"merge\"], // merge visit - visit number\n [\"A43\", \"move\"], // move patient information - patient identifier list\n [\"A44\", \"move\"], // move account information - patient account number\n [\"A24\", \"link\"], // link patient information\n [\"A37\", \"unlink\"], // unlink patient information\n [\"A28\", \"add\"], // add person information\n [\"A31\", \"update\"], // update person information\n]);\n\n/**\n * True when MSH-12 declares HL7 v2.7 or later — the era in which the\n * backward-compat single-ID fields (PID-2, MRG-2/4/6) are withdrawn. An\n * absent or unparseable version is treated as pre-v2.7 (the lenient default:\n * real-world ADT traffic is overwhelmingly v2.3–v2.5.1, where those fields\n * are still legal). @internal\n */\nfunction isV27OrLater(version: string | undefined): boolean {\n if (version === undefined) return false;\n const match = /^(\\d+)(?:\\.(\\d+))?/.exec(version.trim());\n if (match === null) return false;\n const major = Number(match[1]);\n const minor = match[2] === undefined ? 0 : Number(match[2]);\n return major > 2 || (major === 2 && minor >= 7);\n}\n\n/** Parse a single-CX field into a CX, or `undefined` when empty. @internal */\nfunction cxOrUndefined(seg: Segment, fieldIndex: number): CX | undefined {\n const cx = seg.field(fieldIndex).asCx();\n return Object.keys(cx).length > 0 ? cx : undefined;\n}\n\n/** Parse every non-empty CX repetition of a field. @internal */\nfunction cxList(seg: Segment, fieldIndex: number, msg: Hl7Message): readonly CX[] {\n const out: CX[] = [];\n for (const rep of seg.field(fieldIndex).repetitions) {\n const cx = parseCx(rep, msg.encodingCharacters);\n if (Object.keys(cx).length > 0) out.push(cx);\n }\n return Object.freeze(out);\n}\n\n/**\n * Build the PID/PV1-sourced party for a group. `role` distinguishes the\n * surviving (merge/move), linked (link/unlink), and subject (add/update)\n * uses of the same field map. @internal\n */\nfunction buildPidParty(\n pid: Segment,\n pv1: Segment | undefined,\n msg: Hl7Message,\n role: IdentityRole,\n legacyWithdrawn: boolean,\n): IdentityParty {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<IdentityParty> = {\n role,\n sourceSegment: \"PID\",\n identifiers: cxList(pid, 3, msg),\n };\n\n if (!legacyWithdrawn) {\n const legacy = cxOrUndefined(pid, 2);\n if (legacy !== undefined) out.legacyPatientId = legacy;\n }\n\n const account = cxOrUndefined(pid, 18);\n if (account !== undefined) out.accountNumber = account;\n\n if (pv1 !== undefined) {\n const visit = cxOrUndefined(pv1, 19);\n if (visit !== undefined) out.visitNumber = visit;\n }\n\n const name = pid.field(5).asXpn();\n if (Object.keys(name).length > 0) out.name = name;\n\n return Object.freeze(out) as IdentityParty;\n}\n\n/** Build the MRG-sourced `prior` party (version-scoped field map). @internal */\nfunction buildMrgParty(mrg: Segment, msg: Hl7Message, legacyWithdrawn: boolean): IdentityParty {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<IdentityParty> = {\n role: \"prior\",\n sourceSegment: \"MRG\",\n identifiers: cxList(mrg, 1, msg),\n };\n\n if (!legacyWithdrawn) {\n const legacy = cxOrUndefined(mrg, 4);\n if (legacy !== undefined) out.legacyPatientId = legacy;\n }\n\n const account = cxOrUndefined(mrg, 3);\n if (account !== undefined) out.accountNumber = account;\n\n const visit = cxOrUndefined(mrg, 5);\n if (visit !== undefined) out.visitNumber = visit;\n\n const name = mrg.field(7).asXpn();\n if (Object.keys(name).length > 0) out.name = name;\n\n return Object.freeze(out) as IdentityParty;\n}\n\n/** One PID-led (or orphan-MRG) segment group. @internal */\ninterface IdentityGroup {\n pid?: Segment;\n pv1?: Segment;\n mrg?: Segment;\n}\n\n/**\n * Split the message into PID-led groups (spec shape: `PID [PD1] MRG [PV1]`,\n * repeating). An MRG or PV1 attaches to the currently-open PID group; an MRG\n * with no open group — or arriving when the open group already holds one —\n * opens/continues an orphan group so it is NEVER dropped. @internal\n */\nfunction splitGroups(msg: Hl7Message): IdentityGroup[] {\n const groups: IdentityGroup[] = [];\n let current: IdentityGroup | undefined;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"PID\") {\n current = { pid: seg };\n groups.push(current);\n continue;\n }\n if (seg.type === \"MRG\") {\n if (current === undefined || current.mrg !== undefined) {\n current = { mrg: seg };\n groups.push(current);\n } else {\n current.mrg = seg;\n }\n continue;\n }\n if (seg.type === \"PV1\" && current !== undefined && current.pv1 === undefined) {\n current.pv1 = seg;\n }\n }\n return groups;\n}\n\n/** Does the CX carry a usable ID number (Ch. 2A: CX.1 is the identifier)? @internal */\nfunction hasUsableId(cx: CX | undefined): boolean {\n return cx !== undefined && cx.idNumber !== undefined && cx.idNumber !== \"\";\n}\n\n/**\n * Does a party carry at least one usable identity field? A CX with no ID\n * number (e.g. `^^^HOSP`, assigning authority only) is not a usable\n * identifier. Account and visit numbers count on BOTH sides — they are the\n * merge keys of A41/A42 — but a name alone never does. @internal\n */\nfunction hasIdentityField(party: IdentityParty): boolean {\n return (\n party.identifiers.some(hasUsableId) ||\n hasUsableId(party.legacyPatientId) ||\n hasUsableId(party.accountNumber) ||\n hasUsableId(party.visitNumber)\n );\n}\n\n/** Position of a segment for warning context. @internal */\nfunction positionOf(seg: Segment | undefined): Hl7Position {\n return { segmentIndex: seg === undefined ? 0 : seg.absoluteIndex };\n}\n\n/** Finalize one merge/move event from one group. @internal */\nfunction buildMergeEvent(\n group: IdentityGroup,\n eventType: string,\n kind: \"merge\" | \"move\",\n msg: Hl7Message,\n legacyWithdrawn: boolean,\n): IdentityEvent {\n const parties: IdentityParty[] = [];\n const warnings: Hl7ParseWarning[] = [];\n let surviving: IdentityParty | undefined;\n let prior: IdentityParty | undefined;\n\n if (group.pid !== undefined) {\n surviving = buildPidParty(group.pid, group.pv1, msg, \"surviving\", legacyWithdrawn);\n parties.push(surviving);\n }\n if (group.mrg !== undefined) {\n prior = buildMrgParty(group.mrg, msg, legacyWithdrawn);\n parties.push(prior);\n }\n\n // Fail-safe (roadmap Phase K): surface what is present + a typed warning\n // when either role of the MRG→PID pair is missing OR carries no usable\n // identity field (e.g. a v2.7+ MRG whose only content was the gated\n // MRG-4 — the consumer must not read an empty prior as \"nothing to\n // retire\"); never guess direction.\n if (prior === undefined || !hasIdentityField(prior)) {\n warnings.push(\n mergeMissingPriorOrSurvivor(positionOf(group.mrg ?? group.pid), eventType, \"prior\"),\n );\n }\n if (surviving === undefined || !hasIdentityField(surviving)) {\n warnings.push(\n mergeMissingPriorOrSurvivor(positionOf(group.pid ?? group.mrg), eventType, \"survivor\"),\n );\n }\n\n const out: IdentityEvent = {\n eventType,\n kind,\n parties: Object.freeze(parties),\n ...(surviving !== undefined ? { surviving } : {}),\n ...(prior !== undefined ? { prior } : {}),\n direction: \"MRG_TO_PID\",\n warnings: Object.freeze(warnings),\n };\n return Object.freeze(out);\n}\n\n/**\n * Recognize the message's identity trigger event and surface every party\n * labelled by role. Returns `[]` when the trigger (MSH-9.2, falling back to\n * EVN-1) is not in the identity family. Never throws; the result and every\n * nested view are deeply frozen. NOT memoized — each call re-walks the\n * message (mirrors `orders()`).\n *\n * Event shapes:\n * - `merge` / `move` — one event per PID-led group (repeating groups yield\n * one event each); `surviving` + `prior` + constant `direction`.\n * - `link` / `unlink` — ONE event; every PID group is a `linked` party.\n * - `add` / `update` — one event per PID group; the party role is `subject`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(rawA40);\n * const [ev] = msg.identityEvents();\n * ev?.kind; // \"merge\"\n * ev?.direction; // \"MRG_TO_PID\" — spec-constant, never guessed\n * ev?.surviving?.sourceSegment; // \"PID\"\n * ev?.prior?.sourceSegment; // \"MRG\"\n * ```\n *\n * @internal\n */\nexport function identityEvents(msg: Hl7Message): readonly IdentityEvent[] {\n const trigger = msg.meta.triggerEvent ?? msg.get(\"EVN.1\");\n if (trigger === undefined || trigger === \"\") return Object.freeze([]);\n\n const eventType = trigger.toUpperCase();\n const kind = IDENTITY_TRIGGERS.get(eventType);\n if (kind === undefined) return Object.freeze([]);\n\n const legacyWithdrawn = isV27OrLater(msg.meta.version);\n const groups = splitGroups(msg);\n const events: IdentityEvent[] = [];\n\n if (kind === \"merge\" || kind === \"move\") {\n if (groups.length === 0) {\n // Trigger says merge/move but the message carries neither PID nor MRG:\n // one event recording both missing roles (position falls back to MSH).\n events.push(buildMergeEvent({}, eventType, kind, msg, legacyWithdrawn));\n } else {\n for (const group of groups) {\n events.push(buildMergeEvent(group, eventType, kind, msg, legacyWithdrawn));\n }\n }\n } else if (kind === \"link\" || kind === \"unlink\") {\n // A24/A37: the PID groups are peers being (un)linked — no survivor/prior\n // semantics. A nonconforming MRG is still surfaced (never dropped) as a\n // prior-role party in document order.\n const parties: IdentityParty[] = [];\n for (const group of groups) {\n if (group.pid !== undefined) {\n parties.push(buildPidParty(group.pid, group.pv1, msg, \"linked\", legacyWithdrawn));\n }\n if (group.mrg !== undefined) {\n parties.push(buildMrgParty(group.mrg, msg, legacyWithdrawn));\n }\n }\n const out: IdentityEvent = {\n eventType,\n kind,\n parties: Object.freeze(parties),\n warnings: Object.freeze([]),\n };\n events.push(Object.freeze(out));\n } else {\n // add / update (A28/A31): one subject party per PID group. A\n // nonconforming MRG is surfaced on the same event (never dropped).\n for (const group of groups) {\n const parties: IdentityParty[] = [];\n let subject: IdentityParty | undefined;\n if (group.pid !== undefined) {\n subject = buildPidParty(group.pid, group.pv1, msg, \"subject\", legacyWithdrawn);\n parties.push(subject);\n }\n if (group.mrg !== undefined) {\n parties.push(buildMrgParty(group.mrg, msg, legacyWithdrawn));\n }\n if (parties.length === 0) continue;\n const out: IdentityEvent = {\n eventType,\n kind,\n parties: Object.freeze(parties),\n warnings: Object.freeze([]),\n };\n events.push(Object.freeze(out));\n }\n }\n\n return Object.freeze(events);\n}\n","/**\n * `immunizations` — Phase E (P0 safety) implementation of the VXU^V04\n * immunization extractor. Walks the message in document order and projects each\n * RXA (Pharmacy/Treatment Administration) segment into a typed `Immunization`,\n * grouping the RXR (route/site) and OBX (e.g. VFC eligibility / funding) that\n * follow it positionally under that RXA — the same order-group state machine\n * `orders()` uses for ORC → OBR → OBX, specialized to the VXU group\n * `ORC`→`RXA`→`[RXR]`→`[{OBX}]` (one RXA per ORC; CDC v2.5.1 Immunization\n * Messaging IG).\n *\n * Field map (HL7 Ch. 4A — RXA; CDC v2.5.1 Immunization Messaging IG R1.5):\n * - RXA-3 date/time start of administration (TS)\n * - RXA-5 administered vaccine code (CWE — CVX, Table 0292) + any alternate\n * - RXA-6 administered dose amount (NM; `999` = IIS \"unknown\", surfaced as-is)\n * - RXA-7 administered dose units (CWE — UCUM)\n * - RXA-9 immunization information source (CWE — Table NIP001) → recordOrigin\n * - RXA-15 substance lot number (ST, first repetition)\n * - RXA-16 substance expiration date (TS, first repetition)\n * - RXA-17 substance manufacturer (CWE — MVX, Table 0227, first repetition)\n * - RXA-18 substance/treatment refusal reason (CWE, first repetition)\n * - RXA-20 completion status (ID — CP/RE/NA/PA)\n * - RXA-21 action code (ID — A/D/U), preserved verbatim\n * - RXR-1/2 route (Table 0162) / site (Table 0163), grouped (reuses MedicationRoute)\n * - ORC-1 order control of the preceding ORC, attached as orderControl\n *\n * Safety rules enforced here (Phase E):\n * - Never throws — malformed RXA surfaces as omitted keys (HELPERS-07).\n * - `actionCode` (RXA-21) is surfaced VERBATIM and never defaulted — a wrong\n * A/D/U corrupts an IIS add/delete/update dedup.\n * - `recordOrigin` is derived ONLY from the well-known NIP001 RXA-9.1 codes\n * (`00` administered; `01`-`08` historical) and OMITTED otherwise — the raw\n * RXA-9 claim is always preserved on `informationSource`. Never guessed.\n * - `doseAmount` is strict-`Number()` parsed via `Field.asNm()` → never `NaN`;\n * the `999` unknown-dose sentinel is surfaced as the number `999`, not coerced.\n * - Code-system provenance rides on the CWE fields\n * (`vaccineCode.nameOfCodingSystem`, `manufacturer.nameOfCodingSystem`,\n * `route.nameOfCodingSystem`); the helper reports the claim, never validates it.\n * - Output is frozen at the boundary (D-01).\n *\n * Grouping rules (parity with `orders()`):\n * - Each RXA opens a new `Immunization`. A preceding ORC contributes its ORC-1\n * as `orderControl`; an unmatched trailing ORC (after the last RXA) is dropped.\n * - RXR/OBX seen before any RXA are not attached to a phantom immunization\n * (pre-RXA OBX still surface via `msg.observations()`).\n * - `routes` and `observations` are ALWAYS present arrays (empty when none).\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\n\nimport { buildObservation } from \"./observations.js\";\nimport type {\n Immunization,\n ImmunizationRecordOrigin,\n MedicationRoute,\n Observation,\n} from \"./types.js\";\n\n/**\n * NIP001 RXA-9.1 codes that classify a dose as *historical* (sourced from\n * elsewhere, not administered by the reporting system). `00` is the sole\n * administered code; everything outside this set + `00` yields `undefined`\n * (fail-safe — never guessed). @internal\n */\nconst NIP001_HISTORICAL: ReadonlySet<string> = new Set([\n \"01\",\n \"02\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"07\",\n \"08\",\n]);\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so optional CWE keys stay absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Classify RXA-9.1 against HL7 Table NIP001 — `00` administered, `01`-`08`\n * historical, anything else (incl. absent) → `undefined` (fail-safe). @internal\n */\nfunction classifyOrigin(infoSource: CWE | undefined): ImmunizationRecordOrigin | undefined {\n const code = infoSource?.identifier;\n if (code === undefined) return undefined;\n if (code === \"00\") return \"administered\";\n if (NIP001_HISTORICAL.has(code)) return \"historical\";\n return undefined;\n}\n\n/** One RXR segment → a grouped `MedicationRoute` (Table 0162 route + Table 0163 site). @internal */\nfunction buildRoute(rxr: Segment): MedicationRoute {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationRoute> = {};\n\n const route = cweOrUndefined(rxr.field(1));\n if (route !== undefined) out.route = route;\n\n const site = cweOrUndefined(rxr.field(2));\n if (site !== undefined) out.site = site;\n\n return Object.freeze(out);\n}\n\n/** Build a frozen `Immunization` from one RXA + its attached ORC / routes / observations. @internal */\nfunction finalizeImmunization(\n rxa: Segment,\n attachedOrc: Segment | undefined,\n routes: readonly MedicationRoute[],\n observations: readonly Observation[],\n): Immunization {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Immunization> = {\n routes: Object.freeze(routes.slice()),\n observations: Object.freeze(observations.slice()),\n };\n\n // ORC-1 order control (when an ORC preceded this RXA).\n if (attachedOrc !== undefined) {\n const oc = stringOrUndefined(attachedOrc.field(1).value);\n if (oc !== undefined) out.orderControl = oc;\n }\n\n // RXA-3 administered date/time (fidelity TS, Phase N).\n const administered = rxa.field(3).asTs();\n if (administered.valid) out.administeredDateTime = administered;\n\n // RXA-5 vaccine code (CVX) with provenance + alternate coding.\n const vaccineCode = cweOrUndefined(rxa.field(5));\n if (vaccineCode !== undefined) out.vaccineCode = vaccineCode;\n\n // RXA-6 dose amount (strict-parsed; 999 unknown surfaced as-is).\n const doseAmount = rxa.field(6).asNm().value;\n if (doseAmount !== undefined) out.doseAmount = doseAmount;\n\n // RXA-7 dose units (UCUM) + the unitsAreUcum claim flag.\n const doseUnits = cweOrUndefined(rxa.field(7));\n if (doseUnits !== undefined) {\n out.doseUnits = doseUnits;\n out.doseUnitsAreUcum = doseUnits.nameOfCodingSystem === \"UCUM\";\n }\n\n // RXA-9 information source (NIP001) → preserve raw + derive recordOrigin.\n const informationSource = cweOrUndefined(rxa.field(9));\n if (informationSource !== undefined) out.informationSource = informationSource;\n const recordOrigin = classifyOrigin(informationSource);\n if (recordOrigin !== undefined) out.recordOrigin = recordOrigin;\n\n // RXA-15 lot number (first repetition).\n const lotNumber = stringOrUndefined(rxa.field(15).value);\n if (lotNumber !== undefined) out.lotNumber = lotNumber;\n\n // RXA-16 substance expiration date (first repetition; fidelity TS, Phase N).\n const expiration = rxa.field(16).asTs();\n if (expiration.valid) out.expirationDate = expiration;\n\n // RXA-17 manufacturer (MVX, first repetition).\n const manufacturer = cweOrUndefined(rxa.field(17));\n if (manufacturer !== undefined) out.manufacturer = manufacturer;\n\n // RXA-18 refusal reason (first repetition).\n const refusalReason = cweOrUndefined(rxa.field(18));\n if (refusalReason !== undefined) out.refusalReason = refusalReason;\n\n // RXA-20 completion status.\n const completionStatus = stringOrUndefined(rxa.field(20).value);\n if (completionStatus !== undefined) out.completionStatus = completionStatus;\n\n // RXA-21 action code — VERBATIM, never defaulted.\n const actionCode = stringOrUndefined(rxa.field(21).value);\n if (actionCode !== undefined) out.actionCode = actionCode;\n\n return Object.freeze(out) as Immunization;\n}\n\n/**\n * Every RXA of a VXU^V04 as a typed `Immunization`, with RXR (route/site) and\n * OBX children grouped positionally under the RXA and `orderControl` carried\n * from the preceding ORC of the VXU order group (Phase E, P0 safety). Document\n * order. Returns `[]` when no RXA is present. NOT memoized — each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * The vaccine code carries its own coding-system provenance\n * (`vaccineCode.nameOfCodingSystem` — `CVX`); a dual-coded RXA-5 surfaces its\n * alternate (CVX/NDC) on `vaccineCode.alternateIdentifier`/`…`. The action code\n * (RXA-21) is surfaced verbatim and `recordOrigin` (administered vs historical)\n * is derived only from the well-known NIP001 RXA-9.1 codes — see\n * {@link Immunization}.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const imm of msg.immunizations()) {\n * console.log(imm.vaccineCode?.identifier, imm.vaccineCode?.nameOfCodingSystem);\n * console.log(imm.doseAmount, imm.doseUnits?.identifier, imm.recordOrigin);\n * console.log(imm.actionCode, imm.completionStatus);\n * for (const r of imm.routes) console.log(r.route?.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function immunizations(msg: Hl7Message): readonly Immunization[] {\n const out: Immunization[] = [];\n\n let pendingOrc: Segment | undefined; // accumulates ORCs since the last RXA\n let currentRxa: Segment | undefined;\n let currentOrc: Segment | undefined; // ORC attached to the open RXA group\n let routes: MedicationRoute[] = [];\n let observations: Observation[] = [];\n\n const closeCurrent = (): void => {\n if (currentRxa !== undefined) {\n out.push(finalizeImmunization(currentRxa, currentOrc, routes, observations));\n }\n };\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"ORC\") {\n pendingOrc = seg;\n continue;\n }\n if (seg.type === \"RXA\") {\n // Close the previous group, then open a new one; promote pendingOrc.\n closeCurrent();\n currentRxa = seg;\n currentOrc = pendingOrc;\n pendingOrc = undefined;\n routes = [];\n observations = [];\n continue;\n }\n if (currentRxa === undefined) continue; // RXR/OBX before any RXA — dropped.\n if (seg.type === \"RXR\") {\n routes.push(buildRoute(seg));\n } else if (seg.type === \"OBX\") {\n observations.push(buildObservation(seg));\n }\n }\n\n // Finalize the trailing immunization group. A trailing ORC stays in\n // pendingOrc and is implicitly dropped (never promoted).\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `insurance` — Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * IN1 segment in document order, with positional IN2/IN3 presence flags\n * (`hasIn2` / `hasIn3`). Callers who need the full IN2/IN3 surface can drop\n * to `msg.segments(\"IN2\")[i]` / `msg.segments(\"IN3\")[i]` — the positional\n * index aligns with the IN1 index since we walk `msg.allSegments()` in\n * document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no IN1 present.\n * - D-06: NOT memoized — each call re-walks `msg.allSegments()`.\n * - Phase N: `effectiveDate` / `expirationDate` are the fidelity `TS`.\n * - D-22: never throws — empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"IN1\")`):\n * - `planId` ← IN1-2 (CWE)\n * - `companyId` ← IN1-3 (CX — first repetition)\n * - `companyName` ← IN1-4 (XON first component flattened to string)\n * - `groupNumber` ← IN1-8 (string)\n * - `effectiveDate` ← IN1-12 (TS/DT → fidelity `TS`, Phase N)\n * - `expirationDate` ← IN1-13 (TS/DT → fidelity `TS`, Phase N)\n * - `insuredName` ← IN1-16 (XPN)\n * - `policyNumber` ← IN1-36 (string)\n * - `hasIn2`/`hasIn3` ← positional IN2/IN3 presence booleans\n *\n * State-machine shape (single IN1 slot): open on IN1; attach any intervening\n * IN2/IN3 to flags; close and finalize when the next IN1 is seen or the walk\n * ends. IN2/IN3 appearing before any IN1 are ignored.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { Insurance } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Build a frozen `Insurance` from an IN1 segment + positional IN2/IN3 flags. @internal */\nfunction finalizeInsurance(in1: Segment, hasIn2: boolean, hasIn3: boolean): Insurance {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<Insurance> = { hasIn2, hasIn3 };\n\n const planId = in1.field(2).asCwe();\n if (Object.keys(planId).length > 0) entry.planId = planId;\n\n const companyId = in1.field(3).asCx();\n if (Object.keys(companyId).length > 0) entry.companyId = companyId;\n\n const companyName = stringOrUndefined(in1.field(4).value);\n if (companyName !== undefined) entry.companyName = companyName;\n\n const groupNumber = stringOrUndefined(in1.field(8).value);\n if (groupNumber !== undefined) entry.groupNumber = groupNumber;\n\n const effective = in1.field(12).asTs();\n if (effective.valid) entry.effectiveDate = effective;\n\n const expiration = in1.field(13).asTs();\n if (expiration.valid) entry.expirationDate = expiration;\n\n const insuredName = in1.field(16).asXpn();\n if (Object.keys(insuredName).length > 0) entry.insuredName = insuredName;\n\n const policyNumber = stringOrUndefined(in1.field(36).value);\n if (policyNumber !== undefined) entry.policyNumber = policyNumber;\n\n return Object.freeze(entry) as Insurance;\n}\n\n/**\n * Every IN1 as an `Insurance` entry in document order with positional\n * IN2/IN3 flags. `hasIn2` / `hasIn3` become `true` when an IN2 / IN3 appears\n * between this IN1 and the next IN1 (or end of message). D-05: returns `[]`\n * when no IN1 present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const ins of msg.insurance()) {\n * console.log(ins.companyName, ins.policyNumber, ins.hasIn2);\n * }\n * ```\n *\n * @internal\n */\nexport function insurance(msg: Hl7Message): readonly Insurance[] {\n const out: Insurance[] = [];\n let currentIn1: Segment | undefined;\n let currentHasIn2 = false;\n let currentHasIn3 = false;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"IN1\") {\n // Close previous group.\n if (currentIn1 !== undefined) {\n out.push(finalizeInsurance(currentIn1, currentHasIn2, currentHasIn3));\n }\n currentIn1 = seg;\n currentHasIn2 = false;\n currentHasIn3 = false;\n continue;\n }\n if (seg.type === \"IN2\" && currentIn1 !== undefined) {\n currentHasIn2 = true;\n continue;\n }\n if (seg.type === \"IN3\" && currentIn1 !== undefined) {\n currentHasIn3 = true;\n continue;\n }\n }\n\n // Finalize the trailing IN1 group.\n if (currentIn1 !== undefined) {\n out.push(finalizeInsurance(currentIn1, currentHasIn2, currentHasIn3));\n }\n\n return Object.freeze(out);\n}\n","/**\n * `timing` — Phase M (order / medication timing) extraction. Projects the\n * TQ1 segment (HL7 v2.5+, Ch. 4 §4.5.4) and the **legacy embedded TQ** data\n * type in ORC-7 / RXE-1 (pre-v2.5, Ch. 2A §2.A.81 — retained backward-compat\n * only, detail withdrawn as of v2.7) into the typed {@link OrderTiming}\n * surfaced on `Order.timings` / `Medication.timings`.\n *\n * Safety rules enforced here (Phase M §Fail-safe):\n * - The **repeat pattern** (TQ1-3 / legacy interval RI.1, HL7 Table 0335) is\n * surfaced **verbatim** — never normalized, never resolved to clock times,\n * never mapped to a different frequency. Reading `Q6H` as \"daily\" or losing\n * a `BID` silently changes the administered dose count (transcription-class\n * harm).\n * - A parametric `Q<integer><unit>` template's integer is **load-bearing** and\n * is never dropped — surfaced on `RepeatPattern.interval`.\n * - Total occurrences is read from **TQ1-14** (NM), *not* TQ1-11 (which is a\n * Text Instruction, TX).\n * - Never throws — a malformed timing surfaces as omitted keys (HELPERS-07).\n * - hl7 surfaces the timing *structure* only; it does NOT compute schedules,\n * resolve \"institution-specified times\", or interpret sig.\n *\n * Field maps:\n * TQ1 segment — TQ1-2 quantity (CQ), TQ1-3 repeat pattern (RPT.1, Table 0335),\n * TQ1-4 explicit time, TQ1-6 service duration, TQ1-7 start (DTM), TQ1-8 end\n * (DTM), TQ1-9 priority (CWE), TQ1-14 total occurrences (NM).\n * Legacy embedded TQ (one field) — TQ.1 quantity (CQ), TQ.2 interval (RI.1\n * repeat pattern / RI.2 explicit time), TQ.3 duration, TQ.4 start (TS), TQ.5\n * end (TS), TQ.6 priority (ID), TQ.12 total occurrences (NM).\n */\n\nimport { parseDtm } from \"../parser/dates.js\";\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../parser/types.js\";\nimport type { Field } from \"../model/field.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport { parseCwe, type CWE } from \"../model/types/cwe.js\";\nimport { readSubcomponent } from \"../model/types/_shared.js\";\nimport type { OrderTiming, RepeatPattern, TimingQuantity } from \"./types.js\";\n\n/**\n * Table-0335 fixed mnemonics scheduled at institution-specified times — a\n * conservative, provenance-only set (HL7 v2.5.1 Ch. 4 Table 0335). Membership\n * only sets `RepeatPattern.kind = \"named\"`; it never changes the verbatim\n * `code` or resolves a schedule. Compared case-insensitively. @internal\n */\nconst NAMED_PATTERNS: ReadonlySet<string> = new Set<string>([\n \"BID\",\n \"TID\",\n \"QID\",\n \"QOD\",\n \"QHS\",\n \"QAM\",\n \"QPM\",\n \"QSHIFT\",\n \"QD\",\n \"PRN\",\n \"AC\",\n \"PC\",\n \"HS\",\n \"C\",\n]);\n\n/** `Q<integer><unit>` parametric template (seconds/minutes/hours/days/weeks/lunar-months). @internal */\nconst PARAMETRIC = /^Q(\\d+)([SMHDWL])$/iu;\n/** `Q<integer>J<day-of-week>` parametric template (every N weeks on a weekday). @internal */\nconst PARAMETRIC_DOW = /^Q(\\d+)(J)(\\d)$/iu;\n\n/**\n * Classify a Table-0335 repeat-pattern `code` for **provenance only** — the\n * verbatim `code` is always authoritative and is never modified. A parametric\n * `Q<n><unit>` template surfaces its load-bearing integer + unit on `interval`;\n * a recognized mnemonic is `\"named\"`; anything else is `\"unknown\"` (surfaced\n * verbatim, never mapped). Never throws.\n *\n * @example\n * ```ts\n * classifyRepeatPattern(\"Q6H\"); // { code: \"Q6H\", kind: \"parametric\", interval: { count: 6, unit: \"H\" } }\n * classifyRepeatPattern(\"BID\"); // { code: \"BID\", kind: \"named\" }\n * classifyRepeatPattern(\"Q4-6H\"); // { code: \"Q4-6H\", kind: \"unknown\" } — verbatim, never mapped\n * ```\n * @internal\n */\nexport function classifyRepeatPattern(code: string): RepeatPattern {\n const parametric = PARAMETRIC.exec(code);\n if (parametric !== null) {\n const count = Number.parseInt(parametric[1] ?? \"\", 10);\n const unit = (parametric[2] ?? \"\").toUpperCase();\n if (!Number.isNaN(count)) {\n return { code, kind: \"parametric\", interval: { count, unit } };\n }\n }\n const dow = PARAMETRIC_DOW.exec(code);\n if (dow !== null) {\n const count = Number.parseInt(dow[1] ?? \"\", 10);\n if (!Number.isNaN(count)) {\n return { code, kind: \"parametric\", interval: { count, unit: \"J\" } };\n }\n }\n if (NAMED_PATTERNS.has(code.toUpperCase())) {\n return { code, kind: \"named\" };\n }\n return { code, kind: \"unknown\" };\n}\n\n/** Strict-`Number` parse of a raw HL7 numeric — `undefined` (never `NaN`) on empty/garbage. @internal */\nfunction strictNumber(raw: string | undefined): number | undefined {\n if (raw === undefined || raw === \"\") return undefined;\n const n = Number(raw);\n return Number.isNaN(n) ? undefined : n;\n}\n\n/**\n * Build a `CWE` from the subcomponents of one raw component — used to surface\n * the units (a CE) nested inside a CQ (e.g. TQ1-2's `quantity^units&&`). Each\n * subcomponent maps to one CWE component. Returns `undefined` when the\n * component is absent or carries no content. @internal\n */\nfunction cweFromSubcomponents(\n component: RawComponent | undefined,\n enc: EncodingCharacters,\n): CWE | undefined {\n if (component === undefined || component.subcomponents.length === 0) return undefined;\n const rep: RawRepetition = {\n components: component.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const cwe = parseCwe(rep, enc);\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/** Build a `TimingQuantity` from a CQ-shaped field (TQ1-2 / legacy TQ.1). @internal */\nfunction buildQuantity(\n quantityRaw: string | undefined,\n unitsComponent: RawComponent | undefined,\n enc: EncodingCharacters,\n): TimingQuantity | undefined {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<TimingQuantity> = {};\n\n const value = strictNumber(quantityRaw);\n if (value !== undefined) out.value = value;\n\n const units = cweFromSubcomponents(unitsComponent, enc);\n if (units !== undefined) out.units = units;\n\n return Object.keys(out).length === 0 ? undefined : Object.freeze(out);\n}\n\n/** First repetition's component at `index` (or `undefined`). @internal */\nfunction componentAt(field: Field, index: number): RawComponent | undefined {\n return field.repetitions[0]?.components[index];\n}\n\n/** Read `field`'s first-repetition component `compIdx`, subcomponent `subIdx`, unescaped. @internal */\nfunction fieldSub(field: Field, compIdx: number, subIdx: number): string | undefined {\n return readSubcomponent(componentAt(field, compIdx), subIdx, field.enc);\n}\n\n/**\n * Build one {@link OrderTiming} from a TQ1 segment (v2.5+). Reads TQ1-2, -3, -4,\n * -6, -7, -8, -9, -14. Never throws.\n *\n * @example\n * ```ts\n * const tq1 = msg.segments(\"TQ1\")[0];\n * if (tq1 !== undefined) console.log(buildTq1Timing(tq1).repeatPattern?.code);\n * ```\n * @internal\n */\nexport function buildTq1Timing(tq1: Segment): OrderTiming {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<OrderTiming> = { source: \"TQ1\" };\n\n // TQ1-2 quantity (CQ): CQ.1 = component 0 subcomponent 0, CQ.2 units = component 1.\n const q2 = tq1.field(2);\n const quantity = buildQuantity(fieldSub(q2, 0, 0), componentAt(q2, 1), tq1.enc);\n if (quantity !== undefined) out.quantity = quantity;\n\n // TQ1-3 repeat pattern (RPT.1) — verbatim, classified for provenance only.\n const rpt = fieldSub(tq1.field(3), 0, 0);\n if (rpt !== undefined) out.repeatPattern = Object.freeze(classifyRepeatPattern(rpt));\n\n // TQ1-4 explicit time — verbatim (first repetition/value).\n const explicit = fieldSub(tq1.field(4), 0, 0);\n if (explicit !== undefined) out.explicitTime = explicit;\n\n // TQ1-6 service duration — verbatim.\n const duration = fieldSub(tq1.field(6), 0, 0);\n if (duration !== undefined) out.serviceDuration = duration;\n\n // TQ1-7 / TQ1-8 start / end (DTM) — Phase N fidelity TS.\n const start = tq1.field(7).asTs();\n if (start.raw !== \"\") out.startDateTime = start;\n const end = tq1.field(8).asTs();\n if (end.raw !== \"\") out.endDateTime = end;\n\n // TQ1-9 priority (CWE).\n const priority = tq1.field(9).asCwe();\n if (Object.keys(priority).length > 0) out.priority = priority;\n\n // TQ1-14 total occurrences (NM) — NOT TQ1-11.\n const total = strictNumber(fieldSub(tq1.field(14), 0, 0));\n if (total !== undefined) out.totalOccurrences = total;\n\n return Object.freeze(out) as OrderTiming;\n}\n\n/**\n * Build one {@link OrderTiming} from a legacy embedded TQ data type carried in a\n * single field (ORC-7 for orders, RXE-1 for encoded medications; pre-v2.5).\n * Reads TQ.1 (quantity), TQ.2 (interval → repeat pattern / explicit time),\n * TQ.3 (duration), TQ.4/TQ.5 (start / end TS), TQ.6 (priority), TQ.12 (total\n * occurrences). Returns `undefined` when the field carries no timing content so\n * the caller does not surface an empty legacy timing. Never throws.\n *\n * @example\n * ```ts\n * const orc = msg.segments(\"ORC\")[0];\n * if (orc !== undefined) console.log(buildLegacyTiming(orc.field(7))?.repeatPattern?.code);\n * ```\n * @internal\n */\nexport function buildLegacyTiming(field: Field): OrderTiming | undefined {\n const rep = field.repetitions[0];\n if (rep === undefined) return undefined;\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<OrderTiming> = { source: \"legacy\" };\n\n // TQ.1 Quantity (CQ): CQ.1 = component 0 subcomponent 0, CQ.2 units = subcomponent 1.\n const quantity = buildQuantity(fieldSub(field, 0, 0), undefined, field.enc);\n if (quantity !== undefined) {\n // Legacy CQ.2 units collapse to a single subcomponent — surface as { identifier }.\n const unitsId = fieldSub(field, 0, 1);\n out.quantity =\n unitsId !== undefined\n ? Object.freeze({ ...quantity, units: { identifier: unitsId } })\n : quantity;\n }\n\n // TQ.2 Interval (RI): RI.1 = repeat pattern, RI.2 = explicit time.\n const rpt = fieldSub(field, 1, 0);\n if (rpt !== undefined) out.repeatPattern = Object.freeze(classifyRepeatPattern(rpt));\n const explicit = fieldSub(field, 1, 1);\n if (explicit !== undefined) out.explicitTime = explicit;\n\n // TQ.3 Duration.\n const duration = fieldSub(field, 2, 0);\n if (duration !== undefined) out.serviceDuration = duration;\n\n // TQ.4 / TQ.5 Start / End (TS) — Phase N fidelity parse of the embedded value.\n const startRaw = fieldSub(field, 3, 0);\n if (startRaw !== undefined) out.startDateTime = parseDtm(startRaw);\n const endRaw = fieldSub(field, 4, 0);\n if (endRaw !== undefined) out.endDateTime = parseDtm(endRaw);\n\n // TQ.6 Priority (ID) — surfaced as a CWE { identifier } for shape parity with TQ1-9.\n const priorityId = fieldSub(field, 5, 0);\n if (priorityId !== undefined) out.priority = Object.freeze({ identifier: priorityId });\n\n // TQ.12 Total occurrences (NM).\n const total = strictNumber(fieldSub(field, 11, 0));\n if (total !== undefined) out.totalOccurrences = total;\n\n // A source-only object (nothing else populated) is not a real timing.\n if (Object.keys(out).length === 1) return undefined;\n\n return Object.freeze(out) as OrderTiming;\n}\n","/**\n * `medications` — Phase D (P0 safety) implementation of the pharmacy/treatment\n * extractor. Walks the message in document order and projects each RXO / RXE /\n * RXD / RXA segment into a typed `Medication`, grouping the RXR (route) and\n * RXC (component) segments that follow it positionally under that parent —\n * the same state-machine pattern `orders()` uses for OBR → OBX (D-12).\n *\n * Field map (HL7 Ch. 4A — Pharmacy/Treatment):\n * - RXO (order): give RXO-1, amount RXO-2/3, units RXO-4, form RXO-5\n * - RXE (encoded): give RXE-2, amount RXE-3/4, units RXE-5,\n * strength RXE-25 + units RXE-26\n * - RXD (dispense): give RXD-2, amount RXD-4 (single), units RXD-5\n * - RXA (administration): give RXA-5, amount RXA-6 (single), units RXA-7\n * - RXR (route, grouped): route RXR-1 (Table 0162), site RXR-2 (Table 0163)\n * - RXC (component, grouped): type RXC-1, code RXC-2, amount RXC-3, units RXC-4\n *\n * Safety rules enforced here (Phase D §4):\n * - Never throws — malformed RX* surface as omitted keys (matches the helper\n * layer contract; HELPERS-07).\n * - `amount` (how much) and `strength` (concentration) are surfaced as\n * SEPARATE fields and are NEVER reconciled — including against any strength\n * a coded drug (e.g. an NDC) implies. A disagreement is preserved.\n * - Numeric fields are strict-`Number()` parsed via `Field.asNm()` → never\n * `NaN`; absent/blank → key omitted.\n * - Code-system provenance rides on the give-code CWE\n * (`giveCode.nameOfCodingSystem`); the helper reports the claim, never\n * validates it.\n * - Output is frozen at the boundary (Order/Observation parity, D-01).\n *\n * Grouping rules:\n * - Each RXO/RXE/RXD/RXA opens a new `Medication`. RXR/RXC seen before any\n * RX* parent are dropped (parity with `orders()` dropping a leading OBX /\n * trailing ORC) — they are not attached to a phantom medication.\n * - `routes` and `components` are ALWAYS present arrays (empty when none).\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport { buildLegacyTiming, buildTq1Timing } from \"./timing.js\";\nimport type {\n Medication,\n MedicationAmount,\n MedicationComponent,\n MedicationContext,\n MedicationRoute,\n MedicationStrength,\n OrderTiming,\n} from \"./types.js\";\n\n/** The four RX* parent segment types that each open a `Medication`. @internal */\nconst PARENT_CONTEXT: Readonly<Record<string, MedicationContext>> = {\n RXO: \"order\",\n RXE: \"encoded\",\n RXD: \"dispense\",\n RXA: \"administration\",\n};\n\n/** Drop empty-composite leaks so optional CWE keys stay absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Build the give/dispense/administered amount from a (min, max, units) field\n * triple. Returns `undefined` when none of the three carries content so the\n * optional `amount` key stays absent. `max` is `undefined` for single-amount\n * (dispense/administration) callers. @internal\n */\nfunction buildAmount(\n minField: Field,\n maxField: Field | undefined,\n unitsField: Field,\n): MedicationAmount | undefined {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationAmount> = {};\n\n const minimum = minField.asNm().value;\n if (minimum !== undefined) out.minimum = minimum;\n\n if (maxField !== undefined) {\n const maximum = maxField.asNm().value;\n if (maximum !== undefined) out.maximum = maximum;\n }\n\n const units = cweOrUndefined(unitsField);\n if (units !== undefined) out.units = units;\n\n return Object.keys(out).length === 0 ? undefined : Object.freeze(out);\n}\n\n/** RXE-25/26 give strength — surfaced verbatim, never reconciled with the give code. @internal */\nfunction buildStrength(rxe: Segment): MedicationStrength | undefined {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationStrength> = {};\n\n const value = rxe.field(25).asNm().value;\n if (value !== undefined) out.value = value;\n\n const units = cweOrUndefined(rxe.field(26));\n if (units !== undefined) out.units = units;\n\n return Object.keys(out).length === 0 ? undefined : Object.freeze(out);\n}\n\n/** Build the give-code + amount + (strength/form) for one RX* parent by context. @internal */\nfunction buildFromParent(parent: Segment, context: MedicationContext): Medication {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Medication> = { context, routes: [], components: [] };\n\n let giveCode: CWE | undefined;\n let amount: MedicationAmount | undefined;\n\n switch (context) {\n case \"order\": {\n giveCode = cweOrUndefined(parent.field(1));\n amount = buildAmount(parent.field(2), parent.field(3), parent.field(4));\n const form = cweOrUndefined(parent.field(5));\n if (form !== undefined) out.dosageForm = form;\n break;\n }\n case \"encoded\": {\n giveCode = cweOrUndefined(parent.field(2));\n amount = buildAmount(parent.field(3), parent.field(4), parent.field(5));\n const strength = buildStrength(parent);\n if (strength !== undefined) out.strength = strength;\n break;\n }\n case \"dispense\": {\n giveCode = cweOrUndefined(parent.field(2));\n // RXD-4 is a SINGLE actual-dispense amount — no max field.\n amount = buildAmount(parent.field(4), undefined, parent.field(5));\n break;\n }\n case \"administration\": {\n giveCode = cweOrUndefined(parent.field(5));\n // RXA-6 is a SINGLE administered amount — no max field.\n amount = buildAmount(parent.field(6), undefined, parent.field(7));\n break;\n }\n }\n\n if (giveCode !== undefined) out.giveCode = giveCode;\n if (amount !== undefined) out.amount = amount;\n\n return out as Medication;\n}\n\n/** One RXR segment → a grouped `MedicationRoute` (Table 0162 route + Table 0163 site). @internal */\nfunction buildRoute(rxr: Segment): MedicationRoute {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationRoute> = {};\n\n const route = cweOrUndefined(rxr.field(1));\n if (route !== undefined) out.route = route;\n\n const site = cweOrUndefined(rxr.field(2));\n if (site !== undefined) out.site = site;\n\n return Object.freeze(out);\n}\n\n/** One RXC segment → a grouped `MedicationComponent` (structural — not pharmacologically resolved). @internal */\nfunction buildComponent(rxc: Segment): MedicationComponent {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationComponent> = {};\n\n const type = rxc.field(1).value;\n if (type !== \"\") out.type = type;\n\n const code = cweOrUndefined(rxc.field(2));\n if (code !== undefined) out.code = code;\n\n const amount = rxc.field(3).asNm().value;\n if (amount !== undefined) out.amount = amount;\n\n const units = cweOrUndefined(rxc.field(4));\n if (units !== undefined) out.units = units;\n\n return Object.freeze(out);\n}\n\n/**\n * Build the frozen `timings` list for a medication group (Phase M). Every TQ1\n * segment grouped under the RX* parent yields one `OrderTiming`\n * (`source: \"TQ1\"`). When the group carries no TQ1, the **legacy embedded TQ**\n * is read from RXE-1 (an encoded RXE order) or, failing that, from the preceding\n * ORC's ORC-7 (any pharmacy order — e.g. a pre-v2.5 RXO whose timing lives in\n * ORC-7 with no OBR to surface it via `orders()`). Reading the legacy source\n * only when no TQ1 is present means the same timing is never double-counted; the\n * ORC-7 fallback means a legacy-only timing is never dropped. `orc` is the ORC\n * that opened this group (already consumed for only the first RX* of the group,\n * so an `ORC RXO RXE` group never double-surfaces the ORC-7 timing).\n * @internal\n */\nfunction buildMedTimings(\n tq1Segs: readonly Segment[],\n parent: Segment,\n context: MedicationContext,\n orc: Segment | undefined,\n): readonly OrderTiming[] {\n if (tq1Segs.length > 0) {\n return Object.freeze(tq1Segs.map((seg) => buildTq1Timing(seg)));\n }\n if (context === \"encoded\") {\n const legacy = buildLegacyTiming(parent.field(1)); // RXE-1 Quantity/Timing\n if (legacy !== undefined) return Object.freeze([legacy]);\n }\n if (orc !== undefined) {\n const legacy = buildLegacyTiming(orc.field(7)); // ORC-7 Quantity/Timing\n if (legacy !== undefined) return Object.freeze([legacy]);\n }\n return Object.freeze([]);\n}\n\n/** Freeze a Medication and its grouped child arrays at the boundary (D-01). @internal */\nfunction finalize(\n med: Medication,\n parent: Segment,\n orc: Segment | undefined,\n routes: readonly MedicationRoute[],\n components: readonly MedicationComponent[],\n tq1Segs: readonly Segment[],\n): Medication {\n const out = med as { -readonly [K in keyof Medication]: Medication[K] };\n out.routes = Object.freeze(routes.slice());\n out.components = Object.freeze(components.slice());\n out.timings = buildMedTimings(tq1Segs, parent, med.context, orc);\n return Object.freeze(out);\n}\n\n/**\n * Every RXO/RXE/RXD/RXA as a typed `Medication`, with RXR (route) and RXC\n * (component) segments grouped positionally under the preceding RX* parent\n * (Phase D, P0 safety). Document order. Returns `[]` when no RX* parent is\n * present. NOT memoized — each call re-walks `msg.allSegments()`. Never throws\n * (HELPERS-07).\n *\n * The give code carries its own coding-system provenance\n * (`giveCode.nameOfCodingSystem`). The give *amount* and the give *strength*\n * are surfaced as separate fields and are never reconciled — a strength a\n * coded drug implies is never used to validate or overwrite the explicit\n * RXE-25/26 strength (Phase D §4).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const med of msg.medications()) {\n * console.log(med.context, med.giveCode?.identifier, med.giveCode?.nameOfCodingSystem);\n * console.log(med.amount?.minimum, med.amount?.units?.identifier);\n * for (const r of med.routes) console.log(r.route?.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function medications(msg: Hl7Message): readonly Medication[] {\n const out: Medication[] = [];\n\n let current: Medication | undefined;\n let currentParent: Segment | undefined;\n let currentOrc: Segment | undefined; // ORC that opened the current group (ORC-7 legacy source)\n let pendingOrc: Segment | undefined; // ORC seen before the next RX* parent opens\n let routes: MedicationRoute[] = [];\n let components: MedicationComponent[] = [];\n let pendingTq1: Segment[] = []; // TQ1 seen before the next RX* parent opens (Phase M)\n let currentTq1: Segment[] = []; // TQ1 grouped under the open RX* parent (Phase M)\n let awaitingParent = false; // an ORC has begun a group still awaiting its RX* parent (Phase M)\n\n const closeCurrent = (): void => {\n if (current !== undefined && currentParent !== undefined) {\n out.push(finalize(current, currentParent, currentOrc, routes, components, currentTq1));\n }\n };\n\n for (const seg of msg.allSegments()) {\n const context = PARENT_CONTEXT[seg.type];\n if (context !== undefined) {\n // Close the previous medication group, then open a new one — promoting\n // any TQ1 seen since the last parent (the order group places TQ1 ahead\n // of the RXE it modifies). The preceding ORC (its ORC-7 legacy timing) is\n // consumed by only this first RX*: `pendingOrc` is cleared so a sibling\n // RX* in the same ORC group never double-surfaces the ORC-7 timing.\n closeCurrent();\n current = buildFromParent(seg, context);\n currentParent = seg;\n currentOrc = pendingOrc;\n pendingOrc = undefined;\n routes = [];\n components = [];\n currentTq1 = pendingTq1;\n pendingTq1 = [];\n awaitingParent = false;\n continue;\n }\n if (seg.type === \"ORC\") {\n // A new ORC starts a new order group: any following TQ1 (before that\n // group's RX* parent) belongs to the NEXT medication, and its ORC-7\n // carries the legacy timing for that group.\n pendingOrc = seg;\n awaitingParent = true;\n continue;\n }\n if (seg.type === \"TQ1\") {\n // A TQ1 attaches to the open medication only when no newer ORC has begun a\n // group; otherwise it modifies the next RX* parent.\n if (current !== undefined && !awaitingParent) currentTq1.push(seg);\n else pendingTq1.push(seg);\n continue;\n }\n if (current === undefined) continue; // RXR/RXC before any RX* parent — dropped.\n if (seg.type === \"RXR\") {\n routes.push(buildRoute(seg));\n } else if (seg.type === \"RXC\") {\n components.push(buildComponent(seg));\n }\n }\n\n // Finalize the trailing medication group.\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `buildMeta` — compose MSH-derived message metadata into the frozen `Meta`\n * view exposed by `Hl7Message.meta` (HELPERS-01). Implementation composes on\n * the Phase 3 public surface (`msg.get`, `msg.segments(\"MSH\")[0].field(N)`) —\n * never walks `rawSegments` directly (CONTEXT.md §domain \"Compose, don't\n * reach through\").\n *\n * D-01 freeze at boundary. D-02 memoization is handled by the caller\n * (`Hl7Message.meta` getter). D-03 Meta is always defined — MSH absence\n * throws `NO_MSH_SEGMENT` at parse time, so the MSH guard here is purely for\n * TS narrowing. Phase N: `timestamp` is the fidelity `TS` (precision +\n * timezone preserved), never an eager UTC-assuming `Date`. D-21 silent. D-22\n * never throws. D-23 string fields are decoded (unescaped once at parse) by routing through\n * `msg.get()` / `field.value`.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport { parseDtmCascade } from \"../parser/dates.js\";\n\nimport type { Meta } from \"./types.js\";\n\n/**\n * Build the immutable `Meta` view from a parsed message's MSH segment. The\n * result is deeply frozen (D-01) and consumed through the memoized\n * `Hl7Message.meta` getter (D-02). Absent fields are OMITTED from the\n * resulting object (exactOptionalPropertyTypes semantics) — never set to\n * `undefined`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.meta.type); // \"ADT^A01^ADT_A01\"\n * console.log(msg.meta.controlId); // \"MSG001\"\n * console.log(msg.meta.timestamp?.raw); // fidelity TS (Phase N)\n * ```\n *\n * @internal\n */\nexport function buildMeta(msg: Hl7Message): Meta {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Meta> = {};\n\n // D-03: MSH is always present on a parsed Hl7Message. The optional-chain\n // here is purely for TS narrowing under noUncheckedIndexedAccess.\n const msh = msg.segments(\"MSH\")[0];\n\n // ─── MSH-9 message type (full string + per-component shortcuts) ────────\n // msg.get(\"MSH.9\") returns the first subcomponent of the first component —\n // i.e. MSH-9.1. To emit the FULL typed string (e.g. \"ADT^A01^ADT_A01\") we\n // reconstruct it from each component's first subcomponent, joined on '^'\n // and trimmed of trailing empties so \"ADT^A01\" doesn't render as\n // \"ADT^A01^\".\n if (msh !== undefined) {\n const typeField = msh.field(9);\n const firstRep = typeField.repetitions[0];\n if (firstRep !== undefined) {\n const parts: string[] = [];\n for (let i = 0; i < firstRep.components.length; i++) {\n const sub = msg.get(`MSH.9.${String(i + 1)}`);\n parts.push(sub ?? \"\");\n }\n while (parts.length > 0 && parts[parts.length - 1] === \"\") parts.pop();\n const fullType = parts.join(\"^\");\n if (fullType !== \"\") out.type = fullType;\n }\n }\n const messageCode = msg.get(\"MSH.9.1\");\n if (messageCode !== undefined && messageCode !== \"\") out.messageCode = messageCode;\n const triggerEvent = msg.get(\"MSH.9.2\");\n if (triggerEvent !== undefined && triggerEvent !== \"\") out.triggerEvent = triggerEvent;\n const messageStructure = msg.get(\"MSH.9.3\");\n if (messageStructure !== undefined && messageStructure !== \"\") {\n out.messageStructure = messageStructure;\n }\n\n // ─── MSH-10 message control ID ────────────────────────────────────────\n const controlId = msg.get(\"MSH.10\");\n if (controlId !== undefined && controlId !== \"\") out.controlId = controlId;\n\n // ─── MSH-7 timestamp (Phase N fidelity TS + D-21 merged dateFormats) ───\n // Call parseDtmCascade DIRECTLY (not via .asTs() which hard-codes the strict\n // HL7 shape) so Phase 6 D-21 `options.dateFormats ++ profile.dateFormats` is\n // honoured for MSH-7. .asTs() stays strict for composite callers (Phase 3\n // D-10 \"zero duplicate date logic\"); meta.ts is the non-composite caller that\n // benefits from the lenient cascade. Phase N: `timestamp` is the fidelity\n // TS (precision + timezone preserved), never an eager UTC-assuming Date.\n if (msh !== undefined) {\n const tsField = msh.field(7);\n const tsRaw = tsField.value;\n if (tsRaw !== \"\") {\n const parsed = parseDtmCascade(tsRaw, { userFormats: msg.dateFormats });\n // `parseDtmCascade` already returns a frozen `DtmParts`.\n if (parsed.valid) out.timestamp = parsed;\n }\n }\n\n // ─── MSH-12 version ───────────────────────────────────────────────────\n const version = msg.get(\"MSH.12\");\n if (version !== undefined && version !== \"\") out.version = version;\n\n // ─── MSH-3/-4/-5/-6 apps + facilities (first component = namespace id) ─\n const sendingApp = msg.get(\"MSH.3.1\");\n if (sendingApp !== undefined && sendingApp !== \"\") out.sendingApp = sendingApp;\n const sendingFacility = msg.get(\"MSH.4.1\");\n if (sendingFacility !== undefined && sendingFacility !== \"\") {\n out.sendingFacility = sendingFacility;\n }\n const receivingApp = msg.get(\"MSH.5.1\");\n if (receivingApp !== undefined && receivingApp !== \"\") out.receivingApp = receivingApp;\n const receivingFacility = msg.get(\"MSH.6.1\");\n if (receivingFacility !== undefined && receivingFacility !== \"\") {\n out.receivingFacility = receivingFacility;\n }\n\n // ─── MSH-11 processing ID (first component) ───────────────────────────\n const processingId = msg.get(\"MSH.11.1\");\n if (processingId !== undefined && processingId !== \"\") out.processingId = processingId;\n\n // D-01: freeze at boundary — callers see an immutable view.\n return Object.freeze(out);\n}\n","/**\n * `nextOfKin` — Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * NK1 segment in document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no NK1 present.\n * - D-06: NOT memoized — each call re-walks `msg.segments(\"NK1\")`.\n * - D-22: never throws — empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"NK1\")`):\n * - `name` ← NK1-2 (XPN)\n * - `relationship` ← NK1-3 (CWE)\n * - `address` ← NK1-4 (XAD)\n * - `phone` ← NK1-5 first repetition (XTN)\n * - `contactRole` ← NK1-7 (CWE)\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { NextOfKin } from \"./types.js\";\n\n/**\n * Every NK1 as a `NextOfKin` entry in document order. D-05: returns `[]` when\n * no NK1 is present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const nk of msg.nextOfKin()) {\n * console.log(nk.name?.familyName, nk.relationship?.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function nextOfKin(msg: Hl7Message): readonly NextOfKin[] {\n const out: NextOfKin[] = [];\n for (const nk1 of msg.segments(\"NK1\")) {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<NextOfKin> = {};\n\n const name = nk1.field(2).asXpn();\n if (Object.keys(name).length > 0) entry.name = name;\n\n const relationship = nk1.field(3).asCwe();\n if (Object.keys(relationship).length > 0) entry.relationship = relationship;\n\n const address = nk1.field(4).asXad();\n if (Object.keys(address).length > 0) entry.address = address;\n\n const phone = nk1.field(5).asXtn();\n if (Object.keys(phone).length > 0) entry.phone = phone;\n\n const contactRole = nk1.field(7).asCwe();\n if (Object.keys(contactRole).length > 0) entry.contactRole = contactRole;\n\n out.push(Object.freeze(entry));\n }\n return Object.freeze(out);\n}\n","/**\n * `orders` — Phase 4 Plan 04 implementation of HELPERS-05. Walks the message\n * in document order and groups OBX segments positionally under their\n * preceding OBR (D-12). An ORC segment that precedes an OBR contributes its\n * ORC-1 as the order's `orderControl` (D-16); unmatched trailing ORCs are\n * dropped.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each Order and to the outer array.\n * - D-05: returns `[]` when no OBR is present.\n * - D-06: NOT memoized — each call re-walks `msg.allSegments()`.\n * - D-12: OBX attached positionally to the preceding OBR; pre-OBR OBX are\n * NOT grouped here (but still surface via `msg.observations()`).\n * - D-16: Order field contract (placerOrderNumber, fillerOrderNumber,\n * universalServiceId, orderStatus, orderControl, orderedBy, observations).\n * - D-18: `orderStatus` uses OBR-25 (resultStatus) for v1; Phase 7 may revisit.\n * - D-22: never throws — malformed OBR/OBX surface as omitted keys.\n * - D-24 (a): `orderedBy` is an XCN composite (not a flat string).\n * - Reuses `buildObservation` from `./observations.ts` (Plan 03) — never\n * re-implement OBX → Observation construction here.\n *\n * State-machine shape: two ORC slots.\n * - `pendingOrc` accumulates ORCs seen since the last OBR.\n * - `currentOrc` is the ORC attached to the currently-open OBR group.\n * When an OBR is seen, close the previous group with `currentOrc`, then\n * promote `pendingOrc` → `currentOrc` for the new group and reset\n * `pendingOrc`. A trailing ORC after the last OBR stays in `pendingOrc` and\n * is implicitly dropped (never promoted).\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\n\nimport { groupNotes, type NoteGrouping } from \"./notes.js\";\nimport { buildObservation } from \"./observations.js\";\nimport { buildLegacyTiming, buildTq1Timing } from \"./timing.js\";\nimport type { Observation, Order, OrderTiming } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/**\n * Build the frozen `timings` list for an order group (Phase M). Every TQ1\n * segment grouped under the OBR yields one `OrderTiming` (`source: \"TQ1\"`).\n * The legacy embedded TQ in the attached ORC's ORC-7 is read **only when the\n * group carries no TQ1** — so the same timing is never double-counted and a\n * legacy-only (pre-v2.5) timing is never dropped. @internal\n */\nfunction buildTimings(\n tq1Segs: readonly Segment[],\n attachedOrc: Segment | undefined,\n): readonly OrderTiming[] {\n if (tq1Segs.length > 0) {\n return Object.freeze(tq1Segs.map((seg) => buildTq1Timing(seg)));\n }\n if (attachedOrc !== undefined) {\n const legacy = buildLegacyTiming(attachedOrc.field(7)); // ORC-7 Quantity/Timing\n if (legacy !== undefined) return Object.freeze([legacy]);\n }\n return Object.freeze([]);\n}\n\n/** Build a frozen `Order` from the accumulated OBR / attached ORC / observations. @internal */\nfunction finalizeOrder(\n obr: Segment,\n attachedOrc: Segment | undefined,\n observations: readonly Observation[],\n tq1Segs: readonly Segment[],\n noteIndex: NoteGrouping,\n): Order {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Order> = {\n observations,\n timings: buildTimings(tq1Segs, attachedOrc),\n };\n\n // Phase P: every order-level note (ORC-region + OBR-region) is keyed on the\n // OBR in document order by `groupNotes` — the ORC region is flushed onto the\n // OBR when the order opens, so this is a single already-ordered lookup. The\n // array is already frozen by `groupNotes`.\n const orderNotes = noteIndex.byParent.get(obr);\n if (orderNotes !== undefined && orderNotes.length > 0) out.notes = orderNotes;\n\n const placer = stringOrUndefined(obr.field(2).value);\n if (placer !== undefined) out.placerOrderNumber = placer;\n\n const filler = stringOrUndefined(obr.field(3).value);\n if (filler !== undefined) out.fillerOrderNumber = filler;\n\n const usvc: CWE = obr.field(4).asCwe();\n if (Object.keys(usvc).length > 0) out.universalServiceId = usvc;\n\n // D-16: orderStatus from OBR-25 (resultStatus) for v1; Phase 7 may revisit.\n const status = stringOrUndefined(obr.field(25).value);\n if (status !== undefined) out.orderStatus = status;\n\n // D-16: orderControl from the attached ORC-1 (when an ORC preceded this OBR).\n if (attachedOrc !== undefined) {\n const oc = stringOrUndefined(attachedOrc.field(1).value);\n if (oc !== undefined) out.orderControl = oc;\n }\n\n // D-24 (a): orderedBy is an XCN composite read from OBR-16.\n const orderedBy: XCN = obr.field(16).asXcn();\n if (Object.keys(orderedBy).length > 0) out.orderedBy = orderedBy;\n\n return Object.freeze(out) as Order;\n}\n\n/**\n * Every OBR as an Order with its OBX children grouped positionally (D-12).\n * OBX segments that precede any OBR are NOT attached to an order (they still\n * surface in `msg.observations()` which walks all OBX regardless). An ORC\n * segment preceding an OBR contributes its `orderControl` (ORC-1) to that\n * order; unmatched ORCs (trailing after the last OBR) are dropped.\n *\n * D-05: returns `[]` when no OBR is present. D-06: NOT memoized.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const order of msg.orders()) {\n * console.log(order.placerOrderNumber, order.observations.length);\n * for (const obs of order.observations) console.log(obs.value);\n * }\n * ```\n *\n * @internal\n */\nexport function orders(msg: Hl7Message): readonly Order[] {\n const noteIndex = groupNotes(msg); // Phase P: positional NTE grouping (by Segment ref)\n const out: Order[] = [];\n let pendingOrc: Segment | undefined; // accumulates ORCs since last OBR\n let pendingTq1: Segment[] = []; // TQ1 seen before the next OBR opens (Phase M)\n let awaitingObr = false; // an ORC has opened a new group still awaiting its OBR (Phase M)\n let currentObr: Segment | undefined;\n let currentOrc: Segment | undefined; // ORC attached to the open OBR group\n let currentObservations: Observation[] = [];\n let currentTq1: Segment[] = []; // TQ1 grouped under the open OBR (Phase M)\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"ORC\") {\n pendingOrc = seg;\n // A new ORC starts a new order group: any following TQ1 (before that\n // group's OBR) belongs to the NEXT order, never the still-open prior one.\n awaitingObr = true;\n continue;\n }\n if (seg.type === \"TQ1\") {\n // A TQ1 attaches to the open OBR only when no newer ORC has begun a group;\n // otherwise it modifies the next OBR (a TQ1 can sit either side of the OBR,\n // and an intervening ORC re-scopes it to the following order).\n if (currentObr !== undefined && !awaitingObr) currentTq1.push(seg);\n else pendingTq1.push(seg);\n continue;\n }\n if (seg.type === \"OBR\") {\n // Close previous group using THAT group's attached ORC + TQ1.\n if (currentObr !== undefined) {\n out.push(\n finalizeOrder(\n currentObr,\n currentOrc,\n Object.freeze(currentObservations.slice()),\n currentTq1,\n noteIndex,\n ),\n );\n }\n // Open new group; promote pendingOrc / pendingTq1; reset pending.\n currentObr = seg;\n currentOrc = pendingOrc;\n currentTq1 = pendingTq1;\n pendingOrc = undefined;\n pendingTq1 = [];\n awaitingObr = false;\n currentObservations = [];\n continue;\n }\n if (seg.type === \"OBX\" && currentObr !== undefined) {\n currentObservations.push(buildObservation(seg, noteIndex.byParent.get(seg)));\n }\n }\n\n // Finalize the trailing order. A trailing ORC / TQ1 after the last OBR stays\n // pending and is implicitly dropped (never promoted) — parity with ORC.\n if (currentObr !== undefined) {\n out.push(\n finalizeOrder(\n currentObr,\n currentOrc,\n Object.freeze(currentObservations.slice()),\n currentTq1,\n noteIndex,\n ),\n );\n }\n\n return Object.freeze(out);\n}\n","/**\n * `pickMrn` — pick the Medical Record Number string from a PID-3 identifier\n * list. Isolated from `patient.ts` so Phase 6 profile hooks can substitute\n * a profile-aware variant without patching the helper that calls it.\n *\n * Silent (D-21: helpers emit no warnings). Never throws (D-22).\n */\n\nimport type { CX } from \"../model/types/cx.js\";\n\n/**\n * Pick the Medical Record Number string from a list of PID-3 CX identifiers.\n *\n * D-07: prefer the first CX whose `identifierTypeCode === \"MR\"` (HL7 v2.5+\n * canonical MRN marker). D-10: the match is case-SENSITIVE — lowercase\n * `\"mr\"` does NOT match; spec mandates uppercase.\n *\n * D-08: when no MR-typed identifier is found, fall back to the first CX's\n * `idNumber`. Returns `undefined` when the first CX has no `idNumber` (even\n * if later CXs do — the fallback is strictly \"first CX\", not \"first CX with\n * idNumber\", because we need a deterministic answer).\n *\n * D-21: no warning emitted. Callers who need strict MR resolution can walk\n * `patient.identifiers` themselves.\n *\n * @example\n * ```ts\n * import { pickMrn } from \"@cosyte/hl7\";\n * pickMrn([\n * { idNumber: \"X1\" },\n * { idNumber: \"MRN001\", identifierTypeCode: \"MR\" },\n * ]);\n * // → \"MRN001\"\n *\n * pickMrn([{ idNumber: \"X1\" }]);\n * // → \"X1\" (fallback — no MR entry)\n *\n * pickMrn([]);\n * // → undefined\n * ```\n */\nexport function pickMrn(identifiers: readonly CX[]): string | undefined {\n for (const cx of identifiers) {\n if (cx.identifierTypeCode === \"MR\" && cx.idNumber !== undefined) {\n return cx.idNumber;\n }\n }\n const first = identifiers[0];\n return first?.idNumber;\n}\n","/**\n * `buildPatient` — compose PID-derived patient demographics into the frozen\n * `Patient` view exposed by `Hl7Message.patient` (HELPERS-02). Composition\n * happens through the Phase 3 public surface (`msg.segments(\"PID\")[0].field(N)`\n * + composite coercions + `parseCx` / `parseXtn` for multi-rep walks) —\n * never through `rawSegments` directly.\n *\n * Decisions honored here:\n * - D-01: `Object.freeze` the top-level object at the boundary.\n * - D-04: return `undefined` when no PID segment exists.\n * - D-07 / D-08 / D-10: MRN pick via `pickMrn` (isolated for Phase 6).\n * - D-09: `identifiers` is a frozen `readonly CX[]` — always present.\n * - D-17: `fullName` is Western order \"Given Middle Family, Suffix\", omitted\n * parts cleanly joined, absent when no usable parts.\n * - Phase N: `dateOfBirth` is the fidelity `TS` (day-only DOB keeps `precision:\n * \"day\"`, never a UTC-midnight instant that shifts the day).\n * - D-19: flat `familyName` / `givenName` / `middleName` convenience fields\n * mirror XPN, with `middleName` mapped from `XPN.secondName`.\n * - D-20: `phoneNumbers` concatenates PID-13 then PID-14 repetitions.\n * - D-22: never throws — absent / malformed fields surface as omitted keys.\n * - D-23: string reads are decoded via `Field.value` / composite parsers (once at parse).\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { CX } from \"../model/types/cx.js\";\nimport { parseCx } from \"../model/types/cx.js\";\nimport type { XPN } from \"../model/types/xpn.js\";\nimport type { XTN } from \"../model/types/xtn.js\";\nimport { parseXtn } from \"../model/types/xtn.js\";\n\nimport { groupNotes } from \"./notes.js\";\nimport { pickMrn } from \"./pick-mrn.js\";\nimport type { Patient } from \"./types.js\";\n\n/**\n * Compose the `fullName` string in Western order \"Given Middle Family,\n * Suffix\" from XPN parts (D-17). Missing parts are omitted cleanly — no\n * double spaces, no leading/trailing comma. Returns `undefined` when no\n * usable parts remain so the helper can omit the key entirely.\n *\n * @internal\n */\nfunction composeFullName(name: XPN): string | undefined {\n const parts: string[] = [];\n if (name.givenName !== undefined && name.givenName !== \"\") parts.push(name.givenName);\n if (name.secondName !== undefined && name.secondName !== \"\") parts.push(name.secondName);\n if (name.familyName !== undefined && name.familyName !== \"\") parts.push(name.familyName);\n const base = parts.join(\" \");\n const suffix = name.suffix;\n const hasSuffix = suffix !== undefined && suffix !== \"\";\n let full: string;\n if (hasSuffix) {\n full = base === \"\" ? suffix : `${base}, ${suffix}`;\n } else {\n full = base;\n }\n return full === \"\" ? undefined : full;\n}\n\n/**\n * Build the immutable `Patient` view from a parsed message's PID segment, or\n * return `undefined` when no PID exists (D-04). The returned object is\n * deeply frozen (D-01) and consumed through the memoized `Hl7Message.patient`\n * getter (D-02). Absent fields are OMITTED (exactOptionalPropertyTypes); the\n * `name`, `identifiers`, and `phoneNumbers` fields are ALWAYS present (D-09,\n * D-19, D-20).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.patient?.mrn); // first CX-5=\"MR\" idNumber\n * console.log(msg.patient?.fullName); // \"Jane Q Smith, Jr\"\n * console.log(msg.patient?.dateOfBirth?.raw); // fidelity TS (Phase N) — e.g. \"19800115\"\n * for (const phone of msg.patient?.phoneNumbers ?? []) {\n * console.log(phone.telephoneNumber);\n * }\n * ```\n *\n * @internal\n */\nexport function buildPatient(msg: Hl7Message): Patient | undefined {\n const pid = msg.segments(\"PID\")[0];\n if (pid === undefined) return undefined; // D-04\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Patient> = {};\n\n // ─── PID-3 identifiers (D-09) + MRN pick (D-07 / D-08 / D-10) ─────────\n const identifiers: CX[] = [];\n for (const rep of pid.field(3).repetitions) {\n const cx = parseCx(rep, msg.encodingCharacters);\n if (Object.keys(cx).length > 0) identifiers.push(cx);\n }\n const frozenIds = Object.freeze(identifiers);\n out.identifiers = frozenIds;\n\n const mrn = pickMrn(frozenIds);\n if (mrn !== undefined) out.mrn = mrn;\n\n // ─── PID-5 name (XPN) + flat D-19 shortcuts + D-17 fullName ───────────\n const name = pid.field(5).asXpn();\n out.name = name; // always present, may be `{}` on absent PID-5\n\n if (name.familyName !== undefined) out.familyName = name.familyName;\n if (name.givenName !== undefined) out.givenName = name.givenName;\n if (name.secondName !== undefined) out.middleName = name.secondName; // D-19 rename\n\n const fullName = composeFullName(name);\n if (fullName !== undefined) out.fullName = fullName;\n\n // ─── PID-7 date of birth (Phase N fidelity TS) ────────────────────────\n const dob = pid.field(7).asTs();\n if (dob.valid) out.dateOfBirth = dob;\n\n // ─── PID-8 administrative sex (flat string) ───────────────────────────\n const sex = pid.field(8).value;\n if (sex !== \"\") out.sex = sex;\n\n // ─── PID-11 address (XAD) — omit when empty ───────────────────────────\n const address = pid.field(11).asXad();\n if (Object.keys(address).length > 0) out.address = address;\n\n // ─── PID-13 home + PID-14 business phones, concatenated (D-20) ────────\n const phones: XTN[] = [];\n for (const rep of pid.field(13).repetitions) {\n const xtn = parseXtn(rep, msg.encodingCharacters);\n if (Object.keys(xtn).length > 0) phones.push(xtn);\n }\n for (const rep of pid.field(14).repetitions) {\n const xtn = parseXtn(rep, msg.encodingCharacters);\n if (Object.keys(xtn).length > 0) phones.push(xtn);\n }\n out.phoneNumbers = Object.freeze(phones);\n\n // ─── PID-10 race (CWE) ───────────────────────────────────────────────\n const race = pid.field(10).asCwe();\n if (Object.keys(race).length > 0) out.race = race;\n\n // ─── PID-22 ethnicity (CWE) ──────────────────────────────────────────\n const ethnicity = pid.field(22).asCwe();\n if (Object.keys(ethnicity).length > 0) out.ethnicity = ethnicity;\n\n // ─── PID-15 primary language (CE) ────────────────────────────────────\n const language = pid.field(15).asCe();\n if (Object.keys(language).length > 0) out.language = language;\n\n // ─── Phase P: NTE notes positionally attached to this PID ─────────────\n // Notes immediately following the (first) PID segment attach to the patient.\n // A second PID's group notes ride on that PID segment but are not surfaced\n // here (the patient view is the first PID — a documented single-patient model).\n // The array is already frozen by `groupNotes`; a later PID's notes are routed\n // to `msg.notes()` there, never mis-attached to this first-PID patient view.\n const patientNotes = groupNotes(msg).byParent.get(pid);\n if (patientNotes !== undefined && patientNotes.length > 0) out.notes = patientNotes;\n\n // D-01 freeze at boundary.\n return Object.freeze(out) as Patient;\n}\n","/**\n * `buildStructure` — compose the read-side `MessageStructure` summary exposed\n * by `Hl7Message.structure` (roadmap Phase G). It mirrors, on the public\n * message surface, the same conservative expected-group analysis the parser\n * runs at parse time to emit `MISSING_EXPECTED_GROUP` warnings — so a consumer\n * can ask \"did this message carry its expected core groups?\" without scanning\n * `msg.warnings`.\n *\n * Composes on the Phase 3 public surface (`msg.get`, `msg.allSegments()`) —\n * never walks `rawSegments` directly. D-01 freeze at boundary (the underlying\n * `analyzeMessageStructure` already freezes deeply). D-02 memoization is the\n * caller's job (`Hl7Message.structure` getter). D-22 never throws.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport { analyzeMessageStructure, type MessageStructure } from \"../parser/message-structure.js\";\n\n/**\n * Build the immutable `MessageStructure` summary for a parsed message. Reads\n * the message type from MSH-9.1 / MSH-9.2 and the present segment names from\n * `msg.allSegments()`, then defers to the pure `analyzeMessageStructure`. The\n * result is deeply frozen and consumed through the memoized\n * `Hl7Message.structure` getter.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.structure.recognized); // true for known types\n * console.log(msg.structure.missingGroups); // e.g. [\"result\"]\n * ```\n *\n * @internal\n */\nexport function buildStructure(msg: Hl7Message): MessageStructure {\n const messageCode = msg.get(\"MSH.9.1\") ?? \"\";\n const triggerEvent = msg.get(\"MSH.9.2\") ?? \"\";\n const presentSegmentNames = new Set<string>();\n for (const seg of msg.allSegments()) presentSegmentNames.add(seg.type);\n return analyzeMessageStructure(messageCode, triggerEvent, presentSegmentNames);\n}\n","/**\n * `buildVisit` — Phase 4 Plan 03 (visit-and-observations) implementation of\n * HELPERS-03. Reads the first PV1 segment (if any) and projects the 7 locked\n * v1 fields as a deeply frozen `Visit` object, composing on Phase 3's public\n * read surface (`msg.segments(\"PV1\")[0].field(n).asXxx()`).\n *\n * Design decisions enforced here:\n * - D-04 nullable: returns `undefined` when no PV1 segment is present.\n * - Phase N: admit/discharge timestamps are the fidelity `TS` (precision +\n * timezone preserved), not an eager `Date`.\n * - D-24 option (a): attendingDoctor/referringDoctor use the Plan 01\n * `Field.asXcn()` coercion (composite, not flat string).\n * - D-01 freeze at boundary: the returned Visit is frozen.\n * - D-22 never-throws: every field reaches a safe default when absent or\n * malformed (empty strings and empty composites are omitted via\n * `exactOptionalPropertyTypes`).\n * - D-02 memoization is handled by the `Hl7Message.visit` getter — this\n * function is invoked lazily on first access and its result is cached.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { PL } from \"../model/types/pl.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\nimport type { Visit } from \"./types.js\";\n\n/** Return `undefined` when an empty-composite parse (`{}`) leaks through. @internal */\nfunction nonEmptyPl(pl: PL): PL | undefined {\n return Object.keys(pl).length === 0 ? undefined : pl;\n}\n\n/** Return `undefined` when an empty-composite XCN parse (`{}`) leaks through. @internal */\nfunction nonEmptyXcn(xcn: XCN): XCN | undefined {\n return Object.keys(xcn).length === 0 ? undefined : xcn;\n}\n\n/**\n * Build the immutable `Visit` view for a parsed message, or `undefined`\n * when no PV1 segment exists (HELPERS-03 nullable). Memoized by\n * `Hl7Message.visit` (D-02); mutations drop the cache wholesale via\n * `invalidateCaches()`.\n *\n * Doctors (attendingDoctor/referringDoctor) are XCN composites per D-24\n * option (a). admitDateTime/dischargeDateTime are the fidelity `TS` (Phase N).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.visit?.patientClass); // \"I\"\n * console.log(msg.visit?.location?.pointOfCare); // \"ICU\"\n * console.log(msg.visit?.admitDateTime?.raw); // fidelity TS (Phase N)\n * console.log(msg.visit?.attendingDoctor?.familyName); // XCN via D-24(a)\n * ```\n *\n * @internal\n */\nexport function buildVisit(msg: Hl7Message): Visit | undefined {\n const pv1 = msg.segments(\"PV1\")[0];\n if (pv1 === undefined) return undefined; // HELPERS-03 nullable\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Visit> = {};\n\n // PV1-2: patientClass (flat string)\n const patientClass = pv1.field(2).value;\n if (patientClass !== \"\") out.patientClass = patientClass;\n\n // PV1-3: location (PL)\n const location = nonEmptyPl(pv1.field(3).asPl());\n if (location !== undefined) out.location = location;\n\n // PV1-7: attendingDoctor (XCN — D-24 option (a))\n const attending = nonEmptyXcn(pv1.field(7).asXcn());\n if (attending !== undefined) out.attendingDoctor = attending;\n\n // PV1-8: referringDoctor (XCN)\n const referring = nonEmptyXcn(pv1.field(8).asXcn());\n if (referring !== undefined) out.referringDoctor = referring;\n\n // PV1-19: visitNumber. Spec-wise PV1-19 is a CX — the lean v1 shape surfaces\n // the first component (idNumber) via `.value`. Callers needing the full CX\n // can reach msg.segments(\"PV1\")[0].field(19).asCx().\n const visitNumber = pv1.field(19).value;\n if (visitNumber !== \"\") out.visitNumber = visitNumber;\n\n // PV1-44: admitDateTime (fidelity TS, Phase N)\n const admit = pv1.field(44).asTs();\n if (admit.valid) out.admitDateTime = admit;\n\n // PV1-45: dischargeDateTime (fidelity TS, Phase N)\n const discharge = pv1.field(45).asTs();\n if (discharge.valid) out.dischargeDateTime = discharge;\n\n return Object.freeze(out);\n}\n","/**\n * `emitPrettyPrint` — human-readable multi-line rendering of an `Hl7Message`\n * for logs and debugging (SER-04).\n *\n * Implementation lives in Phase 5 Plan 04 (pretty-print). Stub throws.\n *\n * Decisions (for Plan 04 implementer):\n * - D-22: no options — single opinionated format.\n * - D-23: segment-per-line with labeled fields `[N]=value`. Field values\n * shown verbatim with active delimiters; empty trailing positions suppressed.\n * - D-24: resolution depth stops at field level — composite values render as\n * their raw HL7 string (e.g. `Smith^John^Q`).\n * - D-25: first line is a metadata header\n * `HL7 <type> controlId=<id> timestamp=<raw-hl7> (<N> segments)`.\n * - D-26: pure — never warns or throws.\n *\n * @internal\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { RawSegment } from \"../parser/types.js\";\nimport { emitField } from \"./emit-field.js\";\n\n/**\n * Emit a human-readable multi-line rendering of a parsed `Hl7Message` for\n * logs and debugging (SER-04). Single opinionated format per D-22; no\n * options. Header per D-25; segment lines per D-23; depth stops at field\n * level per D-24; pure per D-26.\n *\n * **Raw-escape rendering (W2):** field values render as their raw HL7\n * string representation, produced via `emitField`. Embedded delimiters in\n * user data appear as HL7 escape sequences — e.g. a patient family name\n * that was decoded from `\\F\\` on input (literal `|` in `Field.value`)\n * renders in pretty-print as `Smith\\F\\Jones`, NOT as `Smith|Jones`. This\n * preserves round-trip fidelity: copy-pasting the output into `parseHL7`\n * yields a structurally equivalent message. For un-escaped human display,\n * use typed accessors (e.g. `msg.patient?.familyName`), which return\n * already-decoded strings.\n *\n * @internal\n */\nexport function emitPrettyPrint(msg: Hl7Message): string {\n const lines: string[] = [];\n lines.push(buildHeaderLine(msg));\n for (const seg of msg.rawSegments) {\n lines.push(buildSegmentLine(seg, msg));\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * D-25 header:\n * `HL7 <type> controlId=<id> timestamp=<raw-hl7> (<N> segments)`\n * Missing meta fields render as `-`. Segment count is always a number.\n * Separator between header fields is TWO spaces.\n * @internal\n */\nfunction buildHeaderLine(msg: Hl7Message): string {\n const meta = msg.meta;\n const type = meta.type ?? \"-\";\n const controlId = meta.controlId ?? \"-\";\n // Phase N: render the raw HL7 timestamp verbatim (precision + zone preserved)\n // rather than coercing to a UTC ISO instant, which would misstate a day-only\n // or offset-less value.\n const timestamp = meta.timestamp?.raw ?? \"-\";\n const segCount = msg.rawSegments.length;\n return (\n \"HL7 \" +\n type +\n \" controlId=\" +\n controlId +\n \" timestamp=\" +\n timestamp +\n \" (\" +\n String(segCount) +\n \" segments)\"\n );\n}\n\n/**\n * D-23 segment line:\n * `<seg.name> [N]=<emittedFieldValue> [M]=<emittedFieldValue> ...`\n * - Non-MSH: start at fields[1] with HL7 index 1.\n * - MSH: start at fields[2] with HL7 index 3 (MSH-1/MSH-2 are the\n * delimiters themselves and are not labelled — their content is\n * implicit in the header).\n * - Field rendered via `emitField` (D-24 depth stop + W2 raw-escape).\n * - Empty-emitted values are SUPPRESSED (no `[N]=` entry) so sparse\n * segments stay terse. `isNull === true` emits `\"\"` (2 chars) and IS\n * shown.\n * - A segment with only absent fields emits just the segment name\n * (no trailing spaces).\n * @internal\n */\nfunction buildSegmentLine(seg: RawSegment, msg: Hl7Message): string {\n const enc = msg.encodingCharacters;\n // First data field index and first displayed HL7 field number:\n // - MSH: fields[2] -> [3]\n // - non-MSH: fields[1] -> [1]\n const isMsh = seg.name === \"MSH\";\n const firstFieldIndex = isMsh ? 2 : 1;\n const firstDisplayNumber = isMsh ? 3 : 1;\n\n const labeledParts: string[] = [];\n for (let i = firstFieldIndex; i < seg.fields.length; i++) {\n const f = seg.fields[i];\n if (f === undefined) continue;\n const emitted = emitField(f, enc);\n if (emitted === \"\") continue; // suppress absent-field labels\n const displayNumber = firstDisplayNumber + (i - firstFieldIndex);\n labeledParts.push(\"[\" + String(displayNumber) + \"]=\" + emitted);\n }\n\n if (labeledParts.length === 0) return seg.name;\n return seg.name + \" \" + labeledParts.join(\" \");\n}\n","/**\n * `emitJson` + `SerializedMessage` — snapshot-stable JSON projection of an\n * `Hl7Message`. Mirrors `rawSegments` one-for-one; preserves `isNull`;\n * always includes `warnings: []`; omits `profile` when absent.\n *\n * The `SerializedMessage` interface is exported in Plan 01 (this file) so\n * consumers + `src/index.ts` can reference the type immediately. The\n * `emitJson` function body is filled in Phase 5 Plan 03 (to-json).\n *\n * Decisions:\n * - D-17: shape is a raw-tree mirror (encodingCharacters + segments +\n * warnings + optional profile).\n * - D-18: `Hl7Message.toJSON` delegates here so `JSON.stringify(msg)` Just Works.\n * - D-19: warnings array is ALWAYS present (`warnings: []` when empty).\n * - D-20: `profile` field appears only when `msg.profile` is truthy — then\n * contains only `name` + `lineage`.\n * - D-21: `SerializedMessage` is exported from `src/index.ts` (not nested\n * under HL7 namespace).\n *\n * Note on runtime freeze scope: `emitJson` returns an object that is\n * boundary-frozen (top level only — `Object.isFrozen(msg.toJSON()) === true`).\n * Inner arrays are readonly at the TypeScript type level but MUTABLE at\n * runtime — consumers should treat the returned structure as immutable\n * and not mutate nested arrays. Deep-freeze is explicitly rejected per\n * D-30 (emit is hot-path; runtime deep-freeze would add cost with no\n * observable benefit given the type-level readonly contract).\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { EncodingCharacters } from \"../parser/types.js\";\nimport type { Hl7ParseWarning } from \"../parser/warnings.js\";\n\n/**\n * Snapshot-stable JSON projection of an `Hl7Message` (SER-03). Every field\n * is readonly; segment order is preserved; `isNull` flags are preserved.\n *\n * Runtime immutability: the top-level object is `Object.freeze`d\n * (boundary-frozen). Inner arrays are readonly at the TypeScript type\n * level but mutable at runtime — treat as immutable, do not mutate.\n *\n * @example\n * ```ts\n * import { parseHL7, type SerializedMessage } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const snap: SerializedMessage = msg.toJSON();\n * console.log(snap.segments[0]?.name); // \"MSH\"\n * console.log(snap.warnings.length); // 0 when clean\n * console.log(JSON.stringify(msg) === JSON.stringify(snap)); // true\n * console.log(Object.isFrozen(snap)); // true (D-30 boundary freeze)\n * ```\n */\nexport interface SerializedMessage {\n readonly encodingCharacters: EncodingCharacters;\n readonly segments: ReadonlyArray<{\n readonly name: string;\n readonly fields: ReadonlyArray<{\n readonly repetitions: ReadonlyArray<{\n readonly components: ReadonlyArray<{ readonly subcomponents: readonly string[] }>;\n }>;\n readonly isNull: boolean;\n }>;\n }>;\n readonly warnings: readonly Hl7ParseWarning[];\n readonly profile?: { readonly name: string; readonly lineage: readonly string[] };\n}\n\n/**\n * Build the `SerializedMessage` snapshot from a parsed message (SER-03).\n * Raw-tree mirror per D-17; warnings array always present (D-19); profile\n * included only when `msg.profile` is truthy (D-20). Pure — never warns,\n * never throws. Not cached (D-30 — each call re-walks `rawSegments`).\n *\n * Boundary-frozen: the top-level returned object passes through\n * `Object.freeze` before return, so `Object.isFrozen(result) === true`.\n * Inner arrays are readonly at the TS type level but NOT runtime-frozen\n * (D-30 cost doctrine — emit is hot-path; deep-freeze would add traversal\n * cost with no observable benefit beyond the type contract).\n *\n * Shared Phase-2 invariant (established by Plan 02): the raw tree stores\n * DECODED subcomponent strings (tokenize now unescapes on parse). emitJson\n * mirrors those decoded strings verbatim — NO re-escape transformation is\n * applied here; the JSON projection reflects the decoded source of truth.\n *\n * @internal\n */\nexport function emitJson(msg: Hl7Message): SerializedMessage {\n // Raw-tree mirror (D-17). Build fresh plain objects so the output is\n // decoupled from the parser's internal arrays. `subcomponents.slice()`\n // clones the inner string array; primitives are cloned for free.\n const segments = msg.rawSegments.map((seg) => ({\n name: seg.name,\n fields: seg.fields.map((field) => ({\n // D-17 + Claude's-Discretion: `repetitions` is ALWAYS `[]` when the\n // field has zero repetitions — shape-stable, no conditional omission.\n repetitions: field.repetitions.map((rep) => ({\n components: rep.components.map((comp) => ({\n subcomponents: comp.subcomponents.slice(),\n })),\n })),\n isNull: field.isNull,\n })),\n }));\n\n // exactOptionalPropertyTypes-safe conditional-assign pattern. An absent\n // `profile` key is valid for the optional field; an explicit\n // `profile: undefined` is NOT. Mirrors `src/helpers/meta.ts::buildMeta`.\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<SerializedMessage> = {\n encodingCharacters: {\n field: msg.encodingCharacters.field,\n component: msg.encodingCharacters.component,\n repetition: msg.encodingCharacters.repetition,\n escape: msg.encodingCharacters.escape,\n subcomponent: msg.encodingCharacters.subcomponent,\n },\n segments,\n // D-19: ALWAYS present, even when empty. `msg.warnings` is already frozen\n // at Hl7Message construction (Phase 2) — pass-through is safe.\n warnings: msg.warnings,\n };\n\n if (msg.profile !== undefined) {\n // D-20 structural contract: EXACTLY `{name, lineage}`. The upstream\n // parser constructor (src/parser/index.ts) already strips any extra\n // `Profile`-descriptor fields (onWarning, customSegments, dateFormats,\n // description) before assigning to `Hl7Message.profile`. `lineage` is\n // REQUIRED (not optional) when profile is defined — straight\n // assignment; no nullish-coalesce fallback (would be dead code given\n // the type guarantee).\n out.profile = {\n name: msg.profile.name,\n lineage: msg.profile.lineage,\n };\n }\n\n // W5: boundary-freeze at the top level only. Inner arrays remain mutable\n // at runtime by design (D-30 — deep-freeze rejected as hot-path cost with\n // no observable benefit over the TS readonly type contract).\n return Object.freeze(out) as SerializedMessage;\n}\n","/**\n * `emitMessage` — top-level HL7 string emitter. Composes `emitSegment` from\n * `./emit-field.ts`, special-cases MSH-1 / MSH-2 per D-06, and joins segments\n * with strict CR (`\\r`) per D-05.\n *\n * Implementation lives in Phase 5 Plan 02 (to-string-and-round-trip). This\n * stub exists so Plan 01 can wire the `Hl7Message.toString` instance method\n * before Plan 02 runs; invoking it throws.\n *\n * Decisions (for Plan 02 implementer):\n * - D-01: walk `msg.rawSegments` verbatim.\n * - D-04: every field string passes through `emitField` (which calls\n * `reescape` internally).\n * - D-05: segments joined by `\\r`; trailing `\\r` after the last segment.\n * - D-06: MSH-1 / MSH-2 inlined (see CONTEXT §specifics emission trace).\n * - D-07: pure — never warns, never throws.\n * - D-08: no MLLP wrapping.\n *\n * @internal\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport { emitField, emitSegment } from \"./emit-field.js\";\nimport type { EncodingCharacters, RawSegment } from \"../parser/types.js\";\n\n/**\n * Emit a parsed `Hl7Message` as spec-clean HL7 (SER-01 + SER-05). Walks\n * `msg.rawSegments` verbatim (D-01). Inlines MSH-1 and MSH-2 from\n * `msg.encodingCharacters` per D-06. Joins segments with strict CR (`\\r`)\n * and appends a trailing CR per D-05. Does NOT wrap in MLLP framing (D-08).\n *\n * Trailing-empty semantics: D-02's trailing-empty strip is field-SCOPED\n * (inside `emitField` — trailing empty repetitions/components/subcomponents\n * are stripped). At the SEGMENT level (inside `emitSegment`) trailing empty\n * fields are PRESERVED to maintain HL7 positional addressing. `emitMessage`\n * does not alter either behavior.\n *\n * Pure for all well-formed inputs — never warns on structurally valid\n * messages (D-07). Throws a typed `Error` ONLY for the structurally\n * invalid case of `msg.rawSegments.length === 0` (W1 fix): emitting a\n * bare `\"\\r\"` for a zero-segment message would violate the \"serializer\n * is conservative (always emits spec-clean HL7)\" guardrail, since\n * `parseHL7(\"\\r\")` fails with `NO_MSH_SEGMENT`. The throw mirrors the\n * D-06 MSH guard in `emitSegment` — catch programmer misuse loudly at\n * the call site rather than silently corrupting wire output. The parser\n * cannot produce an empty `rawSegments`, so this path is only reachable\n * via direct `new Hl7Message({ segments: [] })` construction or post-\n * `removeSegment` edge cases.\n *\n * @internal\n */\nexport function emitMessage(msg: Hl7Message): string {\n if (msg.rawSegments.length === 0) {\n throw new Error(\n \"emitMessage: refusing to emit a message with zero segments. \" +\n \"Every HL7 message must contain at least an MSH segment per HL7 v2 spec.\",\n );\n }\n const enc = msg.encodingCharacters;\n const segmentStrings: string[] = [];\n for (const seg of msg.rawSegments) {\n if (seg.name === \"MSH\") {\n segmentStrings.push(emitMshSegment(seg, enc));\n } else {\n segmentStrings.push(emitSegment(seg, enc));\n }\n }\n return segmentStrings.join(\"\\r\") + \"\\r\";\n}\n\n/**\n * Emit the MSH segment with the D-06 special case: MSH-1 is `enc.field`\n * (one char, inlined immediately after \"MSH\"), MSH-2 is\n * `enc.component + enc.repetition + enc.escape + enc.subcomponent`\n * (4 chars, fixed order), and MSH-3..N use the normal `emitField` path\n * joined by `enc.field`.\n *\n * This is the exact inverse of Phase 2 `readDelimiters`:\n * - `readDelimiters` reads `firstSegment.charAt(3)` as the field separator\n * and `firstSegment.slice(4, 8)` as MSH-2;\n * - `emitMshSegment` writes `\"MSH\" + enc.field + <MSH-2 chars> + enc.field + <rest>`.\n *\n * Trailing empty fields in MSH-3..N are PRESERVED (W3) — no trimming of\n * the `tailParts` array before joining.\n *\n * **IMPORTANT — `seg.fields[0]` and `seg.fields[1]` content is IGNORED**\n * (WR-02): MSH-1 and MSH-2 are emitted from `msg.encodingCharacters` per\n * D-06, which is the single source of truth. This is a deliberate\n * deviation from the general D-01 \"walk `msg.rawSegments` verbatim\"\n * doctrine, because running MSH-2 through `emitField` would re-escape\n * the encoding chars and produce garbage. For parser-produced messages\n * `fields[0]` / `fields[1]` always match `encodingCharacters`. For\n * synthetic messages constructed via `new Hl7Message({...})` directly,\n * the burden is on the caller to keep `encodingCharacters` aligned with\n * the raw tree's MSH-1/MSH-2 placeholders — if they diverge, this\n * emitter silently favors `encodingCharacters`.\n *\n * @internal\n */\nfunction emitMshSegment(seg: RawSegment, enc: EncodingCharacters): string {\n // MSH-2 literal chars (D-06 fixed order). When the parsed encoding carried\n // a v2.7+ truncation char (5-char MSH-2), emit it in the 5th position so\n // the wire form round-trips byte-exact.\n const msh2 =\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\");\n // MSH-3..N: fields[2..N] via emitField, joined by enc.field.\n // W3: trailing empty fields preserved — do NOT pop trailing \"\" off tailParts.\n const tailParts: string[] = [];\n for (let i = 2; i < seg.fields.length; i++) {\n const f = seg.fields[i];\n tailParts.push(f === undefined ? \"\" : emitField(f, enc));\n }\n const tail = tailParts.join(enc.field);\n // D-06 exact emission trace:\n // \"MSH\" + enc.field + enc.component + enc.repetition + enc.escape +\n // enc.subcomponent + enc.field + <tail>\n // = \"MSH\" + enc.field + msh2 + enc.field + tail\n return \"MSH\" + enc.field + msh2 + enc.field + tail;\n}\n","/**\n * `Hl7Message` — the immutable parsed-message model produced by `parseHL7`.\n * Phase 2 shipped the read-only shell; Phase 3 extends the same class with\n * the read-path traversal methods (`get`, `getAll`, `segments`,\n * `allSegments`) on top of lazy, referentially stable Segment/Field caches\n * (D-11/D-12). The constructor surface is unchanged (Phase 2 D-05 lock) —\n * `init.segments` is still the parser-side key, but the public raw-tree\n * field is now exposed as `rawSegments` to free up the name `segments` for\n * the typed `segments(type)` method.\n */\n\nimport { parsePath, resolvePath } from \"./dot-path.js\";\nimport { Segment } from \"./segment.js\";\nimport type {\n CustomSegmentDefinition,\n EncodingCharacters,\n RawComponent,\n RawField,\n RawRepetition,\n RawSegment,\n} from \"../parser/types.js\";\nimport type { Hl7ParseWarning } from \"../parser/warnings.js\";\nimport { allergies as walkAllergies } from \"../helpers/allergies.js\";\nimport { appointments as walkAppointments } from \"../helpers/appointments.js\";\nimport { charges as walkCharges } from \"../helpers/charges.js\";\nimport { diagnoses as walkDiagnoses } from \"../helpers/diagnoses.js\";\nimport { documents as walkDocuments } from \"../helpers/documents.js\";\nimport type { IdentityEvent } from \"../helpers/identity.js\";\nimport { identityEvents as walkIdentityEvents } from \"../helpers/identity.js\";\nimport { immunizations as walkImmunizations } from \"../helpers/immunizations.js\";\nimport { insurance as walkInsurance } from \"../helpers/insurance.js\";\nimport { medications as walkMedications } from \"../helpers/medications.js\";\nimport { buildMeta } from \"../helpers/meta.js\";\nimport { nextOfKin as walkNextOfKin } from \"../helpers/next-of-kin.js\";\nimport { notes as walkNotes } from \"../helpers/notes.js\";\nimport { observations as walkObservations } from \"../helpers/observations.js\";\nimport { orders as walkOrders } from \"../helpers/orders.js\";\nimport { buildPatient } from \"../helpers/patient.js\";\nimport { buildStructure } from \"../helpers/structure.js\";\nimport type {\n Allergy,\n Appointment,\n Charge,\n ClinicalDocument,\n Diagnosis,\n Immunization,\n Insurance,\n Medication,\n Meta,\n NextOfKin,\n Observation,\n Order,\n Patient,\n Visit,\n} from \"../helpers/types.js\";\nimport type { MessageStructure } from \"../parser/message-structure.js\";\nimport { buildVisit } from \"../helpers/visit.js\";\nimport { emitPrettyPrint } from \"../serialize/pretty-print.js\";\nimport { emitJson, type SerializedMessage } from \"../serialize/to-json.js\";\nimport { emitMessage } from \"../serialize/to-string.js\";\n\n/**\n * HL7 segment-name shape: 3 characters, first an uppercase ASCII letter,\n * remaining two uppercase ASCII letters or digits — `[A-Z][A-Z0-9]{2}`.\n * This matches standard HL7 v2 segment names (MSH, PID, PV1, PV2, OBX,\n * OBR, NK1, AL1, DG1, IN1, IN2, IN3, …) AND Z-segment custom shapes\n * (ZPI, ZX1, …). Enforced symmetrically on `addSegment` and\n * `removeSegment` so consumers see consistent validation for any mutation\n * that takes a segment name.\n * @internal\n */\nconst SEGMENT_NAME_RE = /^[A-Z][A-Z0-9]{2}$/u;\n\n/**\n * Shallow-copy a readonly array to a mutable one. Mutation methods rebuild\n * the affected path from leaf to root to keep the declared `readonly Raw*`\n * shapes honest — this helper is the one sanctioned bridge from readonly to\n * mutable for Phase 3 mutation.\n * @internal\n */\nfunction toMutableArray<T>(arr: readonly T[]): T[] {\n return arr.slice();\n}\n\n/**\n * Constructor init shape for `Hl7Message`. Exposed for advanced use (e.g.\n * constructing synthetic messages in tests or higher-level builders) but\n * most consumers should rely on `parseHL7` to produce `Hl7Message`\n * instances.\n *\n * @remarks\n * With `exactOptionalPropertyTypes: true`, callers cannot pass\n * `{ profile: undefined }` — either omit the key or pass a real profile\n * descriptor. This matches the `Hl7Message.profile` public field shape\n * (`... | undefined`).\n *\n * The init key is still named `segments` (not `rawSegments`) so Phase 2\n * parser code that constructs `Hl7Message` does not need to change. Inside\n * the class body the raw tree is stored on `this.rawSegments`.\n *\n * @internal\n */\nexport interface Hl7MessageInit {\n readonly segments: readonly RawSegment[];\n readonly encodingCharacters: EncodingCharacters;\n readonly version: string;\n readonly warnings: readonly Hl7ParseWarning[];\n readonly profile?: { readonly name: string; readonly lineage: readonly string[] };\n /**\n * Merged customSegments map from the applied profile (D-16). Threaded\n * into Segment constructors so `seg.get(fieldName)` can resolve custom\n * positions (PROF-07). Absent when no profile was applied.\n */\n readonly customSegments?: Readonly<Record<string, CustomSegmentDefinition>>;\n /**\n * Merged `dateFormats` list — `options.dateFormats ++ profile.dateFormats`\n * deduped first-occurrence per D-21. Consumed by `msg.meta.timestamp` and\n * any future helper that calls `parseDtmCascade` directly. Absent when\n * neither `options.dateFormats` nor `profile.dateFormats` was supplied.\n */\n readonly dateFormats?: readonly string[];\n}\n\n/**\n * Parsed HL7 v2 message. Produced by `parseHL7`. Exposes the raw positional\n * tree (`rawSegments`), delimiter metadata, warnings, and a typed traversal\n * surface — `get(path)` for dot-paths, `getAll(type)` / `segments(type)` /\n * `allSegments()` for wrapper-level iteration.\n *\n * @remarks\n * The `warnings` array is frozen at the model boundary so downstream\n * traversal and helper phases cannot mutate parser output. The `profile`\n * field is populated by Phase 6 when a profile is passed; Phase 2 leaves\n * it `undefined` by default. Segment/Field wrappers are cached per-message\n * and invalidated wholesale by Plan 04 mutation methods.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.get(\"PID.5.1\")); // \"Smith\"\n * for (const obx of msg.segments(\"OBX\")) {\n * console.log(obx.field(5).value);\n * }\n * for (const w of msg.warnings) console.warn(w.code);\n * ```\n */\nexport class Hl7Message {\n /**\n * Raw positional tree produced by the parser. 1-indexed per HL7 convention\n * (`fields[0]` is the segment-name / MSH separator placeholder slot). Use\n * `segments(type)` / `allSegments()` for typed wrapper access — this field\n * is exposed for advanced callers that need the raw tree directly (e.g.\n * future serialization phase 5).\n */\n public readonly rawSegments: readonly RawSegment[];\n\n public readonly encodingCharacters: EncodingCharacters;\n public readonly version: string;\n public readonly warnings: readonly Hl7ParseWarning[];\n public readonly profile:\n | { readonly name: string; readonly lineage: readonly string[] }\n | undefined;\n\n /**\n * Merged `dateFormats` list — `options.dateFormats ++ profile.dateFormats`\n * deduped first-occurrence per D-21. Empty array when neither source\n * supplied any formats. Exposed publicly so helpers (`msg.meta.timestamp`)\n * and advanced callers can introspect the active cascade.\n */\n public readonly dateFormats: readonly string[];\n\n /**\n * Merged `customSegments` map from the applied profile, stored so\n * `allSegments()` can hand per-segment slices to `Segment` constructors\n * (D-16). Undefined when no profile was applied.\n * @internal\n */\n private _customSegments: Readonly<Record<string, CustomSegmentDefinition>> | undefined;\n\n /**\n * Lazily built cache of Segment wrappers keyed by segment type. Built on\n * first `segments(type)` call and filtered from `_allSegments` so\n * individual Segment instances are identical across both caches (D-11).\n * Plan 04 mutation methods drop this cache wholesale.\n * @internal\n */\n private _segmentsByType: Map<string, readonly Segment[]> | undefined;\n\n /**\n * Lazily built cache of every Segment wrapper in document order. Built on\n * first `segments(type)` / `allSegments()` call. Plan 04 mutation methods\n * drop this cache wholesale.\n * @internal\n */\n private _allSegments: readonly Segment[] | undefined;\n\n /**\n * Lazily built `Meta` view (Phase 4 D-02 memoization). Dropped wholesale\n * by `invalidateCaches`. `Meta` is always defined (D-03 — MSH absence\n * throws `NO_MSH_SEGMENT` at parse time) so no null-sentinel is needed.\n * @internal\n */\n private _meta: Meta | undefined;\n\n /**\n * Lazily built `MessageStructure` view (Phase G). Dropped wholesale by\n * `invalidateCaches`. Always defined — `analyzeMessageStructure` returns an\n * `recognized: false` summary for unmodelled types rather than absence.\n * @internal\n */\n private _structure: MessageStructure | undefined;\n\n /**\n * Lazily built `Patient | undefined` view (Phase 4 D-02 memoization). Uses\n * a null-sentinel cache because `undefined` means \"not yet computed\" while\n * `null` means \"computed, absent\". D-04: no PID → public value `undefined`.\n * @internal\n */\n private _patient: Patient | null | undefined;\n\n /**\n * Lazily built `Visit | undefined` view (Phase 4 D-02 memoization). Same\n * null-sentinel convention as `_patient`. HELPERS-03: no PV1 → public\n * value `undefined`.\n * @internal\n */\n private _visit: Visit | null | undefined;\n\n /**\n * Construct a new `Hl7Message`. The constructor takes a plain init\n * object and freezes the warnings array so callers cannot mutate parser\n * output after handoff.\n *\n * @internal\n */\n public constructor(init: Hl7MessageInit) {\n this.rawSegments = init.segments;\n this.encodingCharacters = init.encodingCharacters;\n this.version = init.version;\n // Freeze the warnings array at the model boundary so downstream phases\n // cannot mutate parser output after handoff. `slice()` first to avoid\n // sharing a reference the parser may still hold internally.\n this.warnings = Object.freeze(init.warnings.slice());\n // exactOptionalPropertyTypes: `init.profile` is `{...} | undefined`\n // (the optional key was omitted or the caller passed the real value).\n // The public field declares `... | undefined`, so direct assignment is\n // sound.\n this.profile = init.profile;\n // D-16: stash the merged customSegments map so allSegments() can hand\n // per-segment slices to Segment constructors. Conditional assignment\n // under exactOptionalPropertyTypes — absent key stays undefined.\n if (init.customSegments !== undefined) this._customSegments = init.customSegments;\n // D-21: merged dateFormats list (options ++ profile). Empty array when\n // neither source supplied any formats so the public field is always\n // defined (simpler consumer contract than `readonly string[] | undefined`).\n this.dateFormats = init.dateFormats ?? [];\n }\n\n /**\n * Resolve a dot-path (e.g. `PID.5.1`, `OBX[2].5`, `PID.3[0].1`) to its\n * decoded leaf string (unescaped once at parse — never re-unescaped on read,\n * HL7-VALUE-REDECODE). Returns `undefined` when the path doesn't\n * resolve — never throws on missing path (MODEL-05). Throws `TypeError`\n * on malformed path syntax (e.g. `\"pid.5\"`, empty string).\n *\n * @example\n * ```ts\n * const msg = parseHL7(raw);\n * msg.get(\"PID.5.1\"); // \"Smith\"\n * msg.get(\"OBX[2].5\"); // third OBX's 5th field\n * msg.get(\"NOT.9.9\"); // undefined\n * msg.get(\"MSH.12\"); // \"2.5\" — HL7 version string\n * ```\n */\n public get(path: string): string | undefined {\n return resolvePath(path, this.rawSegments, this.encodingCharacters);\n }\n\n /**\n * Return every `Segment` of `segmentType` in document order. Returns `[]`\n * (empty array, NEVER `undefined`) when no segment of that type exists\n * (MODEL-02). Alias for `segments(segmentType)` — shares the same cache.\n *\n * @example\n * ```ts\n * for (const obx of msg.getAll(\"OBX\")) {\n * console.log(obx.field(5).value);\n * }\n * ```\n */\n public getAll(segmentType: string): readonly Segment[] {\n return this.segments(segmentType);\n }\n\n /**\n * Return the cached array of `Segment` wrappers for `segmentType` in\n * document order. The returned array identity and the individual Segment\n * instances are both stable across calls (D-11). Invalidated wholesale\n * by Plan 04 mutation methods.\n *\n * @example\n * ```ts\n * const pid = msg.segments(\"PID\")[0];\n * if (pid !== undefined) console.log(pid.field(5).value);\n * ```\n */\n public segments(segmentType: string): readonly Segment[] {\n if (this._segmentsByType === undefined) {\n this._segmentsByType = new Map();\n }\n const cached = this._segmentsByType.get(segmentType);\n if (cached !== undefined) return cached;\n\n // Build from the master `_allSegments` cache so individual Segment\n // wrappers are identical across both caches (D-11 cross-cache\n // stability). `allSegments()` builds the master cache on first call.\n const all = this.allSegments();\n const filtered: readonly Segment[] = all.filter((s) => s.type === segmentType);\n this._segmentsByType.set(segmentType, filtered);\n return filtered;\n }\n\n /**\n * Iterate every `Segment` in document order (MSH first, then every\n * subsequent segment). Cached per-message; same array reference and same\n * Segment instances on repeat calls (D-11). Invalidated wholesale by\n * Plan 04 mutation methods.\n *\n * @example\n * ```ts\n * for (const seg of msg.allSegments()) {\n * console.log(seg.type);\n * }\n * ```\n */\n public allSegments(): readonly Segment[] {\n if (this._allSegments !== undefined) return this._allSegments;\n const built: Segment[] = [];\n for (let i = 0; i < this.rawSegments.length; i++) {\n const raw = this.rawSegments[i];\n if (raw === undefined) continue;\n // D-16: hand each Segment its per-segment customFields slice so\n // `seg.get(name)` can resolve named positions. Conditional-pass under\n // exactOptionalPropertyTypes so the optional 4th ctor param stays\n // truly absent (not explicitly undefined) when no profile applied.\n const customFields = this._customSegments?.[raw.name]?.fields;\n if (customFields !== undefined) {\n built.push(new Segment(raw, this.encodingCharacters, i, customFields));\n } else {\n built.push(new Segment(raw, this.encodingCharacters, i));\n }\n }\n this._allSegments = built;\n return built;\n }\n\n /**\n * MSH-derived message metadata (type, controlId, timestamp, version, etc.).\n * D-01: plain object. D-02: memoized — `msg.meta === msg.meta` across\n * reads until mutation invalidates. D-03: always defined (MSH absence\n * throws `NO_MSH_SEGMENT` at parse time).\n *\n * @example\n * ```ts\n * console.log(msg.meta.type); // \"ADT^A01\"\n * console.log(msg.meta.timestamp?.raw); // fidelity TS (Phase N)\n * console.log(msg.meta.controlId); // \"MSG001\"\n * ```\n */\n public get meta(): Meta {\n return (this._meta ??= buildMeta(this));\n }\n\n /**\n * Structural-conformance summary for the common message types (roadmap\n * Phase G) — a misroute/truncation safety net, NOT a conformance validator.\n * Reports, per the message's recognized (MSH-9.1, MSH-9.2) type, which\n * Required segment groups are present and which are entirely absent\n * (`missingGroups` — the same set the parser flags as\n * `MISSING_EXPECTED_GROUP` warnings). For an unmodelled type, `recognized`\n * is `false` and `missingGroups` is empty. D-02: memoized.\n *\n * @example\n * ```ts\n * console.log(msg.structure.recognized); // true for ORU^R01, ADT^A01, …\n * console.log(msg.structure.missingGroups); // e.g. [\"result\"] if no OBR/OBX\n * ```\n */\n public get structure(): MessageStructure {\n return (this._structure ??= buildStructure(this));\n }\n\n /**\n * PID-derived patient view, or `undefined` when no PID segment exists\n * (D-04). D-02: memoized. HELPERS-07: never throws — absent fields\n * surface as `undefined` on the returned `Patient` object.\n *\n * @example\n * ```ts\n * console.log(msg.patient?.mrn);\n * console.log(msg.patient?.fullName);\n * console.log(msg.patient?.dateOfBirth?.raw); // fidelity TS — e.g. \"19800115\"\n * ```\n */\n public get patient(): Patient | undefined {\n if (this._patient === undefined) {\n this._patient = buildPatient(this) ?? null;\n }\n return this._patient === null ? undefined : this._patient;\n }\n\n /**\n * PV1-derived visit view, or `undefined` when no PV1 segment exists\n * (HELPERS-03). D-02: memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * console.log(msg.visit?.patientClass); // \"I\"\n * console.log(msg.visit?.admitDateTime?.raw); // fidelity TS\n * console.log(msg.visit?.attendingDoctor?.familyName);\n * ```\n */\n public get visit(): Visit | undefined {\n if (this._visit === undefined) {\n this._visit = buildVisit(this) ?? null;\n }\n return this._visit === null ? undefined : this._visit;\n }\n\n /**\n * Every OBX segment as a typed Observation in document order. D-05:\n * returns `[]` when no OBX present. D-06: NOT memoized — each call\n * re-walks `rawSegments`. Value type is discriminated per D-13.\n *\n * @example\n * ```ts\n * for (const obs of msg.observations()) {\n * if (obs.valueType === \"NM\") console.log(obs.value); // number | undefined\n * }\n * ```\n */\n public observations(): readonly Observation[] {\n return walkObservations(this);\n }\n\n /**\n * Every OBR as an Order with its OBX children grouped positionally (D-12) and\n * its TQ1 / legacy embedded-TQ (ORC-7) `timings` (Phase M — the repeat pattern\n * surfaced verbatim, never resolved to a schedule). D-05: returns `[]` when no\n * OBR present. D-06: not memoized.\n *\n * @example\n * ```ts\n * for (const order of msg.orders()) {\n * console.log(order.placerOrderNumber, order.observations.length);\n * for (const t of order.timings) console.log(t.repeatPattern?.code); // e.g. \"Q6H\" — verbatim\n * }\n * ```\n */\n public orders(): readonly Order[] {\n return walkOrders(this);\n }\n\n /**\n * Message-level NTE notes (Phase P) — every NTE segment with no recognized\n * preceding parent (not immediately following a `PID`, `ORC`, `OBR`, or\n * `OBX`), surfaced verbatim in document order so nothing is dropped. Notes\n * that DO attach to a specific patient / order / result are exposed on those\n * helper outputs (`msg.patient?.notes`, `order.notes`, `observation.notes`) —\n * not here. D-05: returns `[]` when there are none. D-06: NOT memoized.\n *\n * @example\n * ```ts\n * for (const note of msg.notes()) console.log(note); // message-level narrative\n * ```\n */\n public notes(): readonly string[] {\n return walkNotes(this);\n }\n\n /**\n * Every recognized ADT patient-identity event (merge / move / link /\n * unlink / person add/update — roadmap Phase K), with the MRG-sourced\n * `prior` and PID/PV1-sourced `surviving` parties labelled by role and the\n * spec-constant `direction: \"MRG_TO_PID\"` on merge/move events. Returns\n * `[]` when the trigger event is not in the identity family. D-06: not\n * memoized. Never throws; incomplete merge pairs surface a\n * `MERGE_MISSING_PRIOR_OR_SURVIVOR` warning on the event.\n *\n * @example\n * ```ts\n * for (const ev of msg.identityEvents()) {\n * if (ev.kind === \"merge\" && ev.prior && ev.surviving) {\n * // retire ev.prior.identifiers in favour of ev.surviving.identifiers\n * }\n * }\n * ```\n */\n public identityEvents(): readonly IdentityEvent[] {\n return walkIdentityEvents(this);\n }\n\n /**\n * Every RXO/RXE/RXD/RXA as a typed `Medication`, with RXR (route) and RXC\n * (component) segments grouped positionally under their parent (Phase D,\n * P0 safety). D-05: returns `[]` when no RX* parent present. D-06: not\n * memoized. The give *amount* and give *strength* are surfaced separately\n * and never reconciled (Phase D §4).\n *\n * Each medication also carries its TQ1 / legacy embedded-TQ (RXE-1) `timings`\n * (Phase M — repeat pattern verbatim, never resolved to a schedule).\n *\n * @example\n * ```ts\n * for (const med of msg.medications()) {\n * console.log(med.context, med.giveCode?.identifier, med.giveCode?.nameOfCodingSystem);\n * console.log(med.amount?.minimum, med.strength?.value);\n * for (const t of med.timings) console.log(t.repeatPattern?.code, t.totalOccurrences);\n * }\n * ```\n */\n public medications(): readonly Medication[] {\n return walkMedications(this);\n }\n\n /**\n * Every RXA of a VXU^V04 as a typed `Immunization`, with RXR (route/site)\n * and OBX children grouped positionally under the RXA and `orderControl`\n * from the preceding ORC of the VXU order group (Phase E, P0 safety). D-05:\n * returns `[]` when no RXA present. D-06: not memoized. The vaccine code\n * carries its own provenance; the action code (RXA-21) is surfaced verbatim\n * and `recordOrigin` (administered vs historical) is derived only from the\n * well-known NIP001 RXA-9.1 codes — never guessed.\n *\n * @example\n * ```ts\n * for (const imm of msg.immunizations()) {\n * console.log(imm.vaccineCode?.identifier, imm.doseAmount, imm.recordOrigin);\n * console.log(imm.actionCode, imm.completionStatus);\n * }\n * ```\n */\n public immunizations(): readonly Immunization[] {\n return walkImmunizations(this);\n }\n\n /**\n * Every NK1 as a NextOfKin entry in document order. D-05: returns `[]`\n * when no NK1 present.\n *\n * @example\n * ```ts\n * for (const nk of msg.nextOfKin()) {\n * console.log(nk.name?.familyName, nk.relationship?.text);\n * }\n * ```\n */\n public nextOfKin(): readonly NextOfKin[] {\n return walkNextOfKin(this);\n }\n\n /**\n * Every AL1 as an Allergy in document order. D-05: returns `[]` when no\n * AL1 present.\n *\n * @example\n * ```ts\n * for (const al of msg.allergies()) console.log(al.code?.text, al.severity);\n * ```\n */\n public allergies(): readonly Allergy[] {\n return walkAllergies(this);\n }\n\n /**\n * Every DG1 as a Diagnosis in document order. D-05: returns `[]` when no\n * DG1 present.\n *\n * @example\n * ```ts\n * for (const dg of msg.diagnoses()) console.log(dg.code?.identifier);\n * ```\n */\n public diagnoses(): readonly Diagnosis[] {\n return walkDiagnoses(this);\n }\n\n /**\n * Every IN1 as an Insurance entry with positional IN2/IN3 presence flags.\n * D-05: returns `[]` when no IN1 present.\n *\n * @example\n * ```ts\n * for (const ins of msg.insurance()) console.log(ins.planId?.text);\n * ```\n */\n public insurance(): readonly Insurance[] {\n return walkInsurance(this);\n }\n\n /**\n * Every SCH of an SIU message as a typed `Appointment` (roadmap Phase Q), with\n * the AIS/AIG/AIL/AIP resource segments that follow it grouped positionally\n * under that SCH. Surfaces the placer/filler appointment ids, SCH-25 filler\n * status (Table 0278), SCH-11 start/end timing, and the resource groups\n * (service / general / location / personnel). D-05: returns `[]` when no SCH\n * is present. D-06: not memoized. Never throws (HELPERS-07). Not a\n * scheduling-workflow state machine — see the package known-limitations.\n *\n * @example\n * ```ts\n * for (const appt of msg.appointments()) {\n * console.log(appt.fillerAppointmentId, appt.fillerStatusCode?.identifier);\n * for (const r of appt.resources) console.log(r.kind, r.code?.identifier);\n * }\n * ```\n */\n public appointments(): readonly Appointment[] {\n return walkAppointments(this);\n }\n\n /**\n * Every TXA of an MDM message as a typed `ClinicalDocument` (roadmap Phase Q),\n * with the OBX narrative body grouped positionally under that TXA. The\n * completion status (TXA-17) and availability status (TXA-19) are surfaced as\n * **distinct** fields and never conflated — a document can be available before\n * it is authenticated, and reading a preliminary document as final is the\n * harm. D-05: returns `[]` when no TXA is present. D-06: not memoized. Never\n * throws (HELPERS-07).\n *\n * @example\n * ```ts\n * for (const doc of msg.documents()) {\n * console.log(doc.documentType, doc.completionStatus, doc.availabilityStatus);\n * for (const obx of doc.observations) console.log(obx.value); // narrative body\n * }\n * ```\n */\n public documents(): readonly ClinicalDocument[] {\n return walkDocuments(this);\n }\n\n /**\n * Every FT1 of a DFT message as a typed `Charge` (roadmap Phase Q), one per\n * FT1 in document order. Surfaces billing-critical fields (FT1-6 transaction\n * type, FT1-7 code, FT1-11/12 extended/unit amount, FT1-19 diagnosis linkage)\n * with **no billing logic and no money-as-float** — amounts are the verbatim\n * CP wire text. D-05: returns `[]` when no FT1 is present. D-06: not memoized.\n * Never throws (HELPERS-07).\n *\n * @example\n * ```ts\n * for (const charge of msg.charges()) {\n * console.log(charge.transactionType, charge.transactionCode?.identifier);\n * console.log(charge.amountExtended); // verbatim, never a number\n * }\n * ```\n */\n public charges(): readonly Charge[] {\n return walkCharges(this);\n }\n\n /**\n * Emit this message as spec-clean HL7 (SER-01). Re-walks `rawSegments`\n * on every call (D-30 no caching). Segments are joined with `\\r` per\n * D-05; MSH-1 and MSH-2 are inlined verbatim from\n * `this.encodingCharacters` per D-06; every field string passes through\n * `reescape` per D-04. `RawField.isNull === true` is preserved as the\n * HL7 literal `\"\"` (D-02). Pure — never warns, never throws (D-07).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.toString()); // spec-clean, CR-separated HL7\n * ```\n */\n public toString(): string {\n return emitMessage(this);\n }\n\n /**\n * Emit this message as a structured `SerializedMessage` JSON projection\n * (SER-03). Invoked automatically by `JSON.stringify(msg)` (D-18).\n * Re-walks `rawSegments` on every call (D-30 no caching). Mirrors the\n * raw tree one-for-one, preserves `isNull`, always includes\n * `warnings: []`, and includes `profile: { name, lineage }` only when\n * `this.profile` is truthy (D-19/D-20). Pure — never warns, never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const snap = msg.toJSON();\n * console.log(snap.segments[0]?.name); // \"MSH\"\n * console.log(JSON.stringify(msg)); // same content, auto-invokes toJSON\n * ```\n */\n public toJSON(): SerializedMessage {\n return emitJson(this);\n }\n\n /**\n * Emit this message as a human-readable multi-line string for logs and\n * debugging (SER-04). Single opinionated format (D-22 no options):\n * header line with type / controlId / timestamp / segment count, then\n * one line per segment with labeled `[N]=value` fields (D-23). Composite\n * values render as their raw HL7 string — depth stops at field level\n * (D-24). Pure — never warns, never throws (D-26).\n *\n * **Field values render as their raw HL7 string representation.**\n * Embedded delimiters in user data appear as escape sequences — e.g.\n * a patient family name containing `|` renders as `Smith\\F\\Jones`\n * (NOT `Smith|Jones`). This preserves round-trip fidelity: copy-pasting\n * prettyPrint output into `parseHL7` yields a structurally equivalent\n * message. For un-escaped human display, parse the composite first via\n * typed accessors (e.g. `msg.patient?.familyName`) — those return\n * already-decoded strings.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.prettyPrint());\n * // HL7 ADT^A01 controlId=MSG001 timestamp=2026-04-19T10:15:00Z (5 segments)\n * // MSH [3]=SENDAPP [4]=SENDFAC ...\n * // PID [1]=1 [3]=MRN123 [5]=Doe^John\n * ```\n */\n public prettyPrint(): string {\n return emitPrettyPrint(this);\n }\n\n /**\n * Set the string value at a dot-path. Mutates the underlying tree and\n * returns `this` for chaining (D-15). Auto-creates missing repetitions,\n * components, and subcomponents WITHIN an existing field, but does NOT\n * auto-create segments — callers must `addSegment` first (throws\n * `TypeError` with an actionable message otherwise).\n *\n * The value is accepted verbatim: unescaped delimiter characters are NOT\n * rejected on input (D-18). Re-escaping on serialize is Phase 5's concern.\n *\n * MSH-1 / MSH-2 follow the user-facing HL7 convention — `setField(\"MSH.3\", ...)`\n * targets MSH-3 (sending application), matching `msg.get(\"MSH.3\")`.\n *\n * Segment/Field wrapper caches are invalidated wholesale on success (D-17).\n * The frozen `warnings` array is never touched (D-16).\n *\n * @example\n * ```ts\n * msg.setField(\"PID.8\", \"F\"); // patient sex → F\n * msg.setField(\"PID.5.1\", \"Jones\"); // family name\n * msg.setField(\"PID.4[2].1\", \"MRN2\"); // create third repetition of PID-4\n * ```\n */\n public setField(path: string, value: string): this {\n // D-18: parsePath throws TypeError on malformed path.\n const parsed = parsePath(path);\n\n // Find the target segment by type + 0-indexed occurrence.\n let seen = 0;\n let segIdx = -1;\n for (let i = 0; i < this.rawSegments.length; i++) {\n const s = this.rawSegments[i];\n if (s === undefined) continue;\n if (s.name === parsed.segmentType) {\n if (seen === parsed.segmentIndex) {\n segIdx = i;\n break;\n }\n seen++;\n }\n }\n if (segIdx === -1) {\n throw new TypeError(\n `setField: segment \"${parsed.segmentType}\" (occurrence ${String(parsed.segmentIndex)}) not found. ` +\n `Add it first with addSegment(\"${parsed.segmentType}\", [...]).`,\n );\n }\n\n // MSH offset: HL7 MSH-3 lives at fields[2], MSH-12 at fields[11]. Non-MSH\n // segments keep straight 1-indexed access (fields[0] = name placeholder).\n const rawFieldIndex = parsed.segmentType === \"MSH\" ? parsed.fieldIndex - 1 : parsed.fieldIndex;\n\n // Rebuild the affected path from leaf to root, keeping every Raw* shape\n // structurally immutable. The only readonly bypass is reassigning the\n // `rawSegments` reference on `this` — per D-16, the tree is mutable\n // through the mutation API.\n const mutSegments = toMutableArray(this.rawSegments);\n const seg = mutSegments[segIdx];\n // Exhaustive guard — the index was just located above.\n if (seg === undefined) {\n throw new Error(\"setField: internal invariant — segment disappeared after lookup.\");\n }\n\n const mutFields = toMutableArray(seg.fields);\n while (mutFields.length <= rawFieldIndex) {\n mutFields.push({ repetitions: [], isNull: false });\n }\n const field = mutFields[rawFieldIndex];\n if (field === undefined) {\n throw new Error(\"setField: internal invariant — field missing after growth.\");\n }\n\n const mutReps = toMutableArray(field.repetitions);\n const repIdx = parsed.repetitionIndex ?? 0;\n while (mutReps.length <= repIdx) {\n mutReps.push({ components: [] });\n }\n const rep = mutReps[repIdx];\n if (rep === undefined) {\n throw new Error(\"setField: internal invariant — repetition missing after growth.\");\n }\n\n const mutComps = toMutableArray(rep.components);\n const compIdx = (parsed.componentIndex ?? 1) - 1;\n while (mutComps.length <= compIdx) {\n mutComps.push({ subcomponents: [] });\n }\n const comp = mutComps[compIdx];\n if (comp === undefined) {\n throw new Error(\"setField: internal invariant — component missing after growth.\");\n }\n\n const mutSubs = toMutableArray(comp.subcomponents);\n const subIdx = (parsed.subcomponentIndex ?? 1) - 1;\n while (mutSubs.length <= subIdx) {\n mutSubs.push(\"\");\n }\n mutSubs[subIdx] = value;\n\n const newComp: RawComponent = { subcomponents: mutSubs };\n mutComps[compIdx] = newComp;\n const newRep: RawRepetition = { components: mutComps };\n mutReps[repIdx] = newRep;\n const newField: RawField = { repetitions: mutReps, isNull: field.isNull };\n mutFields[rawFieldIndex] = newField;\n const newSeg: RawSegment = { name: seg.name, fields: mutFields };\n mutSegments[segIdx] = newSeg;\n\n // One readonly bypass — reassign the rawSegments reference. Consumers are\n // warned by D-16 that the tree is mutable via the mutation API.\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = mutSegments;\n\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Append a new segment to the end of the message. `name` must match\n * `/^(?:[A-Z]{3}|Z[A-Z0-9]{2})$/u` — throws `TypeError` otherwise (D-19).\n *\n * `fields` is interpreted in HL7 1-indexed terms: `addSegment(\"NTE\", [a, b, c])`\n * produces a segment whose `NTE-1 = a`, `NTE-2 = b`, `NTE-3 = c`. The\n * internal `RawSegment.fields[0]` name/separator placeholder is synthesized\n * by this method.\n *\n * Each entry may be a plain string (treated as a single-subcomponent\n * single-component single-repetition field) or a full `RawField` object\n * for advanced callers who need structured content.\n *\n * Invalidates caches on return; warnings untouched (D-16).\n *\n * @example\n * ```ts\n * msg.addSegment(\"NTE\", [\"\", \"note text\"]);\n * msg.get(\"NTE.2\"); // \"note text\"\n * ```\n */\n public addSegment(name: string, fields: readonly (string | RawField)[]): this {\n if (!SEGMENT_NAME_RE.test(name)) {\n throw new TypeError(\n `addSegment: invalid segment name \"${name}\". ` +\n `Expected 3 chars matching [A-Z][A-Z0-9]{2} (e.g. \"PID\", \"PV1\", \"OBX\", \"ZPI\").`,\n );\n }\n\n // fields[0] is the name-placeholder slot; user-supplied fields start at\n // position 1. An empty string becomes an empty field (no repetitions),\n // matching the natural HL7 \"empty field between pipes\" semantics.\n const rawFields: RawField[] = [{ repetitions: [], isNull: false }];\n for (const f of fields) {\n if (typeof f === \"string\") {\n if (f === \"\") {\n rawFields.push({ repetitions: [], isNull: false });\n } else {\n rawFields.push({\n repetitions: [{ components: [{ subcomponents: [f] }] }],\n isNull: false,\n });\n }\n } else {\n rawFields.push(f);\n }\n }\n\n const newSegment: RawSegment = { name, fields: rawFields };\n const mut = toMutableArray(this.rawSegments);\n mut.push(newSegment);\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = mut;\n\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Remove segments by type + occurrence or by type + all. Call shapes:\n *\n * - `removeSegment(\"NTE\")` — remove the FIRST NTE (occurrence 0).\n * - `removeSegment(\"OBX\", 1)` — remove the SECOND OBX (0-indexed per D-01).\n * - `removeSegment(\"OBX\", { all: true })` — remove ALL OBX segments.\n *\n * `MSH` is protected — `removeSegment(\"MSH\")` throws `TypeError` (every\n * HL7 message must retain its MSH segment). Unknown segment types are a\n * no-op (idempotent; no throw). Segment name must match the D-19 shape\n * regex — invalid shapes throw `TypeError` for symmetry with `addSegment`.\n *\n * Invalidates caches on return; warnings untouched (D-16).\n *\n * @example\n * ```ts\n * msg.removeSegment(\"NTE\"); // remove first NTE\n * msg.removeSegment(\"OBX\", 1); // remove second OBX\n * msg.removeSegment(\"OBX\", { all: true }); // remove all remaining OBX\n * ```\n */\n public removeSegment(\n segmentType: string,\n occurrenceOrOptions?: number | { readonly all?: boolean },\n ): this {\n if (!SEGMENT_NAME_RE.test(segmentType)) {\n throw new TypeError(\n `removeSegment: invalid segment name \"${segmentType}\". ` +\n `Expected 3 chars matching [A-Z][A-Z0-9]{2} (e.g. \"PID\", \"PV1\", \"OBX\", \"ZPI\").`,\n );\n }\n if (segmentType === \"MSH\") {\n throw new TypeError(\n `removeSegment: refusing to remove MSH (every HL7 message must have exactly one MSH segment).`,\n );\n }\n\n const all = typeof occurrenceOrOptions === \"object\" && occurrenceOrOptions.all === true;\n const targetOccurrence = typeof occurrenceOrOptions === \"number\" ? occurrenceOrOptions : 0;\n\n const mut = toMutableArray(this.rawSegments);\n if (all) {\n const filtered = mut.filter((s) => s.name !== segmentType);\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = filtered;\n } else {\n let seen = 0;\n let removeAt = -1;\n for (let i = 0; i < mut.length; i++) {\n const s = mut[i];\n if (s === undefined) continue;\n if (s.name === segmentType) {\n if (seen === targetOccurrence) {\n removeAt = i;\n break;\n }\n seen++;\n }\n }\n if (removeAt !== -1) {\n mut.splice(removeAt, 1);\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = mut;\n }\n // else: no-op — unknown segment type or occurrence out of range.\n }\n\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Drop every wrapper AND helper cache wholesale (Phase 3 D-17 + Phase 4\n * D-02). Called by every mutation method so subsequent `segments(type)` /\n * `allSegments()` / `meta` / `patient` / `visit` reads rebuild from the\n * mutated `rawSegments` tree.\n * @internal\n */\n private invalidateCaches(): void {\n this._segmentsByType = undefined;\n this._allSegments = undefined;\n this._meta = undefined;\n this._structure = undefined;\n this._patient = undefined;\n this._visit = undefined;\n }\n}\n","/**\n * Process-scoped default profile management (PROF-08 / D-18). This module\n * holds the first mutable module-scoped state in the codebase — an\n * intentional trade-off documented in PROJECT.md Key Decisions:\n * `setDefaultProfile` EXISTS but is DISCOURAGED. It is scoped to the\n * current Node process, NOT shared across workers, NOT a symbol-keyed\n * globalThis registry, and NOT reset between test files automatically.\n *\n * Tests that touch the default profile MUST clean up in `afterEach` /\n * `afterAll` (`setDefaultProfile(null)`) to prevent cross-test bleed.\n *\n * Zero runtime deps. Single `let` variable; no class, no registry object,\n * no magic.\n */\n\nimport type { Profile } from \"../parser/types.js\";\n\n/**\n * Process-scoped default profile. `undefined` means \"unset\" (the initial\n * state). `null` is not a stable stored value — `setDefaultProfile(null)`\n * resets this to `undefined` per D-18.\n * @internal\n */\nlet _defaultProfile: Profile | undefined = undefined;\n\n/**\n * Register a process-scoped default profile. `parseHL7(raw)` (with no\n * explicit profile arg) consults `getDefaultProfile()` and applies the\n * returned profile if any. Pass `null` (or `undefined`) to clear.\n *\n * Effects are IDENTICAL to passing the profile explicitly as the second\n * arg of `parseHL7` (D-20): customSegments, dateFormats, onWarning chain,\n * and profile attribution all apply the same way.\n *\n * Explicit args ALWAYS win — `parseHL7(raw, myProfile)` uses `myProfile`\n * regardless of the default; `parseHL7(raw, { profile: null })` opts out\n * of the default for a single call without changing the registered\n * default.\n *\n * **Test hygiene:** This is the ONLY mutable module-scoped state in the\n * library. Tests that call `setDefaultProfile` MUST clean up in\n * `afterEach` (`setDefaultProfile(null)`) or default-profile bleed will\n * infect subsequent tests.\n *\n * @example\n * ```ts\n * import { setDefaultProfile, profiles, parseHL7 } from \"@cosyte/hl7\";\n *\n * // Set once at app startup\n * setDefaultProfile(profiles.epic);\n *\n * // Every parseHL7 call in the app now uses profiles.epic unless\n * // another profile is passed explicitly.\n * const msg = parseHL7(raw);\n * console.log(msg.profile?.name); // \"epic\"\n *\n * // Clear when done (or in test teardown):\n * setDefaultProfile(null);\n * ```\n */\nexport function setDefaultProfile(profile: Profile | null): void {\n // Accept `undefined` defensively — TypeScript narrows to `Profile | null`,\n // but a JS caller may pass `undefined`. Treat it like null (clear).\n _defaultProfile = profile ?? undefined;\n}\n\n/**\n * Return the current default profile, or `undefined` if none is\n * registered. Consistent with `msg.profile` convention — `undefined`\n * rather than `null`.\n *\n * @example\n * ```ts\n * import { getDefaultProfile } from \"@cosyte/hl7\";\n * const p = getDefaultProfile();\n * if (p !== undefined) console.log(\"default profile:\", p.name);\n * ```\n */\nexport function getDefaultProfile(): Profile | undefined {\n return _defaultProfile;\n}\n","/**\n * Public entry point for the `@cosyte/hl7` parser — composes every\n * parser stage built across Plans 01–05 (normalize, strip MLLP, split\n * segments, read delimiters, tokenize) and routes every Tier-2 warning\n * through a single `emitWarning` chokepoint. The four Tier-3 fatal codes\n * (`EMPTY_INPUT`, `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`,\n * `INVALID_ENCODING_CHARACTERS`) are thrown even in lenient mode; every\n * other recoverable deviation is a warning unless `{ strict: true }` is\n * passed.\n *\n * Pipeline order (locked by CONTEXT.md D-03): Buffer decode → EMPTY_INPUT\n * check → BOM strip → MLLP strip → re-check EMPTY_INPUT → line-ending\n * normalize → emitter build → MLLP warning → segment split → delimiter\n * discovery → tokenize → version extract → Hl7Message construct.\n */\n\nimport type { Buffer } from \"node:buffer\";\n\nimport { DEFAULT_ENCODING_CHARACTERS, readDelimiters } from \"./delimiters.js\";\nimport { FATAL_CODES, Hl7ParseError } from \"./errors.js\";\nimport { KNOWN_SEGMENTS } from \"./known-segments.js\";\nimport { emitIfFramed, stripMllp } from \"./mllp.js\";\nimport { canonicalCharset } from \"./charset.js\";\nimport { normalize, normalizeBuffer } from \"./normalize.js\";\nimport { snippet as segmentSnippet, splitSegments } from \"./segments.js\";\nimport { tokenize } from \"./tokenize.js\";\nimport { analyzeMessageStructure } from \"./message-structure.js\";\nimport { encodingMismatch, missingExpectedGroup, unknownSegment } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type {\n CustomSegmentDefinition,\n Hl7Position,\n ParseOptions,\n Profile,\n RawSegment,\n} from \"./types.js\";\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { getDefaultProfile } from \"../profiles/default.js\";\n\n/**\n * The list of `ParseOptions` keys that are TRULY options-only — i.e. keys\n * that appear on `ParseOptions` but NOT on `Profile`. Used by\n * `discriminateOptionsOrProfile` to decide whether an anonymous second\n * argument is a `ParseOptions` (has at least one of these keys) or a\n * `Profile` (no options-only key, has a string `name`).\n *\n * Deliberately EXCLUDES `onWarning` and `dateFormats` even though they're\n * valid `ParseOptions` keys — those two also appear on `Profile` (Profile\n * carries `onWarning`/`dateFormats` fields), so checking for them would\n * mis-classify a `defineProfile()` output (which always has `dateFormats`,\n * even as `[]`) as a `ParseOptions` when a caller passes it as the second\n * arg. The subset below is the precise \"disambiguates options from\n * profile\" witness set — every key here is options-only.\n *\n * @internal\n */\nconst OPTIONS_ONLY_KEYS: readonly (keyof ParseOptions)[] = [\n \"strict\",\n \"stripMllpFraming\",\n \"trimFields\",\n \"profile\",\n \"charset\",\n];\n\n/**\n * Discriminate the optional second argument of `parseHL7` per CONTEXT.md\n * D-06. `undefined` → empty options. A bare `Profile` (object with\n * `name: string` and none of the options-only keys) → wrapped into\n * `{ profile }`. Anything else with an options-only key wins the\n * `ParseOptions` branch (even when it also has a `name` field) so callers\n * who pass `{ name: \"epic\", strict: true }` get options semantics.\n *\n * Uses `Object.prototype.hasOwnProperty.call` rather than the `in`\n * operator so a prototype-polluted object cannot trip the options-only\n * branch by inheriting a `strict` / `onWarning` key (T-02-06-01).\n *\n * @internal\n */\nfunction discriminateOptionsOrProfile(arg: ParseOptions | Profile | undefined): ParseOptions {\n if (arg === undefined) return {};\n // A Profile is REQUIRED to have `name: string` (parser/types.ts locked\n // interface). Any arg without a string `name` is therefore unambiguously\n // ParseOptions — including bare option bags like `{ onWarning }` or\n // `{ dateFormats }` whose keys overlap with Profile but whose shape\n // lacks the required `name` witness.\n const hasStringName = typeof (arg as { name?: unknown }).name === \"string\";\n if (!hasStringName) {\n return arg;\n }\n // Arg has a string `name`. Check for TRULY options-only keys (keys that\n // cannot appear on a Profile) to decide whether the caller intended\n // options with a rogue `name` field (e.g. `{ name: \"x\", strict: true }`)\n // vs a real Profile. Uses hasOwnProperty.call against prototype\n // pollution per T-02-06-01.\n const hasOptionsOnlyKey = OPTIONS_ONLY_KEYS.some((k) =>\n Object.prototype.hasOwnProperty.call(arg, k),\n );\n if (hasOptionsOnlyKey) {\n return arg;\n }\n return { profile: arg as Profile };\n}\n\n/**\n * Build the single `emit` chokepoint passed into every parser stage per\n * CONTEXT.md D-11. Lenient mode: push the warning to the accumulator\n * array, invoke `effectiveProfile?.onWarning` FIRST (D-22) inside its own\n * try/catch so handler throws are swallowed silently, THEN invoke\n * `options.onWarning` inside its own try/catch (consistency with the\n * profile chain so a noisy caller handler cannot break the parser).\n * Strict mode: throw an `Hl7ParseError` whose `code` carries the warning\n * code; neither onWarning handler fires (preserves the existing\n * lenient-vs-strict split from Phase 2).\n *\n * D-22 ordering: profile handlers are observers that run FIRST; caller\n * handler runs LAST. Preserves the \"profile behavior, then caller\n * behavior\" layering pattern — the profile sees warnings as they arise;\n * the caller's handler sees post-profile-handler warnings (same object,\n * same time, just guaranteed ordering).\n *\n * @remarks\n * Under strict mode the thrown error's `code` is a `WarningCode` string\n * which is NOT in `FATAL_CODES`. This intentionally widens the runtime\n * set of values `Hl7ParseError.code` can take without widening the\n * compile-time type — consumers narrow on `err.code` after catching.\n * See the `as unknown as` comment in the implementation for the\n * justification (Plan 06 decision (b)).\n *\n * @internal\n */\nfunction makeEmitter(\n warnings: Hl7ParseWarning[],\n options: ParseOptions,\n input: string,\n effectiveProfile: Profile | undefined,\n): (w: Hl7ParseWarning) => void {\n return (w) => {\n if (options.strict === true) {\n // Justification for `as unknown as FatalCode`: strict mode escalates\n // Tier-2 warnings into thrown `Hl7ParseError`s per TOL-01. The thrown\n // error reuses the existing error shape (code / message / position /\n // snippet) so consumers have one catch surface. The `code` field is\n // typed as `FatalCode` (the 4 Tier-3 codes) at compile time, but at\n // runtime under strict mode it also carries any `WarningCode`. We\n // preserve the narrow compile-time type so lenient-mode callers get\n // exhaustive-switch checks on `FatalCode`; strict-mode consumers\n // narrow on the runtime string. Alternative (a) — widening\n // FatalCode — would leak strict-mode semantics into the lenient-mode\n // type surface; alternative (c) — a separate Hl7StrictError class —\n // would introduce a third error class. (b) is the minimum-surface\n // change and matches Plan 06's recommendation.\n throw new Hl7ParseError(\n w.code as unknown as (typeof FATAL_CODES)[keyof typeof FATAL_CODES],\n w.message,\n w.position,\n buildSnippet(input, w.position),\n );\n }\n warnings.push(w);\n // D-22: profile.onWarning fires BEFORE options.onWarning. Each call is\n // wrapped in its own try/catch so a throw in one handler cannot prevent\n // the other from receiving the warning, and cannot bubble out of the\n // parser (consistent with the D-12 silent-swallow contract for the\n // profile-chain composer). Symmetric treatment of options.onWarning\n // keeps the contract uniform — a noisy caller handler is as contained\n // as a noisy profile handler.\n if (effectiveProfile?.onWarning !== undefined) {\n try {\n effectiveProfile.onWarning(w);\n } catch {\n /* D-22 silent swallow */\n }\n }\n if (options.onWarning !== undefined) {\n try {\n options.onWarning(w);\n } catch {\n /* D-22 symmetric silent swallow */\n }\n }\n };\n}\n\n/**\n * Build a bounded snippet of the input for attaching to a strict-mode\n * `Hl7ParseError`. Phase 2 does not track character offsets — positions\n * are segment/field/component indices — so we return a leading excerpt\n * of the input bounded by `segments.snippet`.\n *\n * @internal\n */\nfunction buildSnippet(input: string, _position: Hl7Position): string {\n return segmentSnippet(input.slice(0, 80));\n}\n\n/**\n * Shallow MSH-18 extractor for the tentative-decode first pass of Buffer\n * charset resolution. Deliberately avoids calling `readDelimiters` or\n * `tokenize` — those can throw on malformed MSH, which would defeat the\n * \"tentative\" contract of the first pass.\n *\n * Line-ending agnostic: splits on `/[\\r\\n]/` so a Buffer that uses Unix\n * (`\\n`), classic Mac (`\\r`), or mixed line endings still isolates segment\n * 0 correctly. A bare split on `\\r` alone here would silently regress\n * PARSE-09 on `\\n`-only Buffer traffic (the whole message would become\n * segment 0, `parts[17]` would swallow subsequent segments, and the\n * charset token would become a garbage string that falls through to\n * UTF-8).\n *\n * MSH-18 is a **repeating** field (HL7 v2 Ch. 2): the **first** occurrence is\n * the message's default encoding; later occurrences are alternates activated\n * mid-message by the charset-switch escapes. Only the first repetition governs\n * the whole-buffer decode, so this returns it — split on the message's own\n * repetition separator (MSH-2 char 2, default `~`).\n *\n * Returns the trimmed first MSH-18 repetition, or `undefined` on any failure\n * (no segment boundary, segment not `MSH`, `parts[17]` missing or empty). The\n * caller applies the ASCII default on `undefined`.\n *\n * @internal\n */\nfunction extractMsh18FromTentativeDecode(tentativeText: string): string | undefined {\n const firstSegment = tentativeText.split(/[\\r\\n]/)[0];\n if (firstSegment === undefined) return undefined;\n if (!firstSegment.startsWith(\"MSH\")) return undefined;\n // HL7 field-separator character is at index 3 of the MSH segment (after\n // the three-letter segment name).\n const fieldSep = firstSegment.charAt(3);\n if (fieldSep === \"\") return undefined;\n const parts = firstSegment.split(fieldSep);\n // Per the unified 1-indexed convention: parts[0] = \"MSH\", parts[1] =\n // encoding characters (MSH-2 = `^~\\&`), ..., parts[17] = MSH-18.\n const raw = parts[17];\n if (raw === undefined) return undefined;\n // Repetition separator = MSH-2 character 2 (0-indexed 1); default `~` when\n // MSH-2 is short/malformed. Take the first repetition = the message default.\n const repSep = (parts[1] ?? \"\").charAt(1) || \"~\";\n const firstRep = raw.split(repSep)[0] ?? raw;\n const trimmed = firstRep.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Resolve the effective charset for a `Buffer` input and return the\n * decoded, line-ending-normalized text. Implements the locked precedence\n * rule (design decision (c)):\n *\n * 1. If `options.charset` is supplied AND MSH-18 is declared, emit\n * `ENCODING_MISMATCH` when they disagree after canonicalization;\n * always honour the override.\n * 2. Else if `options.charset` is supplied, use it.\n * 3. Else if MSH-18 is declared, use it (a recognized-but-undecoded set\n * trips `UNSUPPORTED_CHARSET`, an unrecognized label `UNKNOWN_CHARSET`,\n * both preserving bytes verbatim inside `normalizeBuffer`).\n * 4. Else fall through to `normalizeBuffer`'s ASCII default (decoded as its\n * UTF-8 superset), which emits nothing.\n *\n * Two-pass mechanics: MSH-1 through MSH-18 are always 7-bit ASCII in real\n * HL7 traffic, so a tentative UTF-8 decode reliably surfaces MSH-18 even\n * when the payload declares a non-UTF-8 charset. The second pass\n * (`normalizeBuffer`) re-decodes with the resolved charset.\n *\n * @internal\n */\nfunction resolveBufferCharset(\n raw: Buffer,\n options: ParseOptions,\n emit: (w: Hl7ParseWarning) => void,\n): string {\n const override = options.charset;\n // Pass 1: tentative UTF-8 decode to read MSH-18. This is cheap — for\n // UTF-8 payloads the tentative decode is exactly what `normalizeBuffer`\n // would produce anyway; for non-UTF-8 payloads the MSH header bytes are\n // ASCII so MSH-18 still surfaces correctly even if the body garbles.\n const tentative = new TextDecoder(\"utf-8\").decode(raw);\n const declared = extractMsh18FromTentativeDecode(tentative);\n\n if (override !== undefined && declared !== undefined) {\n const overrideNorm = canonicalCharset(override);\n const declaredNorm = canonicalCharset(declared);\n if (overrideNorm !== declaredNorm) {\n emit(\n encodingMismatch(\n { segmentIndex: 0 },\n `options.charset=\"${override}\" disagrees with MSH-18=\"${declared}\"`,\n ),\n );\n }\n return normalizeBuffer(raw, override, emit);\n }\n if (override !== undefined) {\n return normalizeBuffer(raw, override, emit);\n }\n if (declared !== undefined) {\n return normalizeBuffer(raw, declared, emit);\n }\n return normalizeBuffer(raw, undefined, emit);\n}\n\n/**\n * Read MSH-12 (version) from the first tokenized segment. Per the unified\n * HL7 1-indexed convention locked in Plan 03, `fields[0]` is the\n * separator/name placeholder, `fields[1]` is MSH-2 (encoding chars),\n * `fields[11]` is MSH-12 (version). Returns the empty string when the\n * first segment is absent, not an MSH, or MSH-12 has no content — the\n * `noUncheckedIndexedAccess` strictness flag forces every intermediate\n * index guard to be explicit.\n *\n * @internal\n */\nfunction extractVersion(msh: RawSegment | undefined): string {\n if (msh === undefined || msh.name !== \"MSH\") return \"\";\n const versionField = msh.fields[11];\n if (versionField === undefined) return \"\";\n const firstRep = versionField.repetitions[0];\n if (firstRep === undefined) return \"\";\n const firstComp = firstRep.components[0];\n if (firstComp === undefined) return \"\";\n const firstSub = firstComp.subcomponents[0];\n return firstSub ?? \"\";\n}\n\n/**\n * Read MSH-9.1 (message code) and MSH-9.2 (trigger event) from the first\n * tokenized segment for the Phase G structure safety net. MSH-9 is\n * `fields[8]` under the unified 1-indexed convention (`fields[0]` is the\n * name/separator placeholder). Returns empty strings when the first segment is\n * absent, not an MSH, or the components have no content — every intermediate\n * index guard is explicit under `noUncheckedIndexedAccess`.\n *\n * @internal\n */\nfunction extractMessageType(msh: RawSegment | undefined): {\n readonly messageCode: string;\n readonly triggerEvent: string;\n} {\n if (msh === undefined || msh.name !== \"MSH\") return { messageCode: \"\", triggerEvent: \"\" };\n const typeField = msh.fields[8];\n if (typeField === undefined) return { messageCode: \"\", triggerEvent: \"\" };\n const firstRep = typeField.repetitions[0];\n if (firstRep === undefined) return { messageCode: \"\", triggerEvent: \"\" };\n const messageCode = firstRep.components[0]?.subcomponents[0] ?? \"\";\n const triggerEvent = firstRep.components[1]?.subcomponents[0] ?? \"\";\n return { messageCode, triggerEvent };\n}\n\n/**\n * Parse a raw HL7 v2 message (string or `Buffer`) into an `Hl7Message`.\n * The parser is lenient by default: recoverable deviations from the HL7\n * spec are reported via `msg.warnings` and (optionally)\n * `options.onWarning` but do not throw. Four unrecoverable structural\n * errors throw `Hl7ParseError`: `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`,\n * `INVALID_ENCODING_CHARACTERS`, `EMPTY_INPUT`. Opt into strict mode\n * with `{ strict: true }` to escalate every Tier-2 warning into an\n * `Hl7ParseError`.\n *\n * @example\n * ```ts\n * import { parseHL7, WARNING_CODES } from \"@cosyte/hl7\";\n *\n * const msg = parseHL7(\n * \"MSH|^~\\\\&|APP|FAC|APP|FAC|20250101||ADT^A01|1|P|2.5\\rPID|||123\",\n * );\n * console.log(msg.version); // \"2.5\"\n * console.log(msg.warnings.length); // 0\n * for (const w of msg.warnings) {\n * if (w.code === WARNING_CODES.MLLP_FRAMING_STRIPPED) {\n * // handle MLLP-framed sender\n * }\n * }\n * ```\n */\nexport function parseHL7(raw: string | Buffer): Hl7Message;\nexport function parseHL7(raw: string | Buffer, profile: Profile): Hl7Message;\nexport function parseHL7(raw: string | Buffer, options: ParseOptions): Hl7Message;\n/** @internal — implementation signature; overload signatures above carry the public JSDoc + @example. */\nexport function parseHL7(\n raw: string | Buffer,\n optionsOrProfile?: ParseOptions | Profile,\n): Hl7Message {\n const options = discriminateOptionsOrProfile(optionsOrProfile);\n const warnings: Hl7ParseWarning[] = [];\n\n // Step 1: Buffer → string decode (if needed). UNKNOWN_CHARSET warnings\n // captured here are forwarded through the real emitter after the\n // fatal checks pass.\n const bufferWarnings: Hl7ParseWarning[] = [];\n const bufferEmit = (w: Hl7ParseWarning): void => {\n bufferWarnings.push(w);\n };\n let text: string;\n if (typeof raw === \"string\") {\n text = raw;\n } else {\n text = resolveBufferCharset(raw, options, bufferEmit);\n }\n\n // Step 2: EMPTY_INPUT fatal check at the top of the pipeline (D-03).\n if (text.length === 0) {\n throw new Hl7ParseError(FATAL_CODES.EMPTY_INPUT, \"Input is empty.\", { segmentIndex: 0 }, \"\");\n }\n\n // Step 3: Strip UTF-8 BOM silently (Tier-1; no warning).\n if (text.charCodeAt(0) === 0xfeff) {\n text = text.slice(1);\n }\n\n // Step 4: Strip MLLP framing bytes. Even if `stripMllpFraming` is\n // disabled we still strip — leaving VT/FS in the buffer would corrupt\n // segment splitting — but we suppress the warning in that case.\n const mllpResult = stripMllp(text);\n text = mllpResult.stripped;\n\n // Step 5: Re-check EMPTY_INPUT — MLLP strip may have emptied the payload.\n if (text.length === 0) {\n throw new Hl7ParseError(\n FATAL_CODES.EMPTY_INPUT,\n \"Input is empty after MLLP framing was stripped.\",\n { segmentIndex: 0 },\n \"\",\n );\n }\n\n // Step 6: Normalize line endings to `\\r` (Tier-1 silent).\n const inputForPipeline = normalize(text);\n\n // Step 6.5 (Plan 04 extends): Resolve effectiveProfile BEFORE makeEmitter\n // so the D-22 onWarning chain is wired from the VERY FIRST emission\n // (Buffer-decode warnings in Step 7 replay included). Plan 04 extends\n // Plan 03's single-line assignment into a 3-branch discrimination per\n // D-19 \"explicit wins; null opts out; undefined falls back to default\":\n // - options.profile === null → explicit opt-out for this call (D-19).\n // Registered default is IGNORED; msg.profile === undefined.\n // - options.profile !== undefined → explicit Profile wins over any\n // registered default.\n // - options.profile === undefined → fall back to the registered default\n // via getDefaultProfile() (which may itself be undefined, in which\n // case effectiveProfile stays undefined and parseHL7 behaves exactly\n // like the no-profile case — zero semantic change for unregistered\n // consumers).\n let effectiveProfile: Profile | undefined;\n if (options.profile === null) {\n effectiveProfile = undefined;\n } else if (options.profile !== undefined) {\n effectiveProfile = options.profile;\n } else {\n effectiveProfile = getDefaultProfile();\n }\n\n // Step 7: All Tier-3 fatals are past. Build the real emitter (now\n // profile-aware per D-22) and forward any warnings captured during the\n // Buffer decode. Buffer-decode warnings route through BOTH profile and\n // options handlers — full fidelity from the first warning onwards.\n const emit = makeEmitter(warnings, options, inputForPipeline, effectiveProfile);\n for (const pre of bufferWarnings) emit(pre);\n\n // Step 8: MLLP framing warning (Tier-2) — fired AFTER the fatal checks\n // so `EMPTY_INPUT` always takes precedence over\n // `MLLP_FRAMING_STRIPPED` (D-03 ordering).\n if ((options.stripMllpFraming ?? true) === true) {\n emitIfFramed(mllpResult, emit, { segmentIndex: 0 });\n }\n\n // Step 9: Segment split.\n const segments = splitSegments(inputForPipeline);\n if (segments.length === 0) {\n // Defensive: splitSegments returning [] implies empty input, which the\n // earlier EMPTY_INPUT checks would have caught. Fall through with a\n // NO_MSH_SEGMENT fatal so the invariant \"first segment exists\" holds.\n throw new Hl7ParseError(\n FATAL_CODES.NO_MSH_SEGMENT,\n \"No segments found after normalization.\",\n { segmentIndex: 0 },\n \"\",\n );\n }\n\n // Step 10: Delimiter discovery (may throw NO_MSH_SEGMENT / MSH_TOO_SHORT\n // / INVALID_ENCODING_CHARACTERS).\n const firstSegment = segments[0] ?? \"\";\n const encoding = readDelimiters(firstSegment);\n\n // Step 11: Tokenize (may emit FIELD_WHITESPACE_TRIMMED).\n const rawSegments: readonly RawSegment[] = tokenize(\n segments,\n encoding,\n emit,\n options.trimFields ?? true,\n );\n\n // Step 11.5: Emit UNKNOWN_SEGMENT for any non-standard segment name that\n // is not declared in the active profile (D-31). Uses the already-resolved\n // effectiveProfile for customSegments suppression. O(N) — one Set.has +\n // one hasOwnProperty per segment. Uses Object.prototype.hasOwnProperty.call\n // to guard against prototype pollution (matches the T-02-06-01 mitigation\n // in discriminateOptionsOrProfile).\n const profileCustomSegments = effectiveProfile?.customSegments;\n for (let segIdx = 0; segIdx < rawSegments.length; segIdx++) {\n const rawSeg = rawSegments[segIdx];\n if (rawSeg === undefined) continue;\n const isKnown = KNOWN_SEGMENTS.has(rawSeg.name);\n const isProfileClaimed =\n profileCustomSegments !== undefined &&\n Object.prototype.hasOwnProperty.call(profileCustomSegments, rawSeg.name);\n if (!isKnown && !isProfileClaimed) {\n emit(unknownSegment({ segmentIndex: segIdx }, rawSeg.name));\n }\n }\n\n // Step 11.6 (Phase G): structural-conformance safety net. For the common\n // message types the registry recognizes, warn ADDITIVELY when an expected\n // Required segment group is entirely absent (e.g. ORU^R01 with no OBR/OBX) —\n // the signature of a truncated or misrouted feed. Warning-only (Tier-2);\n // lenient parse never throws, `strict` may promote via the emitter. The\n // warning carries only structural facts (type, group, anchor names) — never\n // a field value, so no PHI is exposed. Conservative by construction: an\n // unrecognized type yields no expected groups and emits nothing.\n const { messageCode, triggerEvent } = extractMessageType(rawSegments[0]);\n if (messageCode !== \"\") {\n const presentSegmentNames = new Set<string>();\n for (const seg of rawSegments) {\n if (seg !== undefined) presentSegmentNames.add(seg.name);\n }\n const structure = analyzeMessageStructure(messageCode, triggerEvent, presentSegmentNames);\n const messageType = triggerEvent !== \"\" ? `${messageCode}^${triggerEvent}` : messageCode;\n for (const group of structure.expectedGroups) {\n if (!group.present) {\n emit(\n missingExpectedGroup(\n { segmentIndex: 0, fieldIndex: 9 },\n messageType,\n group.name,\n group.anchorSegments,\n ),\n );\n }\n }\n }\n\n // Step 12: Version extraction — Phase 4 extends this via msg.meta.\n const version = extractVersion(rawSegments[0]);\n\n // Step 13: Profile attribution + merged customSegments / dateFormats for\n // Hl7Message init. Step 13 is a CONSUMER of the already-resolved\n // effectiveProfile (resolution moved to Step 6.5 per Plan 03 Option A).\n const profileInit =\n effectiveProfile !== undefined\n ? {\n name: effectiveProfile.name,\n lineage: effectiveProfile.lineage ?? [effectiveProfile.name],\n }\n : undefined;\n\n // D-21: options.dateFormats precede profile.dateFormats in the try-order.\n // Dedupe preserving first occurrence. `mergedDateFormats` stays undefined\n // when neither source supplied any formats so the Hl7MessageInit omission\n // discipline (exactOptionalPropertyTypes) is honoured.\n const optionFormats = options.dateFormats ?? [];\n const profileFormats = effectiveProfile?.dateFormats ?? [];\n const mergedFormats: string[] = [];\n const seenFormats = new Set<string>();\n for (const f of optionFormats) {\n if (!seenFormats.has(f)) {\n seenFormats.add(f);\n mergedFormats.push(f);\n }\n }\n for (const f of profileFormats) {\n if (!seenFormats.has(f)) {\n seenFormats.add(f);\n mergedFormats.push(f);\n }\n }\n const mergedDateFormats: readonly string[] | undefined =\n mergedFormats.length > 0 ? Object.freeze(mergedFormats) : undefined;\n\n const mergedCustomSegments = effectiveProfile?.customSegments;\n\n // exactOptionalPropertyTypes: conditionally assign each optional init key.\n type Init = {\n segments: readonly RawSegment[];\n encodingCharacters: typeof encoding;\n version: string;\n warnings: readonly Hl7ParseWarning[];\n profile?: { readonly name: string; readonly lineage: readonly string[] };\n customSegments?: Readonly<Record<string, CustomSegmentDefinition>>;\n dateFormats?: readonly string[];\n };\n const init: Init = {\n segments: rawSegments,\n encodingCharacters: encoding,\n version,\n warnings,\n };\n if (profileInit !== undefined) init.profile = profileInit;\n if (mergedCustomSegments !== undefined) init.customSegments = mergedCustomSegments;\n if (mergedDateFormats !== undefined) init.dateFormats = mergedDateFormats;\n\n return new Hl7Message(init);\n}\n\n// Re-export DEFAULT_ENCODING_CHARACTERS so consumers who need it do not\n// have to reach into `./delimiters.js`.\nexport { DEFAULT_ENCODING_CHARACTERS };\n","/**\n * `HL7` namespace — type-only re-exports of the 10 composite interfaces\n * (XPN, XAD, CX, CWE, CE, XTN, PL, TS, NM, HD). Consumed via\n * `export * as HL7 from \"./model/types/namespace.js\";` in the top-level barrel\n * (`src/index.ts`). Named exports of the same interfaces live in the public\n * barrel alongside this namespace for developers who prefer the direct\n * `import type { XPN } ...` style (D-13).\n *\n * The namespace is TYPES-ONLY — parser functions (`parseXpn`, `parseXad`, ...)\n * are exported as value exports from the main barrel, not under `HL7`.\n */\n\nexport type { XPN } from \"./xpn.js\";\nexport type { XAD } from \"./xad.js\";\nexport type { CX } from \"./cx.js\";\nexport type { CWE } from \"./cwe.js\";\nexport type { CE } from \"./ce.js\";\nexport type { XTN } from \"./xtn.js\";\nexport type { PL } from \"./pl.js\";\nexport type { TS } from \"./ts.js\";\nexport type { NM } from \"./nm.js\";\nexport type { SN } from \"./sn.js\";\nexport type { HD } from \"./hd.js\";\nexport type { XCN } from \"./xcn.js\";\n","/**\n * `generateControlId` — synthesise an HL7 message control ID for outbound\n * messages. Shape: 17-char UTC timestamp `YYYYMMDDHHmmssSSS` + 6 random\n * alphanumeric chars = 23 chars total (D-12).\n *\n * Implementation lives in Phase 5 Plan 05 (build-message).\n *\n * Decisions:\n * - D-12: exact shape above; uniqueness via `Date.now()` + cryptographic\n * random bytes from `node:crypto.randomBytes` (WR-03 hardening — was\n * `Math.random` originally); alphabet is plain `[A-Za-z0-9]` (Claude's\n * Discretion: readability doesn't matter — IDs aren't human-typed).\n * - D-31: zero deps — Node stdlib only (`node:crypto` is stdlib).\n *\n * @internal\n */\n\nimport { randomBytes } from \"node:crypto\";\n\n/**\n * Alphabet for the random suffix — plain alphanumeric. Readability doesn't\n * matter (IDs aren't human-typed), so no ambiguous-char filtering.\n * @internal\n */\nconst ALNUM_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Zero-pad a number to N digits (stdlib — avoid regex for perf).\n * @internal\n */\nfunction pad(n: number, width: number): string {\n return String(n).padStart(width, \"0\");\n}\n\n/**\n * Generate an HL7 message control ID per D-12. Shape: 17-char UTC timestamp\n * `YYYYMMDDHHmmssSSS` + 6 random alphanumeric chars = 23 chars total.\n *\n * The 6-char suffix is sourced from `node:crypto.randomBytes(6)` and mapped\n * into the 62-char alnum alphabet. This avoids the `Math.random` collision\n * risk flagged in WR-03 under heavy concurrent load (many parallel workers\n * generating IDs in the same millisecond). Note: mapping 256-bucket bytes\n * into a 62-bucket alphabet via modulo introduces a tiny distributional\n * bias (the first 20 alphabet slots are ~slightly more likely than the\n * last 42), but the bias is negligible for uniqueness — the effective\n * entropy on the suffix remains > 35 bits, and the 17-char ms timestamp\n * prefix further partitions the ID space.\n *\n * Zero dependencies — uses `Date` + `node:crypto` only (D-31); both are\n * Node stdlib.\n *\n * @internal\n */\nexport function generateControlId(): string {\n const now = new Date();\n const ts =\n pad(now.getUTCFullYear(), 4) +\n pad(now.getUTCMonth() + 1, 2) +\n pad(now.getUTCDate(), 2) +\n pad(now.getUTCHours(), 2) +\n pad(now.getUTCMinutes(), 2) +\n pad(now.getUTCSeconds(), 2) +\n pad(now.getUTCMilliseconds(), 3);\n const bytes = randomBytes(6);\n let suffix = \"\";\n for (let i = 0; i < 6; i++) {\n // noUncheckedIndexedAccess: bytes is a Buffer of known length 6, so\n // bytes[i] is a number (0..255). The `?? 0` reflects that invariant\n // without a forbidden non-null assertion — the loop bound is a literal 6\n // that matches the requested byte count, so bytes[i] is always defined.\n const byte = bytes[i] ?? 0;\n const idx = byte % ALNUM_ALPHABET.length;\n // ALNUM_ALPHABET.charAt(idx) is always a single-char string.\n suffix += ALNUM_ALPHABET.charAt(idx);\n }\n return ts + suffix;\n}\n","/**\n * `formatHl7Timestamp` — format a JS `Date` to HL7 TS `YYYYMMDDHHmmss`\n * (UTC, second precision). The outbound (builder) counterpart to the inbound\n * `src/parser/dates.ts::parseDtm`; this side intentionally emits full\n * second-precision UTC for newly-constructed messages.\n *\n * Implementation lives in Phase 5 Plan 05 (build-message).\n *\n * Decisions:\n * - D-13: second precision only (no `.SSSS`); UTC via `getUTC*` methods.\n * - D-31: zero deps — stdlib `Date` only.\n *\n * @internal\n */\n\n/**\n * Format a JS `Date` to HL7 TS `YYYYMMDDHHmmss` (UTC, second precision,\n * always 14 chars). The builder counterpart to the parser's `parseDtm`.\n * D-13: sub-second precision is NOT emitted (acceptable asymmetry — most\n * outbound use cases don't need ms, and HL7 TS `.SSSS` is optional).\n *\n * Always uses UTC — callers who need local-time emission should supply a\n * pre-formatted HL7 TS string to `buildMessage({ timestamp: \"...\" })`.\n *\n * On an Invalid Date (`new Date(\"not-a-date\")`) the output is a string of\n * 14 `NaN`-derived chars. `buildMessage`'s upstream validation never passes\n * an invalid Date — sibling functions don't throw (D-07), so this pathological\n * case is accepted silently.\n *\n * @example\n * ```ts\n * // formatHl7Timestamp is @internal — call buildMessage's `timestamp`\n * // option instead. Internally this maps Date -> YYYYMMDDHHmmss:\n * // new Date(\"2026-04-19T10:15:00Z\") -> \"20260419101500\"\n * ```\n *\n * @internal\n */\nexport function formatHl7Timestamp(date: Date): string {\n const yyyy = String(date.getUTCFullYear()).padStart(4, \"0\");\n const mm = String(date.getUTCMonth() + 1).padStart(2, \"0\"); // +1: getUTCMonth is 0-indexed\n const dd = String(date.getUTCDate()).padStart(2, \"0\");\n const hh = String(date.getUTCHours()).padStart(2, \"0\");\n const min = String(date.getUTCMinutes()).padStart(2, \"0\");\n const ss = String(date.getUTCSeconds()).padStart(2, \"0\");\n return `${yyyy}${mm}${dd}${hh}${min}${ss}`;\n}\n","/**\n * `buildMessage` — top-level outbound factory for the `@cosyte/hl7`\n * package. Synthesizes a complete MSH `RawSegment` from `BuildMessageInit`\n * and returns a real `Hl7Message` (not a builder subtype). Callers chain\n * `.addSegment(...)` (Phase 3 mutation method, unchanged) to append PID,\n * OBX, etc. Symmetric with `parseHL7` (D-09).\n *\n * The `BuildMessageInit` interface is exported in Plan 01 (this file) so\n * consumers + `src/index.ts` can reference the type immediately. The\n * `buildMessage` function body is filled in Phase 5 Plan 05 (build-message).\n *\n * Decisions:\n * - D-09: top-level named export from `src/index.ts`.\n * - D-10: `BuildMessageInit` shape below.\n * - D-11: internally synthesises a complete MSH `RawSegment` and hands to\n * `new Hl7Message({...})`.\n * - D-12: controlId auto-gen — YYYYMMDDHHmmssSSS + 6 alnum = 23 chars.\n * - D-13: `timestamp` accepts `Date | string`; `Date` formats to\n * `YYYYMMDDHHmmss` UTC.\n * - D-14: encoding chars always `DEFAULT_ENCODING_CHARACTERS`.\n * - D-15: subsequent `.addSegment(name, fields)` uses Phase 3 unchanged\n * (`readonly string[]` field input).\n * - D-16: missing/empty `type` throws `TypeError`.\n *\n * **Absent vs. explicit null at the wire level:** at the HL7 wire level,\n * an empty-string field and an omitted field produce IDENTICAL output\n * (both emit as absent — `||` in the line). If you need to distinguish\n * \"explicitly null\" (HL7 `\"\"`) from \"absent\" in an outbound message, use\n * `buildMessage({...}).setField(path, '\"\"')` after construction — the\n * Phase 3 `setField` mutation method sets `RawField.isNull = true`, which\n * the emitter preserves as the literal two-char string `\"\"` per D-02.\n */\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { RawField, RawSegment } from \"../parser/types.js\";\n\nimport { generateControlId } from \"./control-id.js\";\nimport { formatHl7Timestamp } from \"./format-timestamp.js\";\n\n/**\n * Input shape for `buildMessage` (SER-06). Mirrors `msg.meta` 1-for-1 so\n * read and write surfaces share field names (`sendingApp`, `sendingFacility`,\n * `receivingApp`, `receivingFacility`, `controlId`, `timestamp`, `version`,\n * `processingId`). `type` is the only required field.\n *\n * **Empty string vs. undefined semantics:** omitting a field and passing an\n * empty string produce IDENTICAL wire output (both emit as an absent\n * positional field). To emit an HL7 explicit null (`\"\"`) at a specific\n * position in an outbound message, build the message first and then call\n * `.setField(path, '\"\"')` — the Phase 3 mutation method sets `isNull=true`\n * on the underlying `RawField`, and the emitter preserves that as the\n * literal two-char output per D-02.\n *\n * @example\n * ```ts\n * import { buildMessage } from \"@cosyte/hl7\";\n * const msg = buildMessage({\n * type: \"ADT^A01\",\n * sendingApp: \"CLINIC\",\n * sendingFacility: \"MAIN\",\n * receivingApp: \"LAB\",\n * receivingFacility: \"REF\",\n * timestamp: new Date(\"2026-04-19T10:15:00Z\"),\n * })\n * .addSegment(\"PID\", [\"\", \"\", \"MRN123\", \"\", \"Doe^John\"]);\n * console.log(msg.toString());\n *\n * // To emit HL7 explicit null (\"\") instead of absent:\n * // msg.setField(\"PID.2\", '\"\"'); // distinct from empty/omitted\n * ```\n */\nexport interface BuildMessageInit {\n /**\n * HL7 message type, e.g. `\"ADT^A01\"` (code + trigger) or\n * `\"ORU^R01^ORU_R01\"` (code + trigger + structure). Required (D-16).\n *\n * The string is split on `^` into MSH-9 components; each component is\n * emitted verbatim. Literal `^` characters in a component are NOT\n * representable via this field — splitting is unconditional. Callers\n * needing that edge case should build the message and then use\n * `.setField(\"MSH.9.1\", ...)` etc. after construction.\n *\n * Rejected at runtime (D-16 / WR-04):\n * - empty string `\"\"` or whitespace-only `\" \"`;\n * - strings whose every `^`-split component is empty/whitespace\n * (e.g. `\"^\"`, `\"^^\"`, `\" ^ \"`).\n */\n readonly type: string;\n readonly sendingApp?: string;\n readonly sendingFacility?: string;\n readonly receivingApp?: string;\n readonly receivingFacility?: string;\n /** Auto-generated via `generateControlId()` when omitted (D-12). */\n readonly controlId?: string;\n /**\n * `Date` formatted to HL7 `YYYYMMDDHHmmss` (UTC, seconds) when supplied;\n * pre-formatted HL7 TS string passed through verbatim (D-13). Defaults to\n * `new Date()`.\n */\n readonly timestamp?: Date | string;\n /** Defaults to `\"2.5\"`. */\n readonly version?: string;\n /** Defaults to `\"P\"` (production). */\n readonly processingId?: string;\n}\n\n/**\n * Construct an outbound `Hl7Message` from semantic MSH fields (SER-06).\n * Synthesises a complete MSH `RawSegment` per D-10/D-11 and hands to\n * `new Hl7Message({...})`. Callers chain `.addSegment(name, fields)`\n * (Phase 3 mutation method, unchanged) to append PID, OBX, etc.\n *\n * Defaults applied when fields are omitted (D-10):\n * - `controlId` → `generateControlId()` (D-12)\n * - `timestamp` → `formatHl7Timestamp(new Date())` (D-13)\n * - `version` → `\"2.5\"`\n * - `processingId` → `\"P\"`\n * - `sendingApp`/`sendingFacility`/`receivingApp`/`receivingFacility` → empty\n *\n * Encoding characters are always `DEFAULT_ENCODING_CHARACTERS` (D-14); no\n * option to customise in v1.\n *\n * **Empty string vs. omitted field (W1):** at the HL7 wire level, passing\n * `sendingApp: \"\"` and omitting `sendingApp` produce IDENTICAL output\n * (both emit as absent — `||` at the MSH-3 position). If you need to\n * emit an HL7 explicit null (`\"\"`, the two-char literal) at a specific\n * position, build the message first, then use `setField`:\n *\n * ```ts\n * const msg = buildMessage({ type: \"ADT^A01\" });\n * msg.setField(\"MSH.3\", '\"\"'); // sets RawField.isNull = true\n * // msg.toString() now emits MSH-3 as `\"\"` (2 chars), not as absent.\n * ```\n *\n * The `BuildMessageInit` interface JSDoc (Plan 01) has the same note on\n * the input shape; this function-level doc reinforces it for developers\n * who land on the impl.\n *\n * @example\n * ```ts\n * import { buildMessage, parseHL7 } from \"@cosyte/hl7\";\n * const msg = buildMessage({\n * type: \"ADT^A01\",\n * sendingApp: \"CLINIC\",\n * sendingFacility: \"MAIN\",\n * receivingApp: \"LAB\",\n * receivingFacility: \"REF\",\n * }).addSegment(\"PID\", [\"\", \"\", \"MRN123\", \"\", \"Doe^John\"]);\n *\n * // Spec-clean HL7 string round-trips through parseHL7:\n * const round = parseHL7(msg.toString());\n * console.log(round.meta.type); // \"ADT^A01\"\n * ```\n */\nexport function buildMessage(init: BuildMessageInit): Hl7Message {\n // D-16 validation: type must be a non-empty, non-whitespace string.\n // `init` may be `null`/`undefined` at runtime if a JS caller bypasses the\n // type — guard defensively.\n if (\n init === null ||\n init === undefined ||\n typeof init.type !== \"string\" ||\n init.type.trim().length === 0\n ) {\n throw new TypeError(\n \"buildMessage: `type` is required and must be a non-empty string \" +\n '(e.g. \"ADT^A01\" or \"ORU^R01^ORU_R01\"). ' +\n `Received: ${JSON.stringify(init === null || init === undefined ? init : init.type)}.`,\n );\n }\n\n // WR-04: tighten D-16 — split on `^` and reject a string whose every\n // component is empty/whitespace (e.g. `\"^\"`, `\" ^ \"`, `\"^^\"`). The\n // outer `.trim().length === 0` check above catches `\"\"` and `\" \"`, but\n // passes `\"^\"` (split → `[\"\",\"\"]` → MSH-9 emits as `^` which round-trips\n // but is malformed). Reject at the factory instead of letting garbage\n // through.\n const typeParts = init.type.split(\"^\");\n if (typeParts.every((p) => p.trim().length === 0)) {\n throw new TypeError(\n \"buildMessage: `type` must contain at least one non-empty component \" +\n '(e.g. \"ADT^A01\", not \"^\" or \"^^\"). ' +\n `Received: ${JSON.stringify(init.type)}.`,\n );\n }\n\n const enc = DEFAULT_ENCODING_CHARACTERS; // D-14\n\n // Resolve timestamp per D-13.\n const tsString: string = resolveTimestamp(init.timestamp);\n\n // Resolve controlId per D-12.\n const controlId = init.controlId ?? generateControlId();\n\n // Resolve version + processingId defaults.\n const version = init.version ?? \"2.5\";\n const processingId = init.processingId ?? \"P\";\n\n // Build MSH fields[0..11] per the positional mapping documented in\n // `RawSegment.fields` JSDoc + CONTEXT.md D-11.\n //\n // fields[0] = field-separator placeholder (content: \"|\")\n // fields[1] = MSH-2 encoding chars (content: \"^~\\\\&\")\n // fields[2] = MSH-3 sendingApp\n // fields[3] = MSH-4 sendingFacility\n // fields[4] = MSH-5 receivingApp\n // fields[5] = MSH-6 receivingFacility\n // fields[6] = MSH-7 timestamp\n // fields[7] = MSH-8 (unused) empty\n // fields[8] = MSH-9 = message type (possibly composite).\n // fields[9] = MSH-10 controlId\n // fields[10] = MSH-11 processingId\n // fields[11] = MSH-12 version\n //\n // W1: `scalarField(\"\")` produces an absent RawField (zero repetitions,\n // isNull:false) — identical to omitting the field. That's the correct\n // wire semantic; callers who want explicit null use `.setField(\"MSH.N\",\n // '\"\"')` after construction.\n const mshFields: RawField[] = [\n scalarField(enc.field), // fields[0]\n scalarField(\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\"),\n ), // fields[1] MSH-2 (5th char only when truncation is set, v2.7+)\n scalarField(init.sendingApp ?? \"\"), // MSH-3\n scalarField(init.sendingFacility ?? \"\"), // MSH-4\n scalarField(init.receivingApp ?? \"\"), // MSH-5\n scalarField(init.receivingFacility ?? \"\"), // MSH-6\n scalarField(tsString), // MSH-7\n absentField(), // MSH-8\n compositeField(init.type), // MSH-9 (split on ^)\n scalarField(controlId), // MSH-10\n scalarField(processingId), // MSH-11\n scalarField(version), // MSH-12\n ];\n\n const mshSegment: RawSegment = {\n name: \"MSH\",\n fields: mshFields,\n };\n\n // D-11: construct the Hl7Message with the synthesised MSH as the sole\n // initial segment. Subsequent .addSegment() calls append PID/OBX/etc.\n return new Hl7Message({\n segments: [mshSegment],\n encodingCharacters: enc,\n version,\n warnings: [],\n });\n}\n\n/**\n * D-13: `Date` formats to HL7 `YYYYMMDDHHmmss` UTC; string passes through\n * verbatim; omitted defaults to `formatHl7Timestamp(new Date())`.\n * @internal\n */\nfunction resolveTimestamp(ts: Date | string | undefined): string {\n if (ts === undefined) return formatHl7Timestamp(new Date());\n if (typeof ts === \"string\") return ts;\n return formatHl7Timestamp(ts);\n}\n\n/**\n * Build a RawField carrying a single plain-string value (one repetition,\n * one component, one subcomponent). Empty string → absent field (W1 wire\n * semantic: empty and omitted are indistinguishable on the wire).\n * @internal\n */\nfunction scalarField(value: string): RawField {\n if (value === \"\") return { repetitions: [], isNull: false };\n return {\n repetitions: [\n {\n components: [{ subcomponents: [value] }],\n },\n ],\n isNull: false,\n };\n}\n\n/**\n * Build an absent RawField (no content, not null).\n * @internal\n */\nfunction absentField(): RawField {\n return { repetitions: [], isNull: false };\n}\n\n/**\n * Build MSH-9 from a `^`-delimited type string per the Claude's Discretion\n * resolution (accept a single string, split on `^` for component\n * decomposition). Empty parts suppressed via D-02 trailing-empty strip at\n * emit time.\n * @internal\n */\nfunction compositeField(typeString: string): RawField {\n const parts = typeString.split(\"^\");\n const components = parts.map((p) => ({ subcomponents: [p] }));\n return {\n repetitions: [{ components }],\n isNull: false,\n };\n}\n","/**\n * Frozen HL7 control-vocabulary tables for ACK generation (Phase C). These\n * are read-only enums sourced from the HL7 v2 standard — `@cosyte/hl7` is the\n * single owner of this vocabulary; siblings (notably `@cosyte/mllp`) consume\n * `buildAck` rather than re-declaring these codes.\n *\n * Provenance (re-verify before editing — HL7 tables move):\n * - **Table 0008** Acknowledgment code — https://terminology.hl7.org/CodeSystem-v2-0008.html\n * - **Table 0357** Message error condition codes — https://terminology.hl7.org/CodeSystem-v2-0357.html\n * - **Table 0516** Error severity — HL7 v2 Chapter 2 §2.14.5 (ERR-4)\n * - **Table 0155** Accept/application acknowledgment conditions (MSH-15/16) —\n * HL7 v2 Chapter 2 §2.14.9.15–16\n *\n * Zero runtime deps.\n */\n\n/**\n * HL7 Table 0008 — Acknowledgment code (MSA-1). The two acknowledgment\n * **vocabularies**:\n * - **original** mode: `AA` Application Accept · `AE` Application Error ·\n * `AR` Application Reject.\n * - **enhanced** mode accept-level: `CA` Commit Accept · `CE` Commit Error ·\n * `CR` Commit Reject (the application-level response in enhanced mode reuses\n * `AA`/`AE`/`AR`).\n *\n * @example\n * ```ts\n * import { ACK_CODES } from \"@cosyte/hl7\";\n * ACK_CODES.AA; // \"AA\"\n * ```\n */\nexport const ACK_CODES = {\n AA: \"AA\",\n AE: \"AE\",\n AR: \"AR\",\n CA: \"CA\",\n CE: \"CE\",\n CR: \"CR\",\n} as const;\n\n/**\n * Acknowledgment code union (HL7 Table 0008). Narrow on this to know whether a\n * disposition is accept (`AA`/`CA`), error (`AE`/`CE`), or reject (`AR`/`CR`).\n */\nexport type AckCode = (typeof ACK_CODES)[keyof typeof ACK_CODES];\n\n/** The positive-accept codes — the ones the fail-safe refuses to fabricate. */\nconst POSITIVE_ACK_CODES: ReadonlySet<string> = new Set([ACK_CODES.AA, ACK_CODES.CA]);\n/** The error codes (message received, processing problem). */\nconst ERROR_ACK_CODES: ReadonlySet<string> = new Set([ACK_CODES.AE, ACK_CODES.CE]);\n/** The reject codes (message refused). */\nconst REJECT_ACK_CODES: ReadonlySet<string> = new Set([ACK_CODES.AR, ACK_CODES.CR]);\n\n/**\n * True iff `code` is a positive accept (`AA`/`CA`). Unknown/absent → false.\n *\n * @example\n * ```ts\n * isPositiveAck(\"AA\"); // true\n * isPositiveAck(\"AE\"); // false\n * ```\n */\nexport function isPositiveAck(code: string | undefined): boolean {\n return code !== undefined && POSITIVE_ACK_CODES.has(code);\n}\n\n/**\n * Downgrade a positive acknowledgment code to its matching error code —\n * `AA` → `AE` (original mode), `CA` → `CE` (enhanced mode). Every other code\n * passes through unchanged.\n *\n * This is the **single upstream source of truth** for the fail-safe downgrade\n * pair: `buildAck` applies it when the inbound carries no MSH-10 correlation\n * id, and `@cosyte/mllp`'s `ack-from-hl7` adapter applies it when the inbound\n * cannot be parsed at all — neither ever fabricates an unverifiable positive\n * acknowledgment, and neither carries its own copy of the mapping.\n *\n * @example\n * ```ts\n * import { downgradePositiveAck } from \"@cosyte/hl7\";\n * downgradePositiveAck(\"AA\"); // \"AE\"\n * downgradePositiveAck(\"CA\"); // \"CE\"\n * downgradePositiveAck(\"AR\"); // \"AR\" (unchanged)\n * ```\n */\nexport function downgradePositiveAck(code: AckCode): AckCode {\n if (code === ACK_CODES.AA) return ACK_CODES.AE;\n if (code === ACK_CODES.CA) return ACK_CODES.CE;\n return code;\n}\n\n/**\n * True iff `code` is an error acknowledgment (`AE`/`CE`). Unknown/absent → false.\n *\n * @example\n * ```ts\n * isErrorAck(\"CE\"); // true\n * ```\n */\nexport function isErrorAck(code: string | undefined): boolean {\n return code !== undefined && ERROR_ACK_CODES.has(code);\n}\n\n/**\n * True iff `code` is a reject acknowledgment (`AR`/`CR`). Unknown/absent → false.\n *\n * @example\n * ```ts\n * isRejectAck(\"AR\"); // true\n * ```\n */\nexport function isRejectAck(code: string | undefined): boolean {\n return code !== undefined && REJECT_ACK_CODES.has(code);\n}\n\n/**\n * True iff `code` is one of the six known Table 0008 codes.\n *\n * @example\n * ```ts\n * isKnownAckCode(\"AA\"); // true\n * isKnownAckCode(\"ZZ\"); // false\n * ```\n */\nexport function isKnownAckCode(code: string): code is AckCode {\n return code in ACK_CODES;\n}\n\n/**\n * HL7 Table 0516 — Error severity (ERR-4). A v2.5+ construct (ERR was\n * structured differently in v2.3.1).\n *\n * @example\n * ```ts\n * import { ERR_SEVERITIES } from \"@cosyte/hl7\";\n * ERR_SEVERITIES.E; // \"E\" (Error)\n * ```\n */\nexport const ERR_SEVERITIES = {\n /** Information. */\n I: \"I\",\n /** Warning. */\n W: \"W\",\n /** Error. */\n E: \"E\",\n} as const;\n\n/** Error-severity union (HL7 Table 0516, ERR-4). */\nexport type ErrSeverity = (typeof ERR_SEVERITIES)[keyof typeof ERR_SEVERITIES];\n\n/**\n * HL7 Table 0357 — Message error condition codes (ERR-3.1 → ERR-3.2 text).\n * Frozen read-only map of `code → standard display text`. The code system\n * name emitted in ERR-3.3 is {@link ERR_CONDITION_CODE_SYSTEM}.\n *\n * Codes `104` (value too long) and `105` (table value not found) are v2.7+\n * additions; the rest are present from v2.5. `buildAck` emits whatever code it\n * is told — it never invents a condition — and looks up the display text here.\n *\n * @example\n * ```ts\n * import { ERR_CONDITION_CODES } from \"@cosyte/hl7\";\n * ERR_CONDITION_CODES[\"101\"]; // \"Required field missing\"\n * ```\n */\nexport const ERR_CONDITION_CODES: Readonly<Record<string, string>> = Object.freeze({\n \"0\": \"Message accepted\",\n \"100\": \"Segment sequence error\",\n \"101\": \"Required field missing\",\n \"102\": \"Data type error\",\n \"103\": \"Table value not found\",\n \"104\": \"Value too long\",\n \"105\": \"Table value not found\",\n \"200\": \"Unsupported message type\",\n \"201\": \"Unsupported event code\",\n \"202\": \"Unsupported processing id\",\n \"203\": \"Unsupported version id\",\n \"204\": \"Unknown key identifier\",\n \"205\": \"Duplicate key identifier\",\n \"206\": \"Application record locked\",\n \"207\": \"Application internal error\",\n});\n\n/** Code-system name emitted in ERR-3.3 for Table 0357 condition codes. */\nexport const ERR_CONDITION_CODE_SYSTEM = \"HL70357\";\n\n/**\n * HL7 Table 0155 — Accept/application acknowledgment conditions (MSH-15 /\n * MSH-16): `AL` Always · `NE` Never · `ER` Error/reject conditions only ·\n * `SU` Successful completion only. Exposed read-only for adapters that\n * surface the inbound sender's stated acknowledgment expectations.\n *\n * @example\n * ```ts\n * import { ACK_CONDITIONS } from \"@cosyte/hl7\";\n * ACK_CONDITIONS.AL; // \"AL\" (Always)\n * ```\n */\nexport const ACK_CONDITIONS = {\n AL: \"AL\",\n NE: \"NE\",\n ER: \"ER\",\n SU: \"SU\",\n} as const;\n\n/** Accept/application acknowledgment condition union (HL7 Table 0155). */\nexport type AckCondition = (typeof ACK_CONDITIONS)[keyof typeof ACK_CONDITIONS];\n\n/**\n * The two HL7 acknowledgment modes. **original** = both MSH-15 and MSH-16 are\n * absent/null; **enhanced** = either is present (HL7 v2 Chapter 2 §2.9).\n */\nexport type AckMode = \"original\" | \"enhanced\";\n","/**\n * `buildAck` — generate a spec-clean HL7 v2 acknowledgment (ACK) message from\n * an inbound message (Phase C). The boundary with `@cosyte/mllp` is resolved\n * (hl7 roadmap §10.1): **hl7 owns ACK *content*** (this file + the control\n * tables); mllp owns *policy/timing* (the commit contract) and *framing*.\n *\n * `buildAck` is **mechanical** — it builds the disposition it is *told* via\n * `options.code`; it never decides accept-vs-reject. The one safety override is\n * the fail-safe below: it refuses to fabricate a positive `AA`/`CA` for an\n * inbound message that carries no MSH-10 correlation id.\n *\n * Spec traceability: HL7 v2 Chapter 2 §2.9 (ack model), §2.14.8 (MSA),\n * §2.14.5 (ERR), §2.14.9.15–16 (MSH-15/16). Tables 0008 / 0357 / 0516 / 0155\n * live in `ack-tables.ts`.\n *\n * Zero runtime deps.\n */\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { EncodingCharacters, RawField, RawSegment } from \"../parser/types.js\";\nimport { ackNoCorrelationId } from \"../parser/warnings.js\";\n\nimport {\n downgradePositiveAck,\n ERR_CONDITION_CODES,\n ERR_CONDITION_CODE_SYSTEM,\n ERR_SEVERITIES,\n isKnownAckCode,\n isPositiveAck,\n type AckCode,\n type AckMode,\n type ErrSeverity,\n} from \"./ack-tables.js\";\nimport { generateControlId } from \"./control-id.js\";\nimport { formatHl7Timestamp } from \"./format-timestamp.js\";\n\n/**\n * One ERR segment's worth of error detail for `buildAck`. Carries **codes and\n * locations only — never echoed PHI values** (the phi-redaction-review gate\n * binds this contract).\n *\n * @example\n * ```ts\n * import { buildAck } from \"@cosyte/hl7\";\n * const ack = buildAck(inbound, {\n * code: \"AE\",\n * error: { conditionCode: \"101\", severity: \"E\", location: \"PID^1^5\" },\n * });\n * ```\n */\nexport interface AckErrorDetail {\n /**\n * HL7 Table 0357 message error condition code (ERR-3.1). Defaults to `\"207\"`\n * (Application internal error). The standard display text is looked up from\n * Table 0357 and emitted in ERR-3.2; unknown codes emit with empty text\n * (the code is preserved verbatim — never dropped).\n */\n readonly conditionCode?: string;\n /** HL7 Table 0516 severity (ERR-4). Defaults to `\"E\"` (Error). */\n readonly severity?: ErrSeverity;\n /**\n * Error location (ERR-2, an HL7 ERL). A structural path such as `\"PID^1^5\"`\n * (segment id ^ segment sequence ^ field position). **Must not contain a\n * patient data value** — locations point at *where*, never *what*.\n */\n readonly location?: string;\n}\n\n/**\n * Options for {@link buildAck}.\n *\n * @example\n * ```ts\n * buildAck(inbound, { code: \"AA\" }); // bare accept\n * buildAck(inbound, { code: \"AR\", error: { conditionCode: \"200\" } });\n * ```\n */\nexport interface BuildAckOptions {\n /**\n * The acknowledgment disposition to emit in MSA-1 (HL7 Table 0008). One of\n * `AA`/`AE`/`AR` (original) or `CA`/`CE`/`CR` (enhanced accept-level).\n * Required — `buildAck` builds the disposition it is told. An unknown code\n * is a programming error and throws `TypeError`.\n */\n readonly code: AckCode;\n /**\n * Optional error detail. A single {@link AckErrorDetail} or an array → one\n * ERR segment each. Typically supplied for `AE`/`AR`/`CE`/`CR`.\n */\n readonly error?: AckErrorDetail | readonly AckErrorDetail[];\n /**\n * Optional explicit acknowledgment mode. When omitted it is derived from the\n * inbound MSH-15/16 via {@link detectAckMode}. `buildAck` emits `code`\n * verbatim regardless of mode — this field is advisory metadata for adapters\n * (e.g. `@cosyte/mllp`'s commit-policy layer) that need the detected mode.\n */\n readonly mode?: AckMode;\n}\n\n/**\n * Detect the HL7 acknowledgment mode of an inbound message from MSH-15 (accept\n * acknowledgment type) and MSH-16 (application acknowledgment type), per HL7 v2\n * Chapter 2 §2.9: **original** when *both* are absent/empty; **enhanced** when\n * *either* is present. This split is spec-exact (unlike the disposition mapping,\n * which has no single correct model — see the package README).\n *\n * @example\n * ```ts\n * import { detectAckMode, parseHL7 } from \"@cosyte/hl7\";\n * detectAckMode(parseHL7(raw)); // \"original\" | \"enhanced\"\n * ```\n */\nexport function detectAckMode(inbound: Hl7Message): AckMode {\n const acceptType = inbound.get(\"MSH.15\");\n const appType = inbound.get(\"MSH.16\");\n const hasAccept = acceptType !== undefined && acceptType !== \"\";\n const hasApp = appType !== undefined && appType !== \"\";\n return hasAccept || hasApp ? \"enhanced\" : \"original\";\n}\n\n/**\n * Build a spec-clean ACK (`MSH` + `MSA` [+ `ERR`…]) responding to `inbound`.\n *\n * Behavior:\n * - **MSH** — sender/receiver are swapped (inbound MSH-5/6 → ACK MSH-3/4;\n * inbound MSH-3/4 → ACK MSH-5/6); MSH-7 is the current UTC time; MSH-9 is\n * `ACK` (with the inbound trigger event echoed as `ACK^<trigger>^ACK` when\n * present); MSH-10 is a freshly generated control id; MSH-11 (processing id)\n * and MSH-12 (version) echo the inbound values.\n * - **MSA** — MSA-1 = `code`; **MSA-2 echoes the full inbound MSH-10 field**\n * (the raw field structure is carried over whole — a vendor-quirk id like\n * `ID^X` is never truncated to its first component). The echo carries the\n * inbound field's escape-fidelity overlay (HL7-ESC), so an id bearing a hex\n * escape (`ID\\X41\\Q`) or a preserved escape (`\\H\\`) echoes **byte-verbatim**,\n * not canonicalized — exactly the bytes the sender put on the wire, which is\n * what MSA-2 correlation compares. The only structural transform is\n * trailing-empty canonicalization (D-02). (A sender that used *custom*\n * encoding characters is **re-delimited spec-cleanly**: the overlay carries\n * the sender's raw bytes in the sender's alphabet, so echoing them verbatim\n * under the ACK's default alphabet would corrupt the field's structure and\n * break correlation — the overlay is therefore bypassed and the decoded id is\n * re-escaped under default, which re-parses back to the same control id.\n * Default-delimiter senders, the norm, keep the byte-exact overlay echo.)\n * - **ERR** — one segment per supplied {@link AckErrorDetail}: ERR-2 location\n * (when given), ERR-3 the Table 0357 condition code as a CWE\n * (`code^text^HL70357`), ERR-4 the Table 0516 severity.\n *\n * **Fail-safe (roadmap §Phase C).** If the inbound message has no MSH-10, the\n * ACK cannot be correlated. `buildAck` then leaves MSA-2 empty and, if a\n * positive accept (`AA`/`CA`) was requested, **downgrades it** to the matching\n * error code (`AE`/`CE`) — it never fabricates an unverifiable positive ACK.\n * The returned message carries an `ACK_NO_CORRELATION_ID` warning. (This is the\n * inbound-side complement to `@cosyte/mllp`'s \"no commit ⇒ never AA\".)\n *\n * Pure aside from the generated control id + timestamp; never throws except on\n * a programming error (`inbound` not an `Hl7Message`, or an unknown `code`).\n *\n * @example\n * ```ts\n * import { buildAck, parseHL7 } from \"@cosyte/hl7\";\n * const inbound = parseHL7(raw);\n * const ack = buildAck(inbound, { code: \"AA\" });\n * console.log(ack.toString()); // MSH|...\\rMSA|AA|<inbound MSH-10>\n * parseHL7(ack.toString()).meta.type; // \"ACK\" (round-trips clean)\n * ```\n */\nexport function buildAck(inbound: Hl7Message, options: BuildAckOptions): Hl7Message {\n if (!(inbound instanceof Hl7Message)) {\n throw new TypeError(\"buildAck: `inbound` must be an Hl7Message (from parseHL7).\");\n }\n if (typeof options.code !== \"string\" || !isKnownAckCode(options.code)) {\n throw new TypeError(\n `buildAck: \\`code\\` must be a known HL7 Table 0008 acknowledgment code ` +\n `(AA/AE/AR/CA/CE/CR). Received: ${JSON.stringify(options.code)}.`,\n );\n }\n\n const enc = DEFAULT_ENCODING_CHARACTERS;\n const meta = inbound.meta;\n\n // Swap the addressing HDs by ALIASING the inbound RAW field objects (not\n // the component-1-only `meta` scalars), so multi-component HDs like\n // `APP^DNS^ISO` survive into the reply intact rather than being truncated.\n // Sharing by reference is safe because every Hl7Message mutation method\n // (setField et al.) is copy-on-write leaf-to-root — neither message can\n // corrupt the other through the shared subtree.\n const msh = inbound.segments(\"MSH\")[0];\n const inboundMsh = (n: number): RawField => msh?.field(n).raw ?? absentField();\n\n // Correlation: MSA-2 echoes the inbound RAW MSH-10 field **verbatim** —\n // not the component-1-only `meta.controlId` scalar. A vendor-quirk control\n // id carrying an unescaped delimiter (`ID^X`) must survive into MSA-2\n // byte-for-byte, or a sender correlating on the raw MSH-10 bytes will\n // never match the ACK (HL7 v2 §2.9.2.2: a mismatch is a correlation\n // failure). Absent/empty → fail-safe path.\n //\n // Escape-fidelity overlay caveat (HL7-ESC): the overlay carries the inbound\n // MSH-10's original wire bytes in the SENDER's delimiter alphabet. This ACK\n // emits with DEFAULT encoding characters, so emitting those bytes verbatim is\n // only correct when the inbound used the default alphabet too — otherwise a\n // raw byte that is a delimiter/escape under DEFAULT (but was plain data or a\n // different escape for the sender) would re-parse into a corrupted, truncated\n // MSA-2 and BREAK correlation. So for a custom-delimiter sender we drop the\n // overlay and re-escape the DECODED value under default (spec-clean, and it\n // re-parses back to the same decoded control id — correlation-correct). A\n // default-delimiter sender (the norm) keeps the overlay and echoes byte-exact.\n const sameEnc = encodingsEqual(inbound.encodingCharacters, enc);\n const rawControlId = sameEnc ? inboundMsh(10) : stripEscapeOverlay(inboundMsh(10));\n const hasCorrelation = rawFieldHasContent(rawControlId);\n\n // Resolve the emitted disposition, applying the no-correlation fail-safe.\n const emittedCode: string = hasCorrelation\n ? options.code\n : isPositiveAck(options.code)\n ? downgradePositiveAck(options.code)\n : options.code;\n\n // ── MSH ────────────────────────────────────────────────────────────────\n const ackType = meta.triggerEvent !== undefined ? `ACK^${meta.triggerEvent}^ACK` : \"ACK\";\n const version = meta.version ?? \"2.5\";\n const processingId = meta.processingId ?? \"P\";\n\n const mshFields: RawField[] = [\n scalarField(enc.field),\n scalarField(\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\"),\n ),\n inboundMsh(5), // MSH-3 sendingApp = inbound MSH-5 (receivingApp)\n inboundMsh(6), // MSH-4 sendingFacility = inbound MSH-6 (receivingFacility)\n inboundMsh(3), // MSH-5 receivingApp = inbound MSH-3 (sendingApp)\n inboundMsh(4), // MSH-6 receivingFacility = inbound MSH-4 (sendingFacility)\n scalarField(formatHl7Timestamp(new Date())), // MSH-7\n absentField(), // MSH-8\n compositeField(ackType), // MSH-9\n scalarField(generateControlId()), // MSH-10\n scalarField(processingId), // MSH-11\n scalarField(version), // MSH-12\n ];\n\n const segments: RawSegment[] = [{ name: \"MSH\", fields: mshFields }];\n\n // ── MSA ────────────────────────────────────────────────────────────────\n // MSA-1 = disposition, MSA-2 = the raw inbound MSH-10 field copied\n // verbatim (empty under the fail-safe).\n segments.push({\n name: \"MSA\",\n fields: [\n absentField(),\n scalarField(emittedCode),\n hasCorrelation ? rawControlId : absentField(),\n ],\n });\n\n // ── ERR (one per supplied detail) ────────────────────────────────────────\n for (const detail of normalizeErrors(options.error)) {\n segments.push(buildErrSegment(detail));\n }\n\n const warnings = hasCorrelation ? [] : [ackNoCorrelationId({ segmentIndex: 0 })];\n\n return new Hl7Message({\n segments,\n encodingCharacters: enc,\n version,\n warnings,\n });\n}\n\n/** Normalize the `error` option to a (possibly empty) array. @internal */\nfunction normalizeErrors(\n error: AckErrorDetail | readonly AckErrorDetail[] | undefined,\n): readonly AckErrorDetail[] {\n if (error === undefined) return [];\n return isErrorArray(error) ? error : [error];\n}\n\n/**\n * Type guard narrowing the `error` union to the array branch. A user-defined\n * guard is needed because `Array.isArray` does not subtract `readonly T[]`\n * from a union on its own.\n * @internal\n */\nfunction isErrorArray(\n error: AckErrorDetail | readonly AckErrorDetail[],\n): error is readonly AckErrorDetail[] {\n return Array.isArray(error);\n}\n\n/**\n * Build one ERR `RawSegment` from an {@link AckErrorDetail}. ERR-3 is the\n * Table 0357 condition code as a CWE (`code^text^HL70357`); ERR-4 is the\n * Table 0516 severity. ERR-1 is left absent (deprecated v2.4 / withdrawn v2.7);\n * ERR-2 carries the optional location.\n * @internal\n */\nfunction buildErrSegment(detail: AckErrorDetail): RawSegment {\n const conditionCode = detail.conditionCode ?? \"207\";\n const severity: string = detail.severity ?? ERR_SEVERITIES.E;\n const text = ERR_CONDITION_CODES[conditionCode] ?? \"\";\n\n // ERR-3 CWE: identifier ^ text ^ name-of-coding-system.\n const err3: RawField = {\n repetitions: [\n {\n components: [\n { subcomponents: [conditionCode] },\n { subcomponents: [text] },\n { subcomponents: [ERR_CONDITION_CODE_SYSTEM] },\n ],\n },\n ],\n isNull: false,\n };\n\n return {\n name: \"ERR\",\n fields: [\n absentField(), // fields[0] — segment-name/separator placeholder slot\n absentField(), // ERR-1 (deprecated v2.4 / withdrawn v2.7)\n detail.location !== undefined ? compositeField(detail.location) : absentField(), // ERR-2 (ERL)\n err3, // ERR-3\n scalarField(severity), // ERR-4\n ],\n };\n}\n\n/**\n * Single plain-string field (empty → absent, matching wire semantics).\n * @internal\n */\nfunction scalarField(value: string): RawField {\n if (value === \"\") return { repetitions: [], isNull: false };\n return { repetitions: [{ components: [{ subcomponents: [value] }] }], isNull: false };\n}\n\n/** Absent field (no content, not null). @internal */\nfunction absentField(): RawField {\n return { repetitions: [], isNull: false };\n}\n\n/**\n * True iff two encoding-character sets are identical across every delimiter\n * (and the optional v2.7+ truncation char). Used to decide whether the inbound\n * MSH-10's escape-fidelity overlay — captured in the sender's alphabet — is safe\n * to echo verbatim under the ACK's DEFAULT alphabet.\n * @internal\n */\nfunction encodingsEqual(a: EncodingCharacters, b: EncodingCharacters): boolean {\n return (\n a.field === b.field &&\n a.component === b.component &&\n a.repetition === b.repetition &&\n a.escape === b.escape &&\n a.subcomponent === b.subcomponent &&\n a.truncation === b.truncation\n );\n}\n\n/**\n * Return a copy of `field` with the HL7-ESC `rawSubcomponents` overlay dropped\n * from every component, so `emitField` re-escapes the DECODED value instead of\n * emitting the sender's raw wire bytes verbatim. Used when the ACK's encoding\n * differs from the inbound's — see the correlation caveat in {@link buildAck}.\n * Returns the field unchanged when it carries no overlay (the common case), so\n * a default-delimiter inbound is untouched.\n * @internal\n */\nfunction stripEscapeOverlay(field: RawField): RawField {\n const hasOverlay = field.repetitions.some((rep) =>\n rep.components.some((comp) => comp.rawSubcomponents !== undefined),\n );\n if (!hasOverlay) return field;\n return {\n repetitions: field.repetitions.map((rep) => ({\n components: rep.components.map((comp) => ({ subcomponents: comp.subcomponents })),\n })),\n isNull: field.isNull,\n };\n}\n\n/**\n * True iff the raw field carries any content at all — at least one non-empty\n * subcomponent in any component of any repetition. Drives the correlation\n * check on the raw MSH-10: a quirky `^X` still correlates (the verbatim echo\n * preserves it), while a genuinely empty/absent field triggers the fail-safe.\n * @internal\n */\nfunction rawFieldHasContent(field: RawField): boolean {\n return field.repetitions.some((rep) =>\n rep.components.some((comp) => comp.subcomponents.some((sub) => sub !== \"\")),\n );\n}\n\n/**\n * MSH-9 composite from a `^`-delimited type string (`ACK^A01^ACK`).\n * @internal\n */\nfunction compositeField(typeString: string): RawField {\n const components = typeString.split(\"^\").map((p) => ({ subcomponents: [p] }));\n return { repetitions: [{ components }], isNull: false };\n}\n","/**\n * `interpretAck` — read-side helper that interprets an inbound HL7 v2\n * acknowledgment (ACK) message into a typed {@link Acknowledgment} view\n * (Phase C). The mechanical inverse of `buildAck`: it reads MSA-1 (code),\n * MSA-2 (the correlated control id), and every ERR segment.\n *\n * Fail-safe: an absent or unrecognized MSA-1 yields `accepted: false` — the\n * interpreter NEVER reports an acknowledgment as accepted on ambiguous input.\n *\n * Spec traceability: HL7 v2 Chapter 2 §2.14.8 (MSA), §2.14.5 (ERR). Codes are\n * surfaced verbatim (Table 0008 / 0357 / 0516) — no validation or lookup.\n *\n * Zero runtime deps.\n */\n\nimport { isErrorAck, isPositiveAck, isRejectAck } from \"../builder/ack-tables.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\n\n/**\n * One ERR segment interpreted from an ACK. All fields are surfaced verbatim\n * (no table lookup) and OMITTED when the underlying component is absent\n * (exactOptionalPropertyTypes). Codes/locations only — never PHI.\n */\nexport interface AckErrorEntry {\n /** ERR-3.1 — HL7 Table 0357 condition code. */\n readonly conditionCode?: string;\n /** ERR-3.2 — condition code display text. */\n readonly conditionText?: string;\n /** ERR-3.3 — condition code system name (e.g. `HL70357`). */\n readonly conditionCodeSystem?: string;\n /** ERR-4 — HL7 Table 0516 severity (`I`/`W`/`E`). */\n readonly severity?: string;\n /** ERR-2 — error location (an HL7 ERL), surfaced verbatim. */\n readonly location?: string;\n}\n\n/**\n * Typed view of an inbound ACK. `accepted` / `error` / `rejected` are derived\n * from MSA-1 against HL7 Table 0008 and are **mutually exclusive**; all three\n * are `false` when MSA-1 is absent or not a recognized code (fail-safe).\n *\n * @example\n * ```ts\n * import { interpretAck, parseHL7 } from \"@cosyte/hl7\";\n * const ack = interpretAck(parseHL7(rawAck));\n * if (ack.accepted) {\n * // safe to consider the message acknowledged\n * } else if (ack.rejected) {\n * for (const e of ack.errors) console.error(e.conditionCode, e.severity);\n * }\n * ```\n */\nexport interface Acknowledgment {\n /** MSA-1 acknowledgment code (HL7 Table 0008), verbatim. Omitted when absent. */\n readonly code?: string;\n /**\n * MSA-2 message control id (the correlated inbound MSH-10), surfaced as the\n * field's **canonical wire text** (`Field.text`) — the whole field,\n * delimiters included, never truncated to the first component. Note this is\n * the *re-escaped* form: a properly-escaped id arrives as its wire bytes\n * (`ID\\S\\X`), and an HL7 explicit-null MSA-2 surfaces as the literal\n * two-character `\"\"`. Omitted when absent/empty.\n */\n readonly controlId?: string;\n /** True iff MSA-1 is a positive accept (`AA`/`CA`). */\n readonly accepted: boolean;\n /** True iff MSA-1 is an error acknowledgment (`AE`/`CE`). */\n readonly error: boolean;\n /** True iff MSA-1 is a reject acknowledgment (`AR`/`CR`). */\n readonly rejected: boolean;\n /** Every ERR segment in document order ( `[]` when none ). */\n readonly errors: readonly AckErrorEntry[];\n}\n\n/**\n * Interpret an `Hl7Message` as an acknowledgment. Never throws; a message with\n * no MSA segment yields an all-`false`, empty-`errors` view. The result is\n * deeply frozen.\n *\n * @example\n * ```ts\n * import { interpretAck, parseHL7 } from \"@cosyte/hl7\";\n * const view = interpretAck(parseHL7(\"MSH|^~\\\\&|...\\rMSA|AA|MSG001\"));\n * view.accepted; // true\n * view.controlId; // \"MSG001\"\n * ```\n */\nexport function interpretAck(msg: Hl7Message): Acknowledgment {\n const msa = msg.segments(\"MSA\")[0];\n let code: string | undefined;\n let controlId: string | undefined;\n if (msa !== undefined) {\n const codeValue = msa.field(1).value;\n if (codeValue !== \"\") code = codeValue;\n // MSA-2 is surfaced as the field's VERBATIM wire text (`Field.text`), not\n // the component-1-only `.value` — the correlation id must compare\n // byte-for-byte against the raw MSH-10 the sender transmitted, even when\n // a vendor-quirk id carries an unescaped delimiter (`ID^X`).\n const controlIdValue = msa.field(2).text;\n if (controlIdValue !== \"\") controlId = controlIdValue;\n }\n\n const errors: AckErrorEntry[] = [];\n for (const err of msg.segments(\"ERR\")) {\n errors.push(interpretErr(err));\n }\n\n const out: Acknowledgment = {\n ...(code !== undefined ? { code } : {}),\n ...(controlId !== undefined ? { controlId } : {}),\n accepted: isPositiveAck(code),\n error: isErrorAck(code),\n rejected: isRejectAck(code),\n errors: Object.freeze(errors),\n };\n return Object.freeze(out);\n}\n\n/** Interpret one ERR segment into an {@link AckErrorEntry}. @internal */\nfunction interpretErr(err: Segment): AckErrorEntry {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<AckErrorEntry> = {};\n\n // ERR-2 is an ERL (Error Location) composite — `segment ^ sequence ^ field\n // position ^ …`. Surface it verbatim by re-joining its components with the\n // component separator (`.value` would yield only the first component). ERL\n // components are delimiter-free structural tokens, so no unescaping is owed.\n const location = readErl(err);\n if (location !== undefined) out.location = location;\n\n const condition = err.field(3).asCwe();\n if (condition.identifier !== undefined) out.conditionCode = condition.identifier;\n if (condition.text !== undefined) out.conditionText = condition.text;\n if (condition.nameOfCodingSystem !== undefined) {\n out.conditionCodeSystem = condition.nameOfCodingSystem;\n }\n\n const severity = err.field(4).value;\n if (severity !== \"\") out.severity = severity;\n\n return Object.freeze(out);\n}\n\n/**\n * Re-join an ERR-2 ERL composite (`PID^1^5`) from its components. Returns\n * `undefined` when the field is absent or carries no content. @internal\n */\nfunction readErl(err: Segment): string | undefined {\n const rep = err.field(2).repetitions[0];\n if (rep === undefined) return undefined;\n const joined = rep.components.map((c) => c.subcomponents[0] ?? \"\").join(\"^\");\n return joined === \"\" ? undefined : joined;\n}\n","/**\n * Build the multi-line `describe()` output per Plan 06-01 D-04. Omits\n * lines for absent fields (exactOptionalPropertyTypes idiom — mirrors\n * `src/helpers/meta.ts::buildMeta`); lineage rendered as `a → b → c`\n * when more than one name is present.\n *\n * Guaranteed non-empty and always starts with `Profile '<name>'` so the\n * PROF-05 \"contains the profile name\" contract is observable regardless\n * of which lines are omitted.\n *\n * @internal\n */\n\nimport type { Profile } from \"../parser/types.js\";\n\n/**\n * Format a `Profile` as a multi-line human-readable description. Always\n * starts with `Profile '<name>'` — see module-level JSDoc for the full\n * line-per-field layout.\n *\n * @internal\n */\nexport function buildDescribe(p: Profile): string {\n const lines: string[] = [`Profile '${p.name}'`];\n if (p.description !== undefined) {\n lines.push(` description: ${p.description}`);\n }\n const lineage = p.lineage ?? [p.name];\n lines.push(` lineage: ${lineage.join(\" → \")}`);\n if (p.customSegments !== undefined) {\n const keys = Object.keys(p.customSegments);\n lines.push(\n ` customSegments: ${String(keys.length)}` + (keys.length > 0 ? ` (${keys.join(\", \")})` : \"\"),\n );\n }\n if (p.dateFormats !== undefined && p.dateFormats.length > 0) {\n lines.push(` dateFormats: ${String(p.dateFormats.length)}`);\n }\n if (p.onWarning !== undefined) {\n lines.push(\" onWarning: registered\");\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Pure merge helpers consumed by `defineProfile()` when `opts.extends` is\n * supplied. Every helper takes a `readonly parents[]` + a self value and\n * returns the merged result; none mutate input. Implements D-03 (lineage),\n * D-09 (scalar last-wins), D-10 (dateFormats concat+dedupe), D-11\n * (customSegments deep-merge), D-12 (onWarning chain composition).\n *\n * Zero runtime deps. A local `Set` is used for first-occurrence dedup\n * tracking across lineage + dateFormats helpers; `mergeCustomSegments`\n * uses a position-indexed `Map` accumulator so later layers overwrite\n * same-position entries while non-colliding positions survive additively.\n *\n * Post-merge re-validation (D-05 Z-only; D-06 duplicate-name defense-in-\n * depth) is the CALLER's responsibility — these helpers are pure reducers.\n *\n * @internal\n */\n\nimport type { CustomSegmentDefinition, OnWarningCallback, Profile } from \"../parser/types.js\";\n\n/**\n * Normalise the `extends` input to a readonly array. Accepts either a\n * single `Profile` or an array; returns `[]` for `undefined` so callers\n * can treat \"no parents\" identically to \"zero parents\".\n *\n * @internal\n */\nexport function normaliseParents(\n ext: Profile | readonly Profile[] | undefined,\n): readonly Profile[] {\n if (ext === undefined) return [];\n if (Array.isArray(ext)) return ext as readonly Profile[];\n return [ext as Profile];\n}\n\n/**\n * Compute lineage per D-03: flatten parent lineages (or `[parent.name]`\n * when a parent has no lineage), append `selfName`, dedupe preserving\n * first occurrence.\n *\n * @internal\n */\nexport function mergeLineage(parents: readonly Profile[], selfName: string): readonly string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const p of parents) {\n const parentLineage = p.lineage ?? [p.name];\n for (const n of parentLineage) {\n if (!seen.has(n)) {\n seen.add(n);\n out.push(n);\n }\n }\n }\n if (!seen.has(selfName)) out.push(selfName);\n return Object.freeze(out);\n}\n\n/**\n * Merge dateFormats per D-10: concat parents (in order) then child,\n * dedupe preserving first occurrence. Parent formats come first so\n * they're tried FIRST by the TOL-08 cascade (compatible with the\n * \"parent behavior, then child specialization\" layering).\n *\n * @internal\n */\nexport function mergeDateFormats(\n parents: readonly Profile[],\n selfFormats: readonly string[],\n): readonly string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const p of parents) {\n for (const f of p.dateFormats ?? []) {\n if (!seen.has(f)) {\n seen.add(f);\n out.push(f);\n }\n }\n }\n for (const f of selfFormats) {\n if (!seen.has(f)) {\n seen.add(f);\n out.push(f);\n }\n }\n return Object.freeze(out);\n}\n\n/**\n * Merge customSegments per D-11: deep-merge by segment name, then by\n * field position. Fields with distinct positions merge additively; child\n * wins on position conflict. Iteration order is: every parent in order\n * (left-to-right), then self. The child's fields map REPLACES any prior\n * entries whose position collides, but preserves parent entries at\n * non-colliding positions within the same Z-segment.\n *\n * Post-merge re-validation (D-05, D-06) is the CALLER's responsibility —\n * this helper is a pure reducer.\n *\n * @internal\n */\nexport function mergeCustomSegments(\n parents: readonly Profile[],\n selfMap: Readonly<Record<string, CustomSegmentDefinition>>,\n): Readonly<Record<string, CustomSegmentDefinition>> {\n // Accumulate per-segment: position → field-name. Child overrides\n // position collisions; parent position entries at non-colliding\n // positions survive.\n const acc = new Map<string, Map<number, string>>();\n const layer = (map: Readonly<Record<string, CustomSegmentDefinition>> | undefined): void => {\n if (map === undefined) return;\n for (const segName of Object.keys(map)) {\n const entry = map[segName];\n if (entry === undefined) continue;\n let byPos = acc.get(segName);\n if (byPos === undefined) {\n byPos = new Map();\n acc.set(segName, byPos);\n }\n for (const fieldName of Object.keys(entry.fields)) {\n const pos = entry.fields[fieldName];\n if (pos === undefined) continue;\n byPos.set(pos, fieldName); // later layers overwrite earlier\n }\n }\n };\n for (const p of parents) {\n layer(p.customSegments);\n }\n layer(selfMap);\n\n const out: Record<string, CustomSegmentDefinition> = {};\n for (const [segName, byPos] of acc.entries()) {\n const fields: Record<string, number> = {};\n for (const [pos, fieldName] of byPos.entries()) {\n fields[fieldName] = pos;\n }\n out[segName] = Object.freeze({\n fields: Object.freeze(fields),\n });\n }\n return Object.freeze(out);\n}\n\n/**\n * Merge a scalar option per D-09: child value wins when explicitly\n * provided; otherwise the LAST parent with a non-undefined value.\n * Works for `description` today; signature is a generic-keyed shape so\n * future scalars reuse the same helper without rewrites.\n *\n * @internal\n */\nexport function mergeScalar<K extends keyof Profile>(\n parents: readonly Profile[],\n selfValue: Profile[K] | undefined,\n key: K,\n): Profile[K] | undefined {\n if (selfValue !== undefined) return selfValue;\n for (let i = parents.length - 1; i >= 0; i--) {\n const p = parents[i];\n if (p === undefined) continue;\n const v = p[key];\n if (v !== undefined) return v;\n }\n return undefined;\n}\n\n/**\n * Compose an onWarning chain per D-12: invoke every non-undefined\n * handler from parents (in order) then self. Each handler's throws are\n * silently swallowed so a noisy profile cannot break downstream\n * handlers. Returns `undefined` when no handlers are supplied anywhere\n * in the lineage (so `Profile.onWarning` stays optional).\n *\n * @internal\n */\nexport function composeOnWarning(\n handlers: readonly (OnWarningCallback | undefined)[],\n): OnWarningCallback | undefined {\n const concrete = handlers.filter((h): h is OnWarningCallback => h !== undefined);\n if (concrete.length === 0) return undefined;\n return (w) => {\n for (const h of concrete) {\n try {\n h(w);\n } catch {\n /* D-12 silent swallow */\n }\n }\n };\n}\n","/**\n * Validation helpers for `defineProfile()`. Implements the Plan 06-01\n * D-05..D-08 throw paths.\n *\n * Every validator returns `void` on success and throws\n * `ProfileDefinitionError` on failure. The name validator (subject of\n * D-01 fail-fast) is split from the full options validator so\n * `defineProfile()` can call it FIRST and pass `opts.name` to every\n * subsequent throw site.\n *\n * Zero runtime deps — inlined Levenshtein (~15 LoC) + regex + token match.\n *\n * @internal\n */\n\nimport { SUPPORTED_DATE_TOKENS } from \"../parser/dates.js\";\nimport { ProfileDefinitionError } from \"../parser/errors.js\";\nimport type { CustomSegmentDefinition } from \"../parser/types.js\";\n\nimport type { DefineProfileOptions } from \"./define.js\";\n\n/**\n * Z-segment shape: `Z` + 2 uppercase alphanumerics (D-05). Mirrors the\n * `SEGMENT_NAME_RE` convention used in `src/model/message.ts` for\n * addSegment validation — Z-segments are the allowed v1 overlay set.\n *\n * @internal\n */\nconst Z_SEGMENT_RE = /^Z[A-Z0-9]{2}$/u;\n\n/**\n * Known top-level option keys accepted by `defineProfile()` (D-07). Any\n * key outside this list triggers a `ProfileDefinitionError` with an\n * optional Levenshtein-based \"did you mean?\" hint.\n *\n * @internal\n */\nconst KNOWN_OPTION_KEYS: readonly string[] = [\n \"name\",\n \"description\",\n \"dateFormats\",\n \"customSegments\",\n \"onWarning\",\n \"extends\",\n];\n\n/**\n * Regex that matches any of the supported date-format tokens. Used by\n * `validateDateFormats` (D-08) to confirm each user-supplied format string\n * contains at least one recognised token — empty strings and dead formats\n * (`\"YYY/MM\"`, `\"foo\"`) fail fast.\n *\n * @internal\n */\nconst TOKEN_MATCH_RE = new RegExp(`(${SUPPORTED_DATE_TOKENS.join(\"|\")})`, \"u\");\n\n/**\n * Iterative DP Levenshtein distance (edit distance) between two strings.\n * Used by `validateOptionKeys` to generate \"did you mean?\" hints. Zero\n * runtime deps per D-33; kept ≤ 15 LoC excluding the signature.\n *\n * @internal\n */\nfunction levenshtein(a: string, b: string): number {\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n let prev: number[] = [];\n for (let j = 0; j <= b.length; j++) prev.push(j);\n for (let i = 1; i <= a.length; i++) {\n const curr: number[] = [i];\n for (let j = 1; j <= b.length; j++) {\n const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;\n curr.push(Math.min((prev[j] ?? 0) + 1, (curr[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + cost));\n }\n prev = curr;\n }\n return prev[b.length] ?? 0;\n}\n\n/**\n * Validate the profile NAME (D-01 fail-fast). Throws on null/undefined\n * opts, non-string name, empty name, whitespace-only name. Separate from\n * the full options validator so callers can trust `opts.name` by the time\n * downstream throws fire.\n *\n * @internal\n */\nexport function validateProfileName(opts: DefineProfileOptions): void {\n if (opts === null || opts === undefined) {\n throw new ProfileDefinitionError(\n \"defineProfile: options is required and must be an object. \" + `Received: ${String(opts)}.`,\n );\n }\n if (typeof opts.name !== \"string\") {\n throw new ProfileDefinitionError(\n \"defineProfile: 'name' is required and must be a non-empty string. \" +\n `Received: ${JSON.stringify((opts as { name?: unknown }).name)}.`,\n );\n }\n if (opts.name.trim().length === 0) {\n throw new ProfileDefinitionError(\n \"defineProfile: 'name' is required and must be a non-empty string. \" +\n `Received: ${JSON.stringify(opts.name)}.`,\n opts.name,\n );\n }\n}\n\n/**\n * Validate TOP-LEVEL option keys (D-07). Throws on any unknown key with a\n * Levenshtein-based \"did you mean?\" hint when distance ≤ 2 from a known\n * key.\n *\n * @internal\n */\nexport function validateOptionKeys(opts: DefineProfileOptions): void {\n for (const key of Object.keys(opts)) {\n if (KNOWN_OPTION_KEYS.includes(key)) continue;\n let hint: string | undefined;\n for (const known of KNOWN_OPTION_KEYS) {\n if (levenshtein(key, known) <= 2) {\n hint = known;\n break;\n }\n }\n throw new ProfileDefinitionError(\n `Profile '${opts.name}' has unknown option key '${key}'. ` +\n (hint !== undefined ? `Did you mean '${hint}'? ` : \"\") +\n `Known keys: ${KNOWN_OPTION_KEYS.join(\", \")}.`,\n opts.name,\n );\n }\n}\n\n/**\n * Validate a pre-merge customSegments map (D-05): every key MUST be a\n * Z-segment matching `/^Z[A-Z0-9]{2}$/u`, and every field position MUST\n * be a positive integer. Duplicate field-name detection (D-06) is\n * deferred to post-merge validation in Plan 02; for Plan 01's\n * single-profile path, object-literal syntax already rules out literal\n * duplicate keys so a simple presence check is sufficient here.\n *\n * @internal\n */\nexport function validateCustomSegments(\n map: Readonly<Record<string, CustomSegmentDefinition>>,\n profileName: string,\n): void {\n for (const key of Object.keys(map)) {\n if (!Z_SEGMENT_RE.test(key)) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' declares customSegments for '${key}' — only Z-segments ` +\n `(Z[A-Z0-9]{2}) are allowed in v1. Typed overlays are a v2 feature.`,\n profileName,\n );\n }\n const entry = map[key];\n if (\n entry === undefined ||\n entry === null ||\n typeof entry.fields !== \"object\" ||\n entry.fields === null\n ) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' customSegments['${key}'] must be an object with a 'fields' map.`,\n profileName,\n );\n }\n for (const fieldName of Object.keys(entry.fields)) {\n const pos = entry.fields[fieldName];\n if (typeof pos !== \"number\" || !Number.isInteger(pos) || pos < 1) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' customSegments['${key}'].fields['${fieldName}'] ` +\n `must be a positive integer (1-indexed). Received: ${JSON.stringify(pos)}.`,\n profileName,\n );\n }\n }\n }\n}\n\n/**\n * Validate date-format strings (D-08) — each MUST contain at least one\n * supported token from `SUPPORTED_DATE_TOKENS`. Catches typos like\n * `\"YYY/MM\"` (missing a `Y`) and empty strings before they reach the\n * parser's timestamp cascade.\n *\n * @internal\n */\nexport function validateDateFormats(formats: readonly string[], profileName: string): void {\n for (let i = 0; i < formats.length; i++) {\n const f = formats[i] ?? \"\";\n if (!TOKEN_MATCH_RE.test(f)) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' dateFormats[${String(i)}] = ${JSON.stringify(f)} is malformed — ` +\n `must contain at least one of ${SUPPORTED_DATE_TOKENS.join(\"/\")}.`,\n profileName,\n );\n }\n }\n}\n\n/**\n * Post-merge D-06 DEFENSE-IN-DEPTH check: within a single segment, the\n * SAME field name MUST NOT resolve to DIFFERENT positions. Cross-\n * position aliasing (two names, same position) is allowed — that's\n * intentional convenience.\n *\n * **Runtime observation:** Given the current `mergeCustomSegments`\n * strategy (accumulator keyed by position, where later layers overwrite\n * same-position entries), a name cannot survive at two positions: if a\n * parent has `{ a: 3 }` and a child has `{ a: 5 }`, the accumulator\n * produces `{ 3: \"a\", 5: \"a\" }` which lowers to `{ a: 5 }` (the second\n * assignment wins inside the final `Record`). If a parent has\n * `{ a: 3, b: 3 }` (two names at the same position — legal) and the\n * child has `{ a: 5 }`, the accumulator produces `{ 3: \"b\", 5: \"a\" }` →\n * output `{ a: 5, b: 3 }`; `a` maps to ONE position (5), no violation.\n * Therefore this validator never fires under the present strategy.\n *\n * It stays as code-level defense-in-depth because (a) it is cheap\n * (O(N) over fields of the merged map) and (b) if a future contributor\n * changes `mergeCustomSegments` to a name-keyed accumulator (e.g. to\n * preserve \"last write per name\" semantics that could allow a name to\n * remain at two positions), this validator becomes reachable and\n * catches the bug before the profile ships. The test suite asserts\n * the validator's presence and contract; it intentionally does NOT\n * assert that `defineProfile` throws through the current merge path for\n * a duplicate-name-different-position case, because that case is\n * unreachable today.\n *\n * @internal\n */\nexport function validateUniqueFieldNames(\n map: Readonly<Record<string, CustomSegmentDefinition>>,\n profileName: string,\n): void {\n for (const segName of Object.keys(map)) {\n const entry = map[segName];\n if (entry === undefined) continue;\n const positionsByName = new Map<string, number>();\n for (const fieldName of Object.keys(entry.fields)) {\n const pos = entry.fields[fieldName];\n if (pos === undefined) continue;\n const prior = positionsByName.get(fieldName);\n if (prior !== undefined && prior !== pos) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' customSegments['${segName}']: field name '${fieldName}' ` +\n `maps to BOTH position ${String(prior)} AND position ${String(pos)} after extends merge. ` +\n `Each field name within a segment must map to exactly one position.`,\n profileName,\n );\n }\n positionsByName.set(fieldName, pos);\n }\n }\n}\n","/**\n * `defineProfile()` — public factory for building `Profile` objects with\n * validation + `describe()` attached (PROF-01, PROF-04, PROF-05).\n *\n * Wave 1 (Plan 06-01) ships the single-profile (no-extends) path;\n * Wave 2 (Plan 06-02) fills in `extends` + merge semantics by extending\n * this factory's body. For Wave 1, `opts.extends` is ACCEPTED but\n * IGNORED, resulting in `lineage === [opts.name]` regardless.\n *\n * Zero runtime deps. Matches CLAUDE.md engineering guardrails: no `any`,\n * JSDoc `@example` on every public export, immutability at the return\n * boundary via `Object.freeze`, short testable helpers split across\n * `validate.ts` + `describe.ts`.\n *\n * Type ownership: `CustomSegmentDefinition` is declared CANONICALLY in\n * `src/parser/types.ts` (alongside `Profile`) and re-exported from THIS\n * module so `@cosyte/hl7` consumers can reach it via either entry\n * point. Single source of truth; no circular type imports.\n */\n\nimport type { CustomSegmentDefinition, OnWarningCallback, Profile } from \"../parser/types.js\";\n\nimport { buildDescribe } from \"./describe.js\";\nimport {\n composeOnWarning,\n mergeCustomSegments,\n mergeDateFormats,\n mergeLineage,\n mergeScalar,\n normaliseParents,\n} from \"./merge.js\";\nimport {\n validateCustomSegments,\n validateDateFormats,\n validateOptionKeys,\n validateProfileName,\n validateUniqueFieldNames,\n} from \"./validate.js\";\n\n/**\n * Re-export of the canonical `CustomSegmentDefinition` type (declared in\n * `src/parser/types.ts`) so profile authors importing from the profile\n * module get the same type identity as those importing from the package\n * barrel. Profile authors annotate Z-segment declarations with this type.\n *\n * @example\n * ```ts\n * import type { CustomSegmentDefinition } from \"@cosyte/hl7\";\n * const zdp: CustomSegmentDefinition = {\n * fields: { departmentCode: 3, departmentName: 4 },\n * };\n * ```\n */\nexport type { CustomSegmentDefinition } from \"../parser/types.js\";\n\n/**\n * Options accepted by `defineProfile()` (D-02). Mirrors the locked\n * `Profile` shape plus the `extends` input key. Every field except\n * `name` is optional.\n *\n * @example\n * ```ts\n * import { defineProfile, type DefineProfileOptions } from \"@cosyte/hl7\";\n * const opts: DefineProfileOptions = {\n * name: \"my-lab\",\n * dateFormats: [\"MM/DD/YYYY\"],\n * customSegments: { ZLB: { fields: { noteText: 3 } } },\n * };\n * const profile = defineProfile(opts);\n * ```\n */\nexport interface DefineProfileOptions {\n readonly name: string;\n readonly description?: string;\n readonly dateFormats?: readonly string[];\n readonly customSegments?: Readonly<Record<string, CustomSegmentDefinition>>;\n readonly onWarning?: OnWarningCallback;\n readonly extends?: Profile | readonly Profile[];\n}\n\n/**\n * Build a readonly `Profile` from a validated options object. Invalid\n * input throws `ProfileDefinitionError` with an actionable message\n * (PROF-02): bad Z-segment names (D-05), malformed date formats (D-08),\n * unknown top-level keys with typo hints (D-07), and missing/empty\n * name.\n *\n * Wave 1 (Plan 06-01) ships the no-extends path — `opts.extends` is\n * ACCEPTED but IGNORED, resulting in `lineage === [opts.name]`\n * regardless. Wave 2 (Plan 06-02) adds full lineage computation + merge\n * semantics.\n *\n * @example\n * ```ts\n * import { defineProfile } from \"@cosyte/hl7\";\n * const epic = defineProfile({\n * name: \"epic\",\n * description: \"Epic-specific quirks and ADT date formats\",\n * dateFormats: [\"MM/DD/YYYY HH:mm:ss\", \"MM/DD/YYYY\"],\n * customSegments: {\n * ZDP: { fields: { departmentCode: 3, departmentName: 4 } },\n * ZRS: { fields: { resultStatus: 1, statusDateTime: 2 } },\n * },\n * });\n * console.log(epic.name); // \"epic\"\n * console.log(epic.lineage); // [\"epic\"]\n * console.log(epic.describe?.());\n * ```\n */\nexport function defineProfile(opts: DefineProfileOptions): Profile {\n // D-01 fail-fast: name validation FIRST so downstream throws can\n // include `opts.name` as the second `ProfileDefinitionError` ctor arg.\n validateProfileName(opts);\n validateOptionKeys(opts);\n\n // Pre-merge: validate self-declared customSegments + dateFormats in\n // isolation so errors surface with the offending profile's own name\n // (not \"after merge\" — a user hitting D-05 should see their own\n // profile flagged, not the composed lineage).\n const selfCustomSegments = opts.customSegments ?? {};\n validateCustomSegments(selfCustomSegments, opts.name);\n const selfDateFormats = opts.dateFormats ?? [];\n validateDateFormats(selfDateFormats, opts.name);\n\n // D-03 + D-09..D-12 — full merge. Plan 06-02 replaces the Wave-1\n // lineage stub with this block.\n const parents = normaliseParents(opts.extends);\n const lineage = mergeLineage(parents, opts.name);\n const dateFormats = mergeDateFormats(parents, selfDateFormats);\n const customSegments = mergeCustomSegments(parents, selfCustomSegments);\n const description = mergeScalar(parents, opts.description, \"description\");\n const onWarning = composeOnWarning([...parents.map((p) => p.onWarning), opts.onWarning]);\n\n // Post-merge re-validation. `validateCustomSegments` catches the D-05\n // rogue-parent scenario (a hand-crafted Profile bypassing\n // defineProfile whose customSegments contains a non-Z key).\n // `validateUniqueFieldNames` is installed as DEFENSE-IN-DEPTH — it is\n // unreachable via the present mergeCustomSegments strategy (position-\n // indexed accumulator collapses same-name-different-position cases\n // to a single entry) but guards against future merge-strategy\n // changes. Both validators are O(N) over the merged map and run once\n // per defineProfile call.\n validateCustomSegments(customSegments, opts.name);\n validateUniqueFieldNames(customSegments, opts.name);\n\n // Assemble the frozen Profile. exactOptionalPropertyTypes discipline:\n // conditionally assign optional fields rather than writing\n // `description: undefined`. Mirrors `src/helpers/meta.ts::buildMeta`\n // lines 38-73 — the consistent pattern across the codebase.\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const profile: Mutable<Profile> = {\n name: opts.name,\n lineage,\n customSegments,\n dateFormats,\n };\n if (description !== undefined) profile.description = description;\n if (onWarning !== undefined) profile.onWarning = onWarning;\n\n // D-04: `describe()` attached as a method — closes over the assembled\n // profile object so calling `.describe()` always reflects the\n // fully-assembled state (not a half-built intermediate).\n const finalised: Profile = profile as Profile;\n profile.describe = (): string => buildDescribe(finalised);\n\n // W5 boundary-freeze: top-level only. Inner `customSegments` /\n // `lineage` / `dateFormats` stay `readonly` at the type level but\n // mutable at runtime per D-30 cost doctrine (matches Phase 5\n // `src/serialize/to-json.ts:139`).\n return Object.freeze(profile) as Profile;\n}\n","/**\n * athenahealth Interop API HL7 quirks. Ships US-short-date format\n * (`MM/DD/YYYY`) commonly used in athena ADT outbound. One Z-segment:\n * `ZCA` (care team membership). BIP-04.\n *\n * The AM/PM meridian variant (`MM/DD/YYYY HH:mm AM/PM`) is intentionally\n * NOT shipped — the library's format-token set does not include AM/PM\n * (`SUPPORTED_DATE_TOKENS` = YYYY/MM/DD/HH/mm/ss/SSSS). Consumers needing\n * meridian support can extend this profile or supply their own format\n * handler.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.athena);\n * const zca = msg.allSegments().find((s) => s.type === \"ZCA\");\n * console.log(zca?.get(\"providerName\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in athenahealth Interop profile (BIP-04). See file header for\n * rationale; use via `parseHL7(raw, profiles.athena)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.athena);\n * ```\n */\nexport const athena = defineProfile({\n name: \"athena\",\n description: \"athenahealth Interop — US-short-date format and care-team Z-segment\",\n dateFormats: [\"MM/DD/YYYY\"],\n customSegments: {\n ZCA: { fields: { careTeamRole: 3, providerId: 5, providerName: 6 } },\n },\n});\n","/**\n * Cerner Millennium HL7 quirks. Ships ISO-8601-with-T format\n * (`YYYY-MM-DDTHH:mm:ss`) plus ISO-date-only (`YYYY-MM-DD`), observed\n * across Millennium's native outbound feeds. Z-segments: `ZDS`\n * (discharge summary text) and `ZCO` (comment overflow for long fields).\n * BIP-02.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.cerner);\n * const zds = msg.allSegments().find((s) => s.type === \"ZDS\");\n * console.log(zds?.get(\"summaryText\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Cerner Millennium profile (BIP-02). See file header for\n * rationale; use via `parseHL7(raw, profiles.cerner)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.cerner);\n * ```\n */\nexport const cerner = defineProfile({\n name: \"cerner\",\n description: \"Cerner Millennium — ISO-style timestamps and common Z-segments\",\n dateFormats: [\"YYYY-MM-DDTHH:mm:ss\", \"YYYY-MM-DD\"],\n customSegments: {\n ZDS: { fields: { summaryText: 3 } },\n ZCO: { fields: { commentText: 3, continuationFlag: 5 } },\n },\n});\n","/**\n * Epic Bridges Interconnect HL7 quirks. Ships non-HL7 date formats\n * (`MM/DD/YYYY HH:mm:ss`, `MM/DD/YYYY`) commonly seen in ADT outbound\n * feeds, plus two Z-segments: `ZDP` (department context) and `ZRS`\n * (result status). BIP-01.\n *\n * Authored from the public `defineProfile()` API — zero privileged\n * internal coupling. Consumers extend this profile via\n * `defineProfile({ name: '...', extends: profiles.epic, ... })`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.epic);\n * const zdp = msg.allSegments().find((s) => s.type === \"ZDP\");\n * console.log(zdp?.get(\"departmentCode\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Epic Bridges Interconnect profile (BIP-01). See file header\n * for rationale; use via `parseHL7(raw, profiles.epic)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.epic);\n * ```\n */\nexport const epic = defineProfile({\n name: \"epic\",\n description: \"Epic Bridges Interconnect — ADT-style date formats and common Z-segments\",\n dateFormats: [\"MM/DD/YYYY HH:mm:ss\", \"MM/DD/YYYY\"],\n customSegments: {\n ZDP: { fields: { departmentCode: 3, departmentName: 4 } },\n ZRS: { fields: { resultStatus: 1, statusDateTime: 2 } },\n },\n});\n","/**\n * Generic reference-laboratory shape (LabCorp / Quest-style). Ships two\n * non-HL7 date formats: `YYYYMMDD HHmm` (ASTM-era space-separated) and\n * `YYYY-MM-DD` (ISO date-only). Two Z-segments: `ZLB` (lab-override\n * flags) and `ZNT` (lab note). BIP-05.\n *\n * The canonical HL7 format `YYYYMMDDHHmmss` is NOT shipped here — it's\n * already the parser's primary (zero-warning) match for TS/DTM.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.genericLab);\n * const znt = msg.allSegments().find((s) => s.type === \"ZNT\");\n * console.log(znt?.get(\"noteText\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in generic reference-laboratory profile (BIP-05). See file\n * header for rationale; use via `parseHL7(raw, profiles.genericLab)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.genericLab);\n * ```\n */\nexport const genericLab = defineProfile({\n name: \"genericLab\",\n description: \"Generic reference-laboratory — ASTM-era + ISO-date formats + lab Z-segments\",\n dateFormats: [\"YYYYMMDD HHmm\", \"YYYY-MM-DD\"],\n customSegments: {\n ZLB: { fields: { specimenOverride: 3, methodOverride: 5 } },\n ZNT: { fields: { noteText: 3 } },\n },\n});\n","/**\n * Meditech MAGIC / Expanse HL7 quirks. Ships minute-precision timestamps\n * (`YYYYMMDDHHmm`) — a non-HL7 format Meditech commonly uses in ADT and\n * scheduling feeds (HL7 spec is `YYYYMMDDHHmmss` with seconds). One\n * Z-segment: `ZVI` (visit info). BIP-03.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.meditech);\n * const zvi = msg.allSegments().find((s) => s.type === \"ZVI\");\n * console.log(zvi?.get(\"visitReason\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Meditech MAGIC/Expanse profile (BIP-03). See file header for\n * rationale; use via `parseHL7(raw, profiles.meditech)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.meditech);\n * ```\n */\nexport const meditech = defineProfile({\n name: \"meditech\",\n description: \"Meditech MAGIC/Expanse — minute-precision timestamps and visit-info Z-segment\",\n dateFormats: [\"YYYYMMDDHHmm\"],\n customSegments: {\n ZVI: { fields: { visitReason: 3, admitSource: 5 } },\n },\n});\n","/**\n * Public barrel for the `@cosyte/hl7` profile subsystem. Assembles\n * the `profiles` namespace object (5 built-ins) and re-exports the public\n * profile API: `defineProfile`, `setDefaultProfile`, `getDefaultProfile`,\n * plus the two type exports `DefineProfileOptions` and\n * `CustomSegmentDefinition`.\n *\n * D-26 contract: individual built-ins are NOT top-level named exports —\n * consumers access them via `profiles.epic`, `profiles.cerner`, etc.\n * (\"epic\" is too generic a name for a top-level export.)\n */\n\nexport { defineProfile } from \"./define.js\";\nexport type { DefineProfileOptions, CustomSegmentDefinition } from \"./define.js\";\nexport { setDefaultProfile, getDefaultProfile } from \"./default.js\";\n\nimport { athena } from \"./athena.js\";\nimport { cerner } from \"./cerner.js\";\nimport { epic } from \"./epic.js\";\nimport { genericLab } from \"./genericLab.js\";\nimport { meditech } from \"./meditech.js\";\n\n/**\n * Namespace object exposing the 5 shipped built-in vendor profiles (epic,\n * cerner, meditech, athena, genericLab). Each is authored via the public\n * `defineProfile()` API (BIP-01..05).\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.epic);\n * console.log(msg.profile?.name); // \"epic\"\n * ```\n */\nexport const profiles = Object.freeze({\n athena,\n cerner,\n epic,\n genericLab,\n meditech,\n}) as {\n readonly athena: typeof athena;\n readonly cerner: typeof cerner;\n readonly epic: typeof epic;\n readonly genericLab: typeof genericLab;\n readonly meditech: typeof meditech;\n};\n","/**\n * Coding-system provenance (HL7 Table 0396, READ-ONLY) — roadmap Phase F.\n *\n * Answers one question about a coded element: **\"what coding system does this\n * code CLAIM?\"** It surfaces the sender's CWE.3 / CE.3 \"Name of Coding System\"\n * value, normalizes well-known aliases to the registered Table 0396 acronym,\n * and reports a canonical human-readable name. It is provenance only:\n *\n * - **No validation.** It does not check that the code exists in the claimed\n * system, nor that the system is current. A wrong-but-registered code\n * (e.g. a deleted LOINC) still reports `known: true` for LOINC.\n * - **No lookup, no network, no bundled codeset.** Zero runtime deps; this is\n * a frozen acronym→name map, nothing more.\n * - **Fail-safe.** An unregistered / local / mistyped system id is surfaced\n * **verbatim** with `known: false` — never dropped, never guessed.\n *\n * Because provenance is the *sender's claim*, not a verified fact, a consumer\n * MUST still treat the code per its own trust policy. The value of this module\n * is letting that consumer ask \"which system?\" before interpreting a code — a\n * \"PCN\" allergen or an \"I10\" diagnosis is only safe to read once you know the\n * system it belongs to.\n *\n * Spec traceability: HL7 Table 0396 (Coding System) — the registry of\n * coding-system acronyms carried in the CWE.3 / CE.3 component. v2.7+ expects\n * the registered acronym. See `docs-content/spec-notes-coding-system.md` for\n * the per-entry source and the `I10` (ICD-10 vs ICD-10-CM) nuance.\n *\n * Zero runtime deps — pure data + pure functions.\n */\n\n/**\n * One recognized HL7 Table 0396 coding system: its registered acronym (the\n * value expected in CWE.3 / CE.3), a canonical human-readable name, and the\n * widely-used aliases tolerated for it. Aliases are matched case-insensitively.\n */\nexport interface KnownCodingSystem {\n /** Registered Table 0396 acronym, e.g. `\"LN\"`. */\n readonly id: string;\n /** Canonical human-readable name, e.g. `\"LOINC\"`. */\n readonly name: string;\n /**\n * Widely-used alternative spellings that claim the same system (matched\n * case-insensitively), e.g. `\"LOINC\"` for `LN`. The registered `id` itself\n * is always recognized and need not be repeated here.\n */\n readonly aliases: readonly string[];\n}\n\n/**\n * The safety-relevant subset of HL7 Table 0396 this library recognizes for\n * provenance. Deliberately small and frozen — it is NOT the full Table 0396\n * registry. Each entry's source is recorded in\n * `docs-content/spec-notes-coding-system.md`.\n *\n * Note on `I10`: Table 0396 registers `I10` as **ICD-10** (the WHO base\n * classification). US v2 feeds frequently send `I10` when they mean\n * ICD-10-**CM**, but that clinical-modification specificity is the sender's\n * convention, not what the acronym registers — so this map reports the\n * registered claim (`\"ICD-10\"`) and does not silently upgrade it to CM.\n *\n * @example\n * ```ts\n * import { KNOWN_CODING_SYSTEMS } from \"@cosyte/hl7\";\n * console.log(KNOWN_CODING_SYSTEMS.find((s) => s.id === \"LN\")?.name); // \"LOINC\"\n * ```\n */\nexport const KNOWN_CODING_SYSTEMS: readonly KnownCodingSystem[] = Object.freeze([\n Object.freeze({ id: \"LN\", name: \"LOINC\", aliases: Object.freeze([\"LOINC\"]) }),\n Object.freeze({\n id: \"SCT\",\n name: \"SNOMED CT\",\n aliases: Object.freeze([\"SNM\", \"SNOMED\", \"SNOMEDCT\"]),\n }),\n Object.freeze({ id: \"I10\", name: \"ICD-10\", aliases: Object.freeze([\"ICD-10\", \"ICD10\"]) }),\n Object.freeze({\n id: \"I10P\",\n name: \"ICD-10-PCS\",\n aliases: Object.freeze([\"ICD-10-PCS\", \"ICD10PCS\"]),\n }),\n Object.freeze({ id: \"RXN\", name: \"RxNorm\", aliases: Object.freeze([\"RXNORM\"]) }),\n Object.freeze({ id: \"NDC\", name: \"National Drug Codes\", aliases: Object.freeze([]) }),\n Object.freeze({ id: \"CVX\", name: \"CDC Vaccine Codes\", aliases: Object.freeze([]) }),\n Object.freeze({\n id: \"MVX\",\n name: \"CDC Vaccine Manufacturer Codes\",\n aliases: Object.freeze([]),\n }),\n Object.freeze({\n id: \"UCUM\",\n name: \"Unified Code for Units of Measure\",\n aliases: Object.freeze([]),\n }),\n] as const);\n\n/**\n * Case-insensitive lookup index: every registered id and every alias\n * (uppercased) → its `KnownCodingSystem`. Built once at module load.\n * @internal\n */\nconst LOOKUP: ReadonlyMap<string, KnownCodingSystem> = (() => {\n const m = new Map<string, KnownCodingSystem>();\n for (const sys of KNOWN_CODING_SYSTEMS) {\n m.set(sys.id.toUpperCase(), sys);\n for (const alias of sys.aliases) m.set(alias.toUpperCase(), sys);\n }\n return m;\n})();\n\n/**\n * A coding-system provenance answer — the system a code CLAIMS, never\n * validated. `claimed` is always present and verbatim (never dropped); the\n * resolved `id` / `name` are present only when the claim maps to a registered\n * Table 0396 entry.\n */\nexport interface CodingSystemInfo {\n /**\n * The coding-system id exactly as it appeared in CWE.3 / CE.3 — preserved\n * verbatim (original case and spelling), never altered, never dropped.\n */\n readonly claimed: string;\n /** `true` when `claimed` resolved (directly or via alias) to a registered Table 0396 entry. */\n readonly known: boolean;\n /** Registered Table 0396 acronym (alias-normalized). Present only when `known`. */\n readonly id?: string;\n /** Canonical human-readable name. Present only when `known`. */\n readonly name?: string;\n}\n\n/**\n * Resolve a raw coding-system id (a CWE.3 / CE.3 \"Name of Coding System\"\n * value) to its provenance. Returns `undefined` when there is no claim to\n * resolve — `id` is `undefined`, empty, or whitespace-only.\n *\n * Matching is case-insensitive and tolerant of surrounding whitespace, and\n * normalizes the well-known aliases in {@link KNOWN_CODING_SYSTEMS} (e.g.\n * `\"LOINC\"` → `LN`, `\"SNOMED\"` → `SCT`, `\"RxNorm\"` → `RXN`). An unrecognized\n * id is returned verbatim with `known: false` — never guessed.\n *\n * @example\n * ```ts\n * import { codingSystem } from \"@cosyte/hl7\";\n * codingSystem(\"LN\"); // { claimed: \"LN\", known: true, id: \"LN\", name: \"LOINC\" }\n * codingSystem(\"loinc\"); // { claimed: \"loinc\", known: true, id: \"LN\", name: \"LOINC\" }\n * codingSystem(\"99zL\"); // { claimed: \"99zL\", known: false }\n * codingSystem(undefined); // undefined\n * ```\n */\nexport function codingSystem(id: string | undefined): CodingSystemInfo | undefined {\n if (id === undefined) return undefined;\n const key = id.trim().toUpperCase();\n if (key === \"\") return undefined;\n\n const entry = LOOKUP.get(key);\n if (entry === undefined) {\n return Object.freeze({ claimed: id, known: false });\n }\n return Object.freeze({ claimed: id, known: true, id: entry.id, name: entry.name });\n}\n\n/**\n * Structural shape of any coded element that carries a primary + alternate\n * coding system — both {@link CWE} and {@link CE} satisfy it. Kept structural\n * (not a union) so callers can pass a `dg.code` / `obs.code` directly.\n */\nexport interface CodedSystemFields {\n readonly nameOfCodingSystem?: string;\n readonly nameOfAlternateCodingSystem?: string;\n}\n\n/**\n * Provenance of a coded element's **primary** coding system (CWE.3 / CE.3).\n * Returns `undefined` when the element claims no primary system.\n *\n * @example\n * ```ts\n * import { parseHL7, codingSystemOf } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const dg of msg.diagnoses()) {\n * const sys = dg.code && codingSystemOf(dg.code);\n * console.log(dg.code?.identifier, sys?.name ?? sys?.claimed ?? \"(no system)\");\n * }\n * ```\n */\nexport function codingSystemOf(coded: CodedSystemFields): CodingSystemInfo | undefined {\n return codingSystem(coded.nameOfCodingSystem);\n}\n\n/**\n * Provenance of a coded element's **alternate** coding system (CWE.6 / CE.6).\n * Returns `undefined` when the element claims no alternate system. Useful for\n * dual-coded fields (e.g. a problem carrying both SNOMED CT and ICD-10), where\n * assuming a single coding system would be unsafe.\n *\n * @example\n * ```ts\n * import { alternateCodingSystemOf } from \"@cosyte/hl7\";\n * const alt = alternateCodingSystemOf(dg.code);\n * if (alt) console.log(\"also coded in\", alt.name ?? alt.claimed);\n * ```\n */\nexport function alternateCodingSystemOf(coded: CodedSystemFields): CodingSystemInfo | undefined {\n return codingSystem(coded.nameOfAlternateCodingSystem);\n}\n","/**\n * Batch / file envelope splitting for the `@cosyte/hl7` parser (roadmap\n * Phase L). Real lab / ELR / IIS feeds ship many messages wrapped in the HL7\n * v2 batch protocol envelope (Ch. 2 §2.10.3):\n *\n * ```\n * [FHS] file header (optional)\n * { [BHS] batch header (optional, repeats)\n * { MSH … } messages (repeat)\n * [BTS] } batch trailer (optional)\n * [FTS] file trailer (optional)\n * ```\n *\n * `splitBatch()` demarcates the individual `MSH`-led messages by **MSH\n * boundaries**, parses each one with {@link parseHL7} (so every message is\n * returned either as a parsed `Hl7Message` **or** as a typed failure entry —\n * a malformed message mid-stream is isolated, never suppresses its siblings),\n * and reconciles the declared envelope counts (BTS-1 batch message count,\n * FTS-1 file batch count) against the actual counts — surfacing a\n * {@link batchCountMismatch} warning on any mismatch **without ever dropping\n * the tail**. A bare single message with no envelope passes straight through\n * as a one-message result.\n *\n * This is a **separate surface** from `parseHL7` on purpose: `parseHL7` rejects\n * non-`MSH`-first input outright (that is correct for a single-message\n * parser), so batch demarcation lives here. `splitBatch` is a **splitter**, not\n * an enforcer — it does not send batch ACKs, does not enforce any profile's\n * mandatory-envelope rule (it warns via {@link batchMissingTrailer}; the caller\n * decides to reject), and does not de-batch across transport framing (that is\n * `@cosyte/mllp`). See `docs-content/spec-notes-batch.md`.\n */\n\nimport { Buffer } from \"node:buffer\";\n\nimport { parseHL7 } from \"./index.js\";\nimport { Hl7ParseError } from \"./errors.js\";\nimport { normalize } from \"./normalize.js\";\nimport { splitSegments } from \"./segments.js\";\nimport type { Hl7Position, ParseOptions, Profile } from \"./types.js\";\nimport { batchCountMismatch, batchMissingTrailer } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\n\nimport type { Hl7Message } from \"../model/message.js\";\n\n/**\n * The four HL7 batch-protocol envelope segment names (Ch. 2 §2.10.3).\n *\n * @example\n * ```ts\n * import type { BatchEnvelopeName } from \"@cosyte/hl7\";\n * const trailer: BatchEnvelopeName = \"BTS\";\n * ```\n */\nexport type BatchEnvelopeName = \"FHS\" | \"BHS\" | \"BTS\" | \"FTS\";\n\n/**\n * A raw batch-envelope segment (`FHS`/`BHS`/`BTS`/`FTS`) surfaced by\n * {@link splitBatch}. `fields` is the segment split on its own field separator\n * with `fields[0]` holding the segment name — deliberately the raw token\n * array, not a typed model: first-class FHS/BHS field helpers are deferred\n * (roadmap Phase L defers \"typed FHS/BHS helpers beyond raw fields\"). Note the\n * HL7 MSH-family indexing quirk: for `FHS`/`BHS`, `fields[1]` is the\n * encoding-characters field (FHS-2/BHS-2); for `BTS`/`FTS`, `fields[1]` is\n * field 1 (BTS-1 batch message count / FTS-1 file batch count).\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * const { fileHeader } = splitBatch(\"FHS|^~\\\\&|SENDER\\r...\");\n * fileHeader?.name; // \"FHS\"\n * fileHeader?.fields[2]; // \"SENDER\" (FHS-3, the File Sending Application)\n * ```\n */\nexport interface BatchEnvelopeSegment {\n readonly name: BatchEnvelopeName;\n /** The verbatim segment string (line-ending normalized). */\n readonly raw: string;\n /** Raw field tokens; `fields[0]` is the segment name. */\n readonly fields: readonly string[];\n /** Position of this envelope segment in the split stream. */\n readonly position: Hl7Position;\n}\n\n/**\n * One message extracted from a batch stream. Discriminated on `ok`: a\n * successful parse carries the `Hl7Message` (whose own `.warnings` hold any\n * per-message Tier-2 deviations); a message that hit one of the four Tier-3\n * fatal conditions carries the `Hl7ParseError` instead — **isolated**, so the\n * rest of the batch still yields. `raw` is the message's verbatim source\n * (re-parseable by {@link parseHL7}); `position` is the message's `MSH` (or,\n * for pre-`MSH` stray content, its first) segment index in the stream.\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * for (const entry of splitBatch(raw).messages) {\n * if (entry.ok) handle(entry.message);\n * else quarantine(entry.raw, entry.error.code);\n * }\n * ```\n */\nexport type BatchMessageEntry =\n | {\n readonly ok: true;\n readonly message: Hl7Message;\n readonly raw: string;\n readonly position: Hl7Position;\n }\n | {\n readonly ok: false;\n readonly error: Hl7ParseError;\n readonly raw: string;\n readonly position: Hl7Position;\n };\n\n/**\n * One batch within a stream: a run of messages delimited by a `BHS` header\n * and/or a `BTS` trailer (both optional in §2.10.3, so a `BTS` closes a\n * preceding run into a batch even with no `BHS`). A run of messages with\n * **neither** a header nor a trailer is *not* a batch — those messages live in\n * {@link BatchSplitResult.messages} only, so they never inflate a batch count.\n * `declaredMessageCount` is BTS-1 when the trailer declared a usable\n * non-negative integer (it is **optional [0..1]** in the spec, so it may be\n * absent); `actualMessageCount` is always the real count.\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * const [batch] = splitBatch(raw).batches;\n * batch?.header?.name; // \"BHS\" (or undefined for a headerless BTS-closed run)\n * batch?.actualMessageCount; // messages actually in the batch\n * ```\n */\nexport interface Batch {\n /** The `BHS` header, when this batch was opened by one. */\n readonly header?: BatchEnvelopeSegment;\n /** The `BTS` trailer, when this batch was closed by one. */\n readonly trailer?: BatchEnvelopeSegment;\n /** The messages in this batch, in stream order. */\n readonly messages: readonly BatchMessageEntry[];\n /** BTS-1 batch message count, when declared as a non-negative integer. */\n readonly declaredMessageCount?: number;\n /** The actual number of messages split out of this batch. */\n readonly actualMessageCount: number;\n}\n\n/**\n * The result of {@link splitBatch}: the flattened `messages` (every message\n * across every batch, in stream order — the primary surface), the nested\n * `batches`, the raw file envelope segments, and the batch-level `warnings`\n * (count-mismatch / missing-trailer). `hadEnvelope` is `false` for a bare\n * passthrough (no FHS/BHS/BTS/FTS seen).\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * const result = splitBatch(rawBatchFile);\n * result.messages.length; // every message, batched or not\n * result.batches.length; // === result.actualBatchCount\n * result.warnings; // BATCH_COUNT_MISMATCH / BATCH_MISSING_TRAILER (counts only)\n * ```\n */\nexport interface BatchSplitResult {\n /**\n * Every message split out of the stream, in order — the primary surface. This\n * includes messages that belong to no explicit batch (a bare stream, or\n * content outside any `BHS`/`BTS`), so it is a superset of the messages\n * reachable via `batches`.\n */\n readonly messages: readonly BatchMessageEntry[];\n /** The explicit (`BHS`-delimited) batches, in stream order. */\n readonly batches: readonly Batch[];\n /** The **first** `FHS` file header, when present. */\n readonly fileHeader?: BatchEnvelopeSegment;\n /** The **last** `FTS` file trailer, when present. */\n readonly fileTrailer?: BatchEnvelopeSegment;\n /** The last `FTS-1` file batch count, when declared as a non-negative integer. */\n readonly declaredBatchCount?: number;\n /** The number of explicit batches split out of the stream. */\n readonly actualBatchCount: number;\n /** `false` when no envelope segment was seen (bare passthrough). */\n readonly hadEnvelope: boolean;\n /** Batch-level warnings (count mismatch, missing trailer); counts/positions only, never PHI. */\n readonly warnings: readonly Hl7ParseWarning[];\n}\n\n/** Mutable batch accumulator used while walking; frozen into a {@link Batch} at the end. */\ninterface MutableBatch {\n header?: BatchEnvelopeSegment;\n trailer?: BatchEnvelopeSegment;\n readonly messages: BatchMessageEntry[];\n /** BTS-1 once reconciled at close (undefined when absent/non-numeric). */\n declaredMessageCount?: number;\n}\n\n/**\n * The 3-character HL7 segment name at the start of a segment string. HL7\n * segment IDs are always exactly three characters, so a fixed slice is correct.\n *\n * Deliberately **case-sensitive** (no upper-casing): the batch-boundary segment\n * names (`FHS`/`BHS`/`BTS`/`FTS`/`MSH`) are only recognized when spelled in\n * their canonical uppercase form. This is a fail-safe against a lenient lowercase\n * body segment (e.g. `fts`) being mistaken for an envelope boundary — the\n * boundary segments cannot be disambiguated from a same-named body segment by\n * anything but their reserved name, so we keep the match strict. A lowercase\n * `msh`-led message is not a valid message anyway (`parseHL7`'s delimiter reader\n * requires an uppercase `MSH`), so declining to treat it as a boundary loses\n * nothing. See the reserved-name limitation in `docs-content/spec-notes-batch.md`.\n *\n * @internal\n */\nfunction segmentName(raw: string): string {\n return raw.slice(0, 3);\n}\n\n/** @internal — narrow a 3-char name to a batch-envelope segment name. */\nfunction isEnvelopeName(name: string): name is BatchEnvelopeName {\n return name === \"FHS\" || name === \"BHS\" || name === \"BTS\" || name === \"FTS\";\n}\n\n/**\n * Split an envelope segment into its raw field tokens on its own field\n * separator (the character at index 3, immediately after the 3-char name — the\n * same self-describing convention MSH uses). Returns `[name]` when the segment\n * has no field separator (a bare 3-char segment).\n *\n * @internal\n */\nfunction envelopeFields(raw: string): readonly string[] {\n const separator = raw.charAt(3);\n if (separator === \"\") return Object.freeze([raw.slice(0, 3)]);\n return Object.freeze(raw.split(separator));\n}\n\n/** @internal — build a frozen {@link BatchEnvelopeSegment}. */\nfunction makeEnvelope(\n name: BatchEnvelopeName,\n raw: string,\n segmentIndex: number,\n): BatchEnvelopeSegment {\n return Object.freeze({\n name,\n raw,\n fields: envelopeFields(raw),\n position: Object.freeze({ segmentIndex }),\n });\n}\n\n/**\n * Parse a declared envelope count. Returns the value only for a trimmed,\n * strictly-numeric, safe non-negative integer; `undefined` for an absent,\n * blank, or non-numeric token — so an absent BTS-1 ([0..1] in the spec) or a\n * garbage count tolerantly disables reconciliation rather than fabricating a\n * mismatch.\n *\n * @internal\n */\nfunction parseDeclaredCount(token: string | undefined): number | undefined {\n if (token === undefined) return undefined;\n const trimmed = token.trim();\n if (!/^\\d+$/.test(trimmed)) return undefined;\n const value = Number.parseInt(trimmed, 10);\n return Number.isSafeInteger(value) ? value : undefined;\n}\n\n/**\n * Parse one demarcated message and classify it. A successful {@link parseHL7}\n * yields an `ok` entry; one of the four Tier-3 fatals (`EMPTY_INPUT`,\n * `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`, `INVALID_ENCODING_CHARACTERS`) — or, under\n * `strict`, a promoted Tier-2 warning — is caught and returned as a typed\n * failure entry so it never suppresses the sibling messages. Any non-parser\n * throw is genuinely unexpected and re-raised.\n *\n * A `Buffer` stream is decoded/re-encoded via `latin1` (a lossless 1:1\n * byte↔codepoint mapping) so each message's own MSH-18 charset resolution runs\n * on its original bytes rather than a stream-wide guess.\n *\n * @internal\n */\nfunction parseEntry(\n rawMessage: string,\n position: Hl7Position,\n wasBuffer: boolean,\n optionsOrProfile: ParseOptions | Profile | undefined,\n): BatchMessageEntry {\n const input: string | Buffer = wasBuffer ? Buffer.from(rawMessage, \"latin1\") : rawMessage;\n try {\n // parseHL7 re-discriminates Profile vs ParseOptions from the argument's\n // runtime shape (its overloads share one implementation), so forwarding the\n // caller's second argument unchanged preserves identical per-message\n // semantics. The cast only selects an overload signature.\n const message =\n optionsOrProfile === undefined\n ? parseHL7(input)\n : parseHL7(input, optionsOrProfile as ParseOptions);\n return { ok: true, message, raw: rawMessage, position };\n } catch (error) {\n if (error instanceof Hl7ParseError) {\n return { ok: false, error, raw: rawMessage, position };\n }\n throw error;\n }\n}\n\n/**\n * Split a raw HL7 v2 **batch / file** stream into its individual messages plus\n * the envelope metadata. Demarcates by `MSH` boundaries inside the optional\n * `[FHS] { [BHS] { MSH… } [BTS] } [FTS]` frame (HL7 v2 Ch. 2 §2.10.3):\n *\n * - handles a file with **multiple batches** and a batch with multiple messages;\n * - a **bare single message** (no envelope) passes straight through as one entry;\n * - a **malformed message mid-batch is isolated** (returned as a typed failure\n * entry) — its siblings are still returned, the tail is never dropped;\n * - reconciles BTS-1 (batch message count) and FTS-1 (file batch count) and\n * emits {@link batchCountMismatch} on a mismatch — counts only, never PHI;\n * - emits {@link batchMissingTrailer} when a `BHS`/`FHS` header opens a scope no\n * `BTS`/`FTS` closes — a warning, never a throw (the caller decides to reject).\n *\n * The second argument, when given, is forwarded verbatim to {@link parseHL7}\n * for **each** message (profile, `strict`, `charset`, `dateFormats`, …). Under\n * `strict`, a message that would warn surfaces as a failure entry (still\n * isolated). `splitBatch` itself never throws — an empty stream yields an empty\n * result.\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n *\n * const { messages, warnings } = splitBatch(\n * \"FHS|^~\\\\&|SENDER\\r\" +\n * \"BHS|^~\\\\&|SENDER\\r\" +\n * \"MSH|^~\\\\&|A|F|B|G|20260101||ADT^A01|1|P|2.5\\rPID|||1\\r\" +\n * \"MSH|^~\\\\&|A|F|B|G|20260101||ADT^A01|2|P|2.5\\rPID|||2\\r\" +\n * \"BTS|2\\rFTS|1\\r\",\n * );\n * console.log(messages.length); // 2\n * for (const entry of messages) {\n * if (entry.ok) console.log(entry.message.version); // \"2.5\"\n * }\n * console.log(warnings.length); // 0 — declared counts match\n * ```\n */\nexport function splitBatch(raw: string | Buffer): BatchSplitResult;\nexport function splitBatch(raw: string | Buffer, profile: Profile): BatchSplitResult;\nexport function splitBatch(raw: string | Buffer, options: ParseOptions): BatchSplitResult;\n/** @internal — implementation signature; overloads above carry the public JSDoc. */\nexport function splitBatch(\n raw: string | Buffer,\n optionsOrProfile?: ParseOptions | Profile,\n): BatchSplitResult {\n const wasBuffer = typeof raw !== \"string\";\n // latin1 is a lossless byte↔codepoint decode: envelope segments + the \\r\n // segment terminator are ASCII, so demarcation is exact, and each message\n // slice re-encodes to its original bytes for per-message MSH-18 charset\n // resolution. NB: stream-level line-ending `normalize()` runs before that\n // per-message decode — correct for the single-byte / ASCII-superset charsets\n // HL7 batch framing uses (its \\r terminator must be a single 0x0D byte), but\n // not a byte-exact substitute for a multi-byte charset (e.g. UTF-16) whose\n // payload embeds 0x0A/0x0D bytes. Such batch files effectively do not exist.\n let text = wasBuffer ? raw.toString(\"latin1\") : raw;\n\n // Strip a leading BOM (UTF-8 as a string codepoint, or its raw latin1 bytes)\n // so the first FHS/MSH is still detected. Per-message BOMs are stripped again\n // by parseHL7.\n if (text.charCodeAt(0) === 0xfeff) {\n text = text.slice(1);\n } else if (text.startsWith(\"\")) {\n text = text.slice(3);\n }\n\n const segments = splitSegments(normalize(text));\n\n const flattened: BatchMessageEntry[] = [];\n const batches: MutableBatch[] = [];\n const warnings: Hl7ParseWarning[] = [];\n let fileHeader: BatchEnvelopeSegment | undefined;\n let fileTrailer: BatchEnvelopeSegment | undefined;\n let hadEnvelope = false;\n\n // A batch is a run of messages delimited by a `BHS` header AND/OR a `BTS`\n // trailer — both are optional in the §2.10.3 grammar, so a `BTS` closes the\n // preceding run into a batch even with no `BHS`. `pendingMessages` accumulates\n // the messages since the last boundary; `currentHeader` is the `BHS` that\n // opened the current run, if any. A run with NEITHER a header nor a trailer is\n // stray — kept in `flattened`/`messages` only, so it never inflates the FTS-1\n // batch count.\n let currentHeader: BatchEnvelopeSegment | undefined;\n let pendingMessages: BatchMessageEntry[] = [];\n let messageLines: string[] = [];\n let messageIndex = -1;\n\n // Per-file scoping so FTS-1 reconciles against the batches of THIS file only\n // (a concatenated second `FHS` resets the count instead of double-counting).\n let openFileHeader: BatchEnvelopeSegment | undefined; // an FHS awaiting its FTS\n let fileBatchCount = 0; // batches seen since the last FHS\n let lastDeclaredBatchCount: number | undefined; // most recent FTS-1\n\n const flushMessage = (): void => {\n // A blank segment right before a boundary is inter-message whitespace, not\n // part of the message (parseHL7 likewise strips a single trailing CR), so\n // drop trailing empties. Interior empties were already kept below.\n while (messageLines.length > 0 && messageLines[messageLines.length - 1] === \"\") {\n messageLines.pop();\n }\n if (messageLines.length === 0) {\n messageIndex = -1;\n return;\n }\n const entry = parseEntry(\n messageLines.join(\"\\r\"),\n Object.freeze({ segmentIndex: messageIndex }),\n wasBuffer,\n optionsOrProfile,\n );\n flattened.push(entry);\n pendingMessages.push(entry);\n messageLines = [];\n messageIndex = -1;\n };\n\n // Finalize the pending message run. A `BTS` trailer always closes the run into\n // a batch (headerless or headed) and reconciles BTS-1 — except a lone `BTS`\n // closing nothing (no messages, no header), which is ignorable noise. Without\n // a trailer, only a `BHS`-opened run is a batch (and warns for its missing\n // BTS); a headerless, trailer-less run is stray.\n const finalizeBatch = (trailer?: BatchEnvelopeSegment): void => {\n flushMessage();\n if (trailer !== undefined) {\n if (pendingMessages.length > 0 || currentHeader !== undefined) {\n const batch: MutableBatch = { messages: pendingMessages, trailer };\n if (currentHeader !== undefined) batch.header = currentHeader;\n const declared = parseDeclaredCount(trailer.fields[1]);\n if (declared !== undefined) {\n batch.declaredMessageCount = declared;\n if (declared !== pendingMessages.length) {\n warnings.push(\n batchCountMismatch(trailer.position, \"message\", declared, pendingMessages.length),\n );\n }\n }\n batches.push(batch);\n fileBatchCount += 1;\n }\n } else if (currentHeader !== undefined) {\n warnings.push(batchMissingTrailer(currentHeader.position, \"BHS\", \"BTS\"));\n batches.push({ messages: pendingMessages, header: currentHeader });\n fileBatchCount += 1;\n }\n // else: headerless, trailer-less run -> stray (already in `flattened`).\n pendingMessages = [];\n currentHeader = undefined;\n };\n\n // Close the current file scope. With an FTS trailer: reconcile FTS-1 against\n // the batches of this file. Without one (a new FHS, or end of stream): if a\n // file header was open, warn that it never got its FTS.\n const closeFile = (trailer?: BatchEnvelopeSegment): void => {\n finalizeBatch();\n if (trailer !== undefined) {\n fileTrailer = trailer;\n const declared = parseDeclaredCount(trailer.fields[1]);\n if (declared !== undefined) {\n lastDeclaredBatchCount = declared;\n if (declared !== fileBatchCount) {\n warnings.push(batchCountMismatch(trailer.position, \"batch\", declared, fileBatchCount));\n }\n }\n } else if (openFileHeader !== undefined) {\n warnings.push(batchMissingTrailer(openFileHeader.position, \"FHS\", \"FTS\"));\n }\n openFileHeader = undefined;\n fileBatchCount = 0;\n };\n\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index];\n if (segment === undefined) continue;\n // Skip a blank / whitespace-only line ONLY between messages — it is\n // inter-message whitespace carrying no segment content (splitBatch is\n // deliberately more tolerant of stream-level whitespace than parseHL7). A\n // blank segment INSIDE an open message is meaningful (HL7 keeps middle empty\n // segments for positional stability) and rides along so the message's `raw`\n // re-parses identically.\n if (messageLines.length === 0 && segment.trim() === \"\") continue;\n const name = segmentName(segment);\n\n if (isEnvelopeName(name)) {\n hadEnvelope = true;\n if (name === \"FHS\") {\n closeFile(); // close any prior file (warns if it had no FTS)\n const env = makeEnvelope(\"FHS\", segment, index);\n if (fileHeader === undefined) fileHeader = env; // result field keeps the first\n openFileHeader = env;\n } else if (name === \"FTS\") {\n closeFile(makeEnvelope(\"FTS\", segment, index));\n } else if (name === \"BHS\") {\n finalizeBatch(); // close the prior run before opening a new batch\n currentHeader = makeEnvelope(\"BHS\", segment, index);\n } else {\n finalizeBatch(makeEnvelope(\"BTS\", segment, index));\n }\n continue;\n }\n\n if (name === \"MSH\") {\n flushMessage();\n messageLines = [segment];\n messageIndex = index;\n continue;\n }\n\n // Message body — or stray content before the first MSH / a body segment\n // severed by a reserved-name boundary, which is kept (never dropped) and\n // surfaces as a NO_MSH_SEGMENT failure entry on flush.\n if (messageLines.length === 0) messageIndex = index;\n messageLines.push(segment);\n }\n\n closeFile(); // flush the final message + batch, and any still-open file header\n\n const publicBatches: Batch[] = batches.map((batch) => {\n const publicBatch: Batch = {\n messages: Object.freeze(batch.messages),\n actualMessageCount: batch.messages.length,\n ...(batch.header !== undefined ? { header: batch.header } : {}),\n ...(batch.trailer !== undefined ? { trailer: batch.trailer } : {}),\n ...(batch.declaredMessageCount !== undefined\n ? { declaredMessageCount: batch.declaredMessageCount }\n : {}),\n };\n return Object.freeze(publicBatch);\n });\n\n const result: BatchSplitResult = {\n messages: Object.freeze(flattened),\n batches: Object.freeze(publicBatches),\n actualBatchCount: publicBatches.length,\n hadEnvelope,\n warnings: Object.freeze(warnings),\n ...(fileHeader !== undefined ? { fileHeader } : {}),\n ...(fileTrailer !== undefined ? { fileTrailer } : {}),\n ...(lastDeclaredBatchCount !== undefined ? { declaredBatchCount: lastDeclaredBatchCount } : {}),\n };\n return Object.freeze(result);\n}\n","/**\n * Public entry point for the `@cosyte/hl7` package.\n *\n * The full public API (parseHL7, defineProfile, helpers, types) is populated\n * in subsequent phases. This stub keeps the module resolvable and typed so\n * downstream tooling (tsup, vitest, tsc) can verify the build/typecheck\n * pipeline end-to-end.\n */\n\n/**\n * Library version string, synced with `package.json#version` at build time\n * by downstream phases. Exported now so consumers (and the type-check\n * pipeline) have at least one symbol to resolve through the `exports` map.\n *\n * @example\n * ```ts\n * import { VERSION } from \"@cosyte/hl7\";\n * console.log(VERSION);\n * ```\n */\nexport const VERSION: string = \"0.0.1\";\n\nexport { parseHL7 } from \"./parser/index.js\";\nexport { Hl7Message } from \"./model/message.js\";\nexport { FATAL_CODES, Hl7ParseError, ProfileDefinitionError } from \"./parser/errors.js\";\nexport type { FatalCode } from \"./parser/errors.js\";\nexport {\n WARNING_CODES,\n mllpFramingStripped,\n fieldWhitespaceTrimmed,\n unknownEscapeSequence,\n unterminatedEscapeSequence,\n timestampFallbackFormat,\n segmentCase,\n extraFields,\n unknownSegment,\n duplicateRequiredSegment,\n encodingMismatch,\n missingRequiredField,\n missingExpectedGroup,\n outOfOrderSegment,\n versionMismatch,\n unknownCharset,\n unsupportedCharset,\n} from \"./parser/warnings.js\";\nexport type { WarningCode, Hl7ParseWarning } from \"./parser/warnings.js\";\n\n// Phase O additive: the frozen HL7 Table-0211 charset registry, so advanced\n// consumers can inspect how an MSH-18 code is treated (decoded vs preserved).\nexport { resolveCharset, canonicalCharset } from \"./parser/charset.js\";\nexport type { CharsetResolution, CharsetTreatment } from \"./parser/charset.js\";\nexport { DEFAULT_ENCODING_CHARACTERS } from \"./parser/delimiters.js\";\nexport type {\n Hl7Position,\n ParseOptions,\n OnWarningCallback,\n Profile,\n EncodingCharacters,\n RawSegment,\n RawField,\n RawRepetition,\n RawComponent,\n} from \"./parser/types.js\";\nexport { BUILTIN_DATE_FALLBACKS, parseDtm, formatDtm, dtmToDate } from \"./parser/dates.js\";\nexport type { DtmParts, DtmPrecision, DtmToDateOptions } from \"./parser/dates.js\";\nexport { unescape, reescape } from \"./parser/escapes.js\";\n\n// Phase 3 structural model — read-path foundation.\nexport { Segment } from \"./model/segment.js\";\nexport { Field } from \"./model/field.js\";\nexport { parsePath, resolvePath } from \"./model/dot-path.js\";\nexport type { DotPath } from \"./model/dot-path.js\";\n\n// Phase 3 typed composites — named exports for the 10 v1 composites\n// (XPN, XAD, CX, CWE, CE, XTN, PL, TS, NM, HD) alongside their parser\n// functions. D-13: these are ALSO re-exported under the `HL7` namespace\n// below so `import { HL7 } from \"@cosyte/hl7\"; type T = HL7.XPN`\n// resolves to the same interface as the named `XPN` import.\nexport type { XPN } from \"./model/types/xpn.js\";\nexport { parseXpn } from \"./model/types/xpn.js\";\nexport type { XAD } from \"./model/types/xad.js\";\nexport { parseXad } from \"./model/types/xad.js\";\nexport type { CX } from \"./model/types/cx.js\";\nexport { parseCx } from \"./model/types/cx.js\";\nexport type { CWE } from \"./model/types/cwe.js\";\nexport { parseCwe } from \"./model/types/cwe.js\";\nexport type { CE } from \"./model/types/ce.js\";\nexport { parseCe } from \"./model/types/ce.js\";\nexport type { XTN } from \"./model/types/xtn.js\";\nexport { parseXtn } from \"./model/types/xtn.js\";\nexport type { PL } from \"./model/types/pl.js\";\nexport { parsePl } from \"./model/types/pl.js\";\nexport type { TS } from \"./model/types/ts.js\";\nexport { parseTs } from \"./model/types/ts.js\";\nexport type { NM } from \"./model/types/nm.js\";\nexport { parseNm } from \"./model/types/nm.js\";\nexport type { SN } from \"./model/types/sn.js\";\nexport { parseSn } from \"./model/types/sn.js\";\nexport type { HD } from \"./model/types/hd.js\";\nexport { parseHd } from \"./model/types/hd.js\";\n\n// Phase 4: XCN composite (11th v1 composite — D-24 option (a)). Used by\n// helpers for `visit.attendingDoctor` / `visit.referringDoctor` (PV1-7/8)\n// and `order.orderedBy` (OBR-16). Structurally XPN + ID prefix + nested HD.\nexport type { XCN } from \"./model/types/xcn.js\";\nexport { parseXcn } from \"./model/types/xcn.js\";\n\n// Phase 3 HL7 namespace re-export (D-13) — `HL7.XPN`, `HL7.XAD`, ..., `HL7.XCN`.\nexport * as HL7 from \"./model/types/namespace.js\";\n\n// Phase 4 named helpers — type-only exports. Runtime behavior lives on\n// `Hl7Message` instance getters (`.meta`, `.patient`, `.visit`) and\n// collection methods (`.observations()`, `.orders()`, `.nextOfKin()`,\n// `.allergies()`, `.diagnoses()`, `.insurance()`). HELPERS-01..07.\nexport type {\n Allergy,\n Appointment,\n AppointmentResource,\n Charge,\n ClinicalDocument,\n Diagnosis,\n Immunization,\n ImmunizationRecordOrigin,\n Insurance,\n Medication,\n MedicationAmount,\n MedicationComponent,\n MedicationContext,\n MedicationRoute,\n MedicationStrength,\n Meta,\n NextOfKin,\n Observation,\n ObservationBase,\n Order,\n OrderTiming,\n Patient,\n RepeatPattern,\n RepeatPatternKind,\n TimingQuantity,\n Visit,\n} from \"./helpers/types.js\";\n\n// Phase 4: `pickMrn` is exposed as a named export so Phase 6 profile override\n// hooks can substitute a profile-aware variant without patching the helper\n// that calls it (D-07/D-08/D-10 default; Phase 6 hook-point).\nexport { pickMrn } from \"./helpers/pick-mrn.js\";\n\n// Roadmap Phase K: patient-identity / merge events. Runtime behavior lives on\n// `Hl7Message.identityEvents()`; the typed views + the event-scoped warning\n// factory are the named exports.\nexport type {\n IdentityEvent,\n IdentityEventKind,\n IdentityParty,\n IdentityRole,\n} from \"./helpers/identity.js\";\nexport { mergeMissingPriorOrSurvivor } from \"./parser/warnings.js\";\n\n// Phase 5: outbound construction + serialization types.\n// D-09: `buildMessage` is a top-level named export, symmetric with `parseHL7`.\n// D-21: `SerializedMessage` is a top-level type export (not under the HL7\n// namespace — that namespace is composite-type territory).\n// The three emit methods (`toString`, `toJSON`, `prettyPrint`) land as\n// instance methods on the already-exported `Hl7Message` class — no new\n// named exports needed for them.\nexport { buildMessage } from \"./builder/build-message.js\";\nexport type { BuildMessageInit } from \"./builder/build-message.js\";\nexport type { SerializedMessage } from \"./serialize/to-json.js\";\n\n// Phase C: ACK / response generation. `buildAck` is the single upstream ACK\n// *content* primitive (`@cosyte/mllp`'s ack-from-hl7 adapts over it);\n// `interpretAck` is the read-side; `detectAckMode` exposes the spec-exact\n// original-vs-enhanced detection. Control vocabulary (Tables 0008/0357/0516/\n// 0155) ships as frozen read-only enums.\nexport { buildAck, detectAckMode } from \"./builder/build-ack.js\";\nexport type { AckErrorDetail, BuildAckOptions } from \"./builder/build-ack.js\";\nexport { interpretAck } from \"./helpers/acknowledgment.js\";\nexport type { Acknowledgment, AckErrorEntry } from \"./helpers/acknowledgment.js\";\nexport {\n ACK_CODES,\n ACK_CONDITIONS,\n downgradePositiveAck,\n ERR_CONDITION_CODES,\n ERR_CONDITION_CODE_SYSTEM,\n ERR_SEVERITIES,\n isPositiveAck,\n} from \"./builder/ack-tables.js\";\nexport type { AckCode, AckCondition, AckMode, ErrSeverity } from \"./builder/ack-tables.js\";\nexport { ackNoCorrelationId } from \"./parser/warnings.js\";\n\n// Phase 6: profile system + built-in vendor profiles.\n// D-26: defineProfile / setDefaultProfile / getDefaultProfile are top-level\n// values; built-ins are exposed under the `profiles` namespace object, not\n// as top-level named exports (`epic` is too generic a name for a top-level\n// export).\nexport { defineProfile, setDefaultProfile, getDefaultProfile, profiles } from \"./profiles/index.js\";\nexport type { DefineProfileOptions, CustomSegmentDefinition } from \"./profiles/index.js\";\n\n// Plan 01 additive: SUPPORTED_DATE_TOKENS re-export so profile authors can\n// introspect valid date-format tokens without reaching into internals.\nexport { SUPPORTED_DATE_TOKENS } from \"./parser/dates.js\";\n\n// Plan 03 additive: KNOWN_SEGMENTS re-export so advanced consumers can\n// inspect the UNKNOWN_SEGMENT detection set (read-only).\nexport { KNOWN_SEGMENTS } from \"./parser/known-segments.js\";\n\n// Phase F: coding-system provenance (HL7 Table 0396, read-only). A frozen\n// acronym→name map plus accessors that answer \"what system does this code\n// CLAIM?\" over CWE/CE — alias-normalized, never validated, unknown surfaced\n// verbatim with `known:false`. No lookup, no network, no bundled codeset.\nexport {\n KNOWN_CODING_SYSTEMS,\n codingSystem,\n codingSystemOf,\n alternateCodingSystemOf,\n} from \"./model/coding-system.js\";\nexport type {\n KnownCodingSystem,\n CodingSystemInfo,\n CodedSystemFields,\n} from \"./model/coding-system.js\";\n\n// Phase G: message-type & structure awareness — a conservative misroute/\n// truncation safety net. `Hl7Message.structure` surfaces the read-side\n// summary; the parser emits an additive `MISSING_EXPECTED_GROUP` warning when\n// a recognized type lacks an expected Required segment group. The expected-\n// group registry + the pure analyzer are exposed read-only for introspection.\nexport {\n MESSAGE_STRUCTURE_DEFINITIONS,\n analyzeMessageStructure,\n} from \"./parser/message-structure.js\";\nexport type {\n ExpectedSegmentGroup,\n MessageStructureDefinition,\n StructureGroup,\n MessageStructure,\n} from \"./parser/message-structure.js\";\n\n// Roadmap Phase L: batch / file envelope splitting. `splitBatch` is a\n// top-level utility (symmetric with `parseHL7`) that demarcates the individual\n// MSH-led messages inside an `[FHS]{[BHS]{MSH…}[BTS]}[FTS]` stream, parses each\n// via parseHL7 (ok / typed-failure entries — a malformed message is isolated,\n// never suppresses siblings), and reconciles the declared BTS-1/FTS-1 counts.\n// The two additive Tier-2 warnings live on the returned result, never on\n// Hl7Message.warnings.\nexport { splitBatch } from \"./parser/batch.js\";\nexport type {\n Batch,\n BatchEnvelopeName,\n BatchEnvelopeSegment,\n BatchMessageEntry,\n BatchSplitResult,\n} from \"./parser/batch.js\";\nexport { batchCountMismatch, batchMissingTrailer } from \"./parser/warnings.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/errors.ts","../src/parser/segments.ts","../src/parser/delimiters.ts","../src/parser/known-segments.ts","../src/parser/warnings.ts","../src/parser/mllp.ts","../src/parser/charset.ts","../src/parser/normalize.ts","../src/parser/escapes.ts","../src/parser/tokenize.ts","../src/parser/message-structure.ts","../src/model/dot-path.ts","../src/serialize/emit-field.ts","../src/text/render.ts","../src/model/types/_shared.ts","../src/model/types/ce.ts","../src/model/types/cwe.ts","../src/model/types/hd.ts","../src/model/types/cx.ts","../src/model/types/nm.ts","../src/model/types/pl.ts","../src/model/types/sn.ts","../src/parser/dates.ts","../src/model/types/ts.ts","../src/model/types/xad.ts","../src/model/types/xcn.ts","../src/model/types/xpn.ts","../src/model/types/xtn.ts","../src/model/field.ts","../src/model/segment.ts","../src/helpers/allergies.ts","../src/helpers/appointments.ts","../src/helpers/charges.ts","../src/helpers/diagnoses.ts","../src/helpers/notes.ts","../src/helpers/observations.ts","../src/helpers/documents.ts","../src/helpers/identity.ts","../src/helpers/immunizations.ts","../src/helpers/insurance.ts","../src/helpers/timing.ts","../src/helpers/medications.ts","../src/helpers/meta.ts","../src/helpers/next-of-kin.ts","../src/helpers/orders.ts","../src/helpers/pick-mrn.ts","../src/helpers/patient.ts","../src/helpers/structure.ts","../src/helpers/visit.ts","../src/serialize/pretty-print.ts","../src/serialize/to-json.ts","../src/serialize/to-string.ts","../src/builder/encode-composite.ts","../src/model/message.ts","../src/profiles/default.ts","../src/parser/index.ts","../src/text/codec.ts","../src/text/index.ts","../src/model/types/namespace.ts","../src/builder/control-id.ts","../src/builder/format-timestamp.ts","../src/builder/build-message.ts","../src/builder/segment-fields.ts","../src/builder/build-adt.ts","../src/builder/build-oru.ts","../src/builder/ack-tables.ts","../src/builder/build-ack.ts","../src/helpers/acknowledgment.ts","../src/profiles/describe.ts","../src/profiles/merge.ts","../src/profiles/validate.ts","../src/profiles/define.ts","../src/profiles/athena.ts","../src/profiles/cerner.ts","../src/profiles/epic.ts","../src/profiles/genericLab.ts","../src/profiles/meditech.ts","../src/profiles/philips.ts","../src/profiles/va.ts","../src/profiles/visage.ts","../src/profiles/index.ts","../src/model/coding-system.ts","../src/parser/batch.ts","../src/conformance/types.ts","../src/conformance/findings.ts","../src/conformance/profile-shape.ts","../src/conformance/validate-against-profile.ts","../src/conformance/index.ts","../src/parser/stream.ts","../src/index.ts"],"names":["snippet","segmentName","DEFAULT_TRUNCATION_CHAR","pad","parseAssigningAuthority","stringOrUndefined","cweOrUndefined","notes","observations","componentAt","fieldSub","buildRoute","typeField","SEGMENT_NAME_RE","scalarField","absentField","resolveTimestamp","repField","compositeField","Buffer","checkCardinality","isEnvelopeName","finalUnterminated"],"mappings":";;;;;;;;;;A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IAAA,MAAM,OAAA,GAAU,eAAe,IAAI,CAAA;AACnC,IAAA,IAAI,OAAA,KAAY,MAAM,MAAM,OAAA;AAE5B,IAAA,iBAAA,GAAoB,YAAA,CAAa,MAAA,GAAS,CAAA,IAAK,IAAA,CAAK,MAAK,KAAM,EAAA;AAAA,EACjE;AACA,EAAA,MAAM,UAAA,GAAa,MAAM,iBAAiB,CAAA;AAC1C,EAAA,IAAI,UAAA,KAAe,MAAM,MAAM,UAAA;AACjC;;;ACtcO,IAAM,OAAA,GAAkB","file":"index.mjs","sourcesContent":["/**\n * Fatal error taxonomy for the `@cosyte/hl7` parser pipeline. Four\n * Tier-3 codes cover every unrecoverable structural failure; anything less\n * severe is a Tier-2 warning (see `./warnings.ts`). `Hl7ParseError` is\n * thrown directly; consumers narrow via the `code` discriminant.\n *\n * `ProfileDefinitionError` is declared here so the error taxonomy is locked\n * before Phase 6 wires profile validation: keeping file ownership clean\n * across phases.\n */\n\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Stable string codes for every Tier-3 fatal the parser may throw. Locked\n * at four codes: anything else MUST be a Tier-2 warning. Consumers narrow\n * on `err.code` to react to specific structural failures.\n *\n * @example\n * ```ts\n * import { parseHL7, FATAL_CODES, Hl7ParseError } from \"@cosyte/hl7\";\n * try {\n * parseHL7(\"\");\n * } catch (err) {\n * if (err instanceof Hl7ParseError && err.code === FATAL_CODES.EMPTY_INPUT) {\n * // handle empty input\n * }\n * }\n * ```\n */\nexport const FATAL_CODES = {\n NO_MSH_SEGMENT: \"NO_MSH_SEGMENT\",\n MSH_TOO_SHORT: \"MSH_TOO_SHORT\",\n INVALID_ENCODING_CHARACTERS: \"INVALID_ENCODING_CHARACTERS\",\n EMPTY_INPUT: \"EMPTY_INPUT\",\n} as const;\n\n/**\n * Discriminant type for `Hl7ParseError.code`. Narrowing a caught error by\n * this code lets consumers write exhaustive `switch` blocks (enabled by the\n * `switch-exhaustiveness-check` lint rule) and guarantees a typo-free\n * comparison against the `FATAL_CODES` registry.\n *\n * @example\n * ```ts\n * import type { FatalCode } from \"@cosyte/hl7\";\n * function describe(code: FatalCode): string {\n * switch (code) {\n * case \"EMPTY_INPUT\":\n * return \"input was empty\";\n * case \"NO_MSH_SEGMENT\":\n * return \"missing MSH\";\n * case \"MSH_TOO_SHORT\":\n * return \"MSH truncated\";\n * case \"INVALID_ENCODING_CHARACTERS\":\n * return \"bad MSH-1/MSH-2\";\n * }\n * }\n * ```\n */\nexport type FatalCode = (typeof FATAL_CODES)[keyof typeof FATAL_CODES];\n\n/**\n * Thrown by `parseHL7` when the input violates one of the 4 unrecoverable\n * Tier-3 structural rules (missing MSH, truncated MSH, invalid encoding\n * characters, or empty input). Carries positional context plus a short\n * snippet of the offending input so consumers can log actionable errors.\n *\n * @remarks\n * Snippets may contain PHI when parsing real clinical messages: redact at\n * the call site if required by your compliance posture. The library does\n * not redact snippets itself.\n *\n * @example\n * ```ts\n * import { parseHL7, Hl7ParseError } from \"@cosyte/hl7\";\n * try {\n * parseHL7(\"\");\n * } catch (err) {\n * if (err instanceof Hl7ParseError && err.code === \"EMPTY_INPUT\") {\n * // handle empty input: err.position, err.snippet available\n * }\n * }\n * ```\n */\nexport class Hl7ParseError extends Error {\n public readonly code: FatalCode;\n public readonly position: Hl7Position;\n public readonly snippet: string;\n\n /**\n * Construct a new `Hl7ParseError`. All four fields are required so every\n * thrower populates full positional context per the TOL-02 requirement.\n *\n * @internal\n */\n public constructor(code: FatalCode, message: string, position: Hl7Position, snippet: string) {\n super(message);\n this.name = \"Hl7ParseError\";\n this.code = code;\n this.position = position;\n this.snippet = snippet;\n }\n}\n\n/**\n * Thrown by `defineProfile()` and profile-validation code (Phase 6) when a\n * profile definition is structurally invalid: e.g. references an undefined\n * parent, declares a malformed custom segment, or includes an unsupported\n * date format. Declared in Phase 2 so the error taxonomy is locked before\n * Phase 6 lands; callers may optionally supply the offending profile name\n * for better diagnostics.\n *\n * @example\n * ```ts\n * import { ProfileDefinitionError } from \"@cosyte/hl7\";\n * throw new ProfileDefinitionError(\n * \"Unknown parent profile: epic-v7\",\n * \"my-epic-extension\",\n * );\n * ```\n */\nexport class ProfileDefinitionError extends Error {\n public readonly profileName: string | undefined;\n\n /**\n * Construct a new `ProfileDefinitionError`. `profileName` is optional so\n * Phase 6 callers may omit it when the offending profile cannot be named\n * (e.g. during initial validation before a name is parsed).\n *\n * @internal\n */\n public constructor(message: string, profileName?: string) {\n super(message);\n this.name = \"ProfileDefinitionError\";\n this.profileName = profileName;\n }\n}\n","/**\n * Segment-split stage for the `@cosyte/hl7` parser pipeline. After\n * input normalization (line endings unified to `\\r`), this module turns the\n * single-string input into an ordered array of segment strings with stable\n * positions. Purely mechanical: no HL7 semantics are evaluated here. MSH\n * detection, delimiter discovery, and field tokenization all live in sibling\n * modules (`delimiters.ts`, `tokenize.ts`).\n *\n * The stage follows the Postel-Law \"liberal parser\" posture: preserves empty\n * middle segments (so that `segmentIndex` stays stable for later warnings)\n * and drops a single trailing `\\r` (so that the universally-seen HL7 \"end\n * with CR\" convention does not produce a spurious empty final segment).\n */\n\n/**\n * Splits a normalized (line-ending = `\\r`) HL7 input string into an ordered\n * array of segment strings. Preserves original order including repeated,\n * empty, and Z-segments. A single trailing `\\r` does NOT create a final\n * empty segment; a MIDDLE empty segment (two consecutive `\\r`) IS preserved\n * so downstream `segmentIndex` positions stay stable against the original\n * input.\n *\n * @example\n * ```ts\n * import { splitSegments } from \"@cosyte/hl7\";\n * splitSegments(\"MSH|A\\rPID|1\\r\"); // [\"MSH|A\", \"PID|1\"]\n * splitSegments(\"MSH|A\\r\\rPID|1\"); // [\"MSH|A\", \"\", \"PID|1\"]\n * ```\n */\nexport function splitSegments(normalized: string): readonly string[] {\n // Strip a single trailing \\r only (preserves middle empty segments).\n const trimmed = normalized.endsWith(\"\\r\") ? normalized.slice(0, -1) : normalized;\n if (trimmed.length === 0) return [];\n return trimmed.split(\"\\r\");\n}\n\n/**\n * Build a short, fixed-length snippet of a segment string for attaching to\n * fatal-error context. Truncates to 40 chars with a trailing ellipsis so the\n * thrown `Hl7ParseError.snippet` stays bounded regardless of input size.\n *\n * @example\n * ```ts\n * import { snippet } from \"@cosyte/hl7\";\n * snippet(\"MSH|^~\\\\&|APP|FAC\"); // \"MSH|^~\\\\&|APP|FAC\"\n * ```\n *\n * @internal\n */\nexport function snippet(segment: string): string {\n return segment.length > 40 ? segment.slice(0, 40) + \"\\u2026\" : segment;\n}\n","/**\n * MSH delimiter-discovery stage for the `@cosyte/hl7` parser pipeline.\n * Reads the encoding characters (MSH-1 field separator + MSH-2 component /\n * repetition / escape / subcomponent, and the optional v2.7+ truncation\n * character) from the first segment and throws a Tier-3 `Hl7ParseError` if\n * the structural preconditions fail. Downstream stages (`tokenize.ts`)\n * consume the returned `EncodingCharacters` verbatim and never re-derive\n * them, which keeps custom-delimiter behaviour (PARSE-02) consistent across\n * the pipeline.\n *\n * Only three of the four Tier-3 fatal codes originate here,\n * `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`, `INVALID_ENCODING_CHARACTERS`. The\n * fourth, `EMPTY_INPUT`, is owned by the `normalize.ts` preprocessing stage.\n */\n\nimport { FATAL_CODES, Hl7ParseError } from \"./errors.js\";\nimport { snippet } from \"./segments.js\";\nimport type { EncodingCharacters } from \"./types.js\";\n\n/**\n * The HL7 default 5-tuple of encoding characters used when a message does\n * not override them via MSH-1 / MSH-2. Re-used by downstream stages (Plan 04\n * escape map, Plan 06 `parseHL7`) as a synthetic-message fallback.\n *\n * @example\n * ```ts\n * import { DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * DEFAULT_ENCODING_CHARACTERS.field; // \"|\"\n * ```\n */\nexport const DEFAULT_ENCODING_CHARACTERS: EncodingCharacters = {\n field: \"|\",\n component: \"^\",\n repetition: \"~\",\n escape: \"\\\\\",\n subcomponent: \"&\",\n};\n\n/**\n * Extract the HL7 encoding characters from the first segment of a message.\n *\n * Accepts a 4-character MSH-2 (HL7 v2.1–v2.6: component/repetition/escape/\n * subcomponent) or a 5-character MSH-2 (HL7 v2.7+: adds a truncation\n * character; spec default `#`). Both shapes are spec-conformant and must not\n * fatal.\n *\n * Throws `Hl7ParseError` with one of three Tier-3 fatal codes when the\n * structural preconditions fail:\n *\n * - `NO_MSH_SEGMENT`: first segment does not start with `MSH`.\n * - `MSH_TOO_SHORT`: MSH has fewer than 8 chars (cannot contain the\n * encoding-characters field).\n * - `INVALID_ENCODING_CHARACTERS`: MSH-1 is whitespace; MSH-2 is not\n * 4 or 5 distinct non-whitespace chars; or the field separator appears\n * among the MSH-2 encoding chars.\n *\n * @example\n * ```ts\n * import { readDelimiters } from \"@cosyte/hl7\";\n * const v25 = readDelimiters(\"MSH|^~\\\\&|APP|FAC|...\");\n * v25.truncation; // undefined\n * const v27 = readDelimiters(\"MSH|^~\\\\&#|APP|FAC|...\");\n * v27.truncation; // \"#\"\n * ```\n */\nexport function readDelimiters(firstSegment: string): EncodingCharacters {\n const fatalPosition = { segmentIndex: 0 };\n const snip = snippet(firstSegment);\n\n if (firstSegment.length < 3 || firstSegment.slice(0, 3) !== \"MSH\") {\n throw new Hl7ParseError(\n FATAL_CODES.NO_MSH_SEGMENT,\n \"First segment is not MSH: HL7 v2 messages must begin with an MSH segment.\",\n fatalPosition,\n snip,\n );\n }\n\n // Need \"MSH\" + field separator + 4 encoding chars = 8 chars minimum\n // (4-char MSH-2 is the v2.1–v2.6 floor; a 5-char v2.7+ MSH-2 needs 9).\n if (firstSegment.length < 8) {\n throw new Hl7ParseError(\n FATAL_CODES.MSH_TOO_SHORT,\n \"MSH segment is truncated: cannot read encoding characters.\",\n fatalPosition,\n snip,\n );\n }\n\n const field = firstSegment.charAt(3);\n\n if (/\\s/u.test(field)) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"MSH-1 field separator is whitespace: refusing to parse.\",\n fatalPosition,\n snip,\n );\n }\n\n // MSH-2 spans from char 4 to the next field separator. If no terminator\n // appears, MSH-2 runs to end-of-segment. This lets v2.7+ 5-char MSH-2\n // (e.g. `^~\\&#`) parse without hard-coding a slice length.\n const nextFieldSep = firstSegment.indexOf(field, 4);\n const msh2End = nextFieldSep === -1 ? firstSegment.length : nextFieldSep;\n const encodingField = firstSegment.slice(4, msh2End);\n const chars = [...encodingField];\n\n if (chars.length !== 4 && chars.length !== 5) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n `MSH-2 encoding characters must be 4 (v2.1–v2.6) or 5 (v2.7+ adds truncation) characters (got ${String(chars.length)}).`,\n fatalPosition,\n snip,\n );\n }\n if (new Set(chars).size !== chars.length) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n `MSH-2 encoding characters must be ${String(chars.length)} distinct characters.`,\n fatalPosition,\n snip,\n );\n }\n if (chars.some((c) => /\\s/u.test(c))) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"MSH-2 encoding characters must not contain whitespace.\",\n fatalPosition,\n snip,\n );\n }\n if (chars.includes(field)) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"Field separator must not appear among the MSH-2 encoding characters.\",\n fatalPosition,\n snip,\n );\n }\n\n // `noUncheckedIndexedAccess` requires explicit narrowing even though the\n // length/distinct-count checks above guarantee these are defined.\n const component = chars[0];\n const repetition = chars[1];\n const escape = chars[2];\n const subcomponent = chars[3];\n if (\n component === undefined ||\n repetition === undefined ||\n escape === undefined ||\n subcomponent === undefined\n ) {\n throw new Hl7ParseError(\n FATAL_CODES.INVALID_ENCODING_CHARACTERS,\n \"MSH-2 encoding characters could not be read.\",\n fatalPosition,\n snip,\n );\n }\n\n const truncation = chars.length === 5 ? chars[4] : undefined;\n return truncation === undefined\n ? { field, component, repetition, escape, subcomponent }\n : { field, component, repetition, escape, subcomponent, truncation };\n}\n","/**\n * Registry of standard HL7 v2 segment names used for UNKNOWN_SEGMENT\n * warning detection. Any segment name NOT in this set AND NOT declared in\n * the active profile's customSegments map emits UNKNOWN_SEGMENT per D-31.\n *\n * Derived from HL7 v2.5.1 chapters 3-7 (core message segments, order/result\n * tree, financial tree, scheduling, master files). Z-segments\n * (`/^Z[A-Z0-9]{2}$/`) are NOT in this set: they're always user-defined\n * and must be declared in a profile to avoid the warning.\n *\n * Frozen as `ReadonlySet<string>` for O(1) lookup without mutation risk.\n */\n\n/**\n * Frozen set of every standard HL7 v2 segment name the library recognises.\n * Consumers parsing any segment whose name is neither in this set nor\n * declared by the active profile will see `UNKNOWN_SEGMENT` in\n * `msg.warnings`.\n *\n * @example\n * ```ts\n * import { KNOWN_SEGMENTS } from \"@cosyte/hl7\";\n * console.log(KNOWN_SEGMENTS.has(\"PID\")); // true\n * console.log(KNOWN_SEGMENTS.has(\"ZPI\")); // false\n * ```\n */\nexport const KNOWN_SEGMENTS: ReadonlySet<string> = new Set<string>([\n // Core message header + event + acknowledgement\n \"MSH\",\n \"MSA\",\n \"EVN\",\n \"ERR\",\n \"SFT\",\n // Patient identifiers + demographics + visit\n \"PID\",\n \"PD1\",\n \"MRG\",\n \"PV1\",\n \"PV2\",\n \"PDA\",\n \"PDC\",\n \"PEO\",\n \"DB1\",\n // Next of kin / guarantor / contacts / insurance\n \"NK1\",\n \"GT1\",\n \"IN1\",\n \"IN2\",\n \"IN3\",\n \"ACC\",\n // Allergy / diagnosis / problem / history / goal\n \"AL1\",\n \"DG1\",\n \"PRB\",\n \"IAM\",\n \"FAM\",\n \"GOL\",\n \"PR1\",\n // Observation / order / result / timing\n \"OBR\",\n \"OBX\",\n \"ORC\",\n \"SPM\",\n \"TQ1\",\n \"TQ2\",\n \"NTE\",\n \"UB1\",\n \"UB2\",\n \"FT1\",\n // Pharmacy / treatment\n \"RXA\",\n \"RXC\",\n \"RXD\",\n \"RXE\",\n \"RXG\",\n \"RXO\",\n \"RXR\",\n \"RXV\",\n // Scheduling\n \"SCH\",\n \"AIG\",\n \"AIL\",\n \"AIP\",\n \"AIS\",\n \"ARQ\",\n \"APR\",\n \"RGS\",\n // Document / master files\n \"TXA\",\n \"MFE\",\n \"MFI\",\n \"MFA\",\n \"MCP\",\n \"LDP\",\n \"LCH\",\n \"LOC\",\n \"LRL\",\n \"LCC\",\n // Roles / staff / organizations\n \"ROL\",\n \"STF\",\n \"PRA\",\n \"EDU\",\n \"CER\",\n \"CTD\",\n \"CTI\",\n \"ORG\",\n \"PRC\",\n \"PRD\",\n // Query + response\n \"QAK\",\n \"QPD\",\n \"QRF\",\n \"QRI\",\n \"QID\",\n \"RDF\",\n \"RDT\",\n \"DSC\",\n \"DSP\",\n \"EQL\",\n \"OMC\",\n // Batch / header envelope (out-of-scope per project OOS but valid tokens)\n \"FHS\",\n \"BHS\",\n \"BTS\",\n \"FTS\",\n // Other legacy / clinical study\n \"CSR\",\n \"CSP\",\n \"CSS\",\n]);\n","/**\n * Tier-2 warning registry and factories for the `@cosyte/hl7` parser\n * pipeline. Consumers compare `warning.code === WARNING_CODES.<CODE>` to\n * narrow and react; the parser uses the factories here to construct every\n * warning it emits so that messages, payload shape, and positional context\n * stay consistent across stages.\n */\n\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Stable string codes for every Tier-2 warning the parser may emit. The\n * registry is frozen via `as const` so TypeScript infers the exact string\n * literal union for `WarningCode`: there is zero runtime cost and no\n * magic-string comparisons for consumers.\n *\n * @example\n * ```ts\n * import { parseHL7, WARNING_CODES } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * if (msg.warnings.some((w) => w.code === WARNING_CODES.MLLP_FRAMING_STRIPPED)) {\n * // handle MLLP-wrapped input\n * }\n * ```\n */\nexport const WARNING_CODES = {\n MLLP_FRAMING_STRIPPED: \"MLLP_FRAMING_STRIPPED\",\n FIELD_WHITESPACE_TRIMMED: \"FIELD_WHITESPACE_TRIMMED\",\n UNKNOWN_ESCAPE_SEQUENCE: \"UNKNOWN_ESCAPE_SEQUENCE\",\n TIMESTAMP_FALLBACK_FORMAT: \"TIMESTAMP_FALLBACK_FORMAT\",\n SEGMENT_CASE: \"SEGMENT_CASE\",\n EXTRA_FIELDS: \"EXTRA_FIELDS\",\n UNKNOWN_SEGMENT: \"UNKNOWN_SEGMENT\",\n DUPLICATE_REQUIRED_SEGMENT: \"DUPLICATE_REQUIRED_SEGMENT\",\n ENCODING_MISMATCH: \"ENCODING_MISMATCH\",\n MISSING_REQUIRED_FIELD: \"MISSING_REQUIRED_FIELD\",\n MISSING_EXPECTED_GROUP: \"MISSING_EXPECTED_GROUP\",\n OUT_OF_ORDER_SEGMENT: \"OUT_OF_ORDER_SEGMENT\",\n VERSION_MISMATCH: \"VERSION_MISMATCH\",\n UNKNOWN_CHARSET: \"UNKNOWN_CHARSET\",\n UNSUPPORTED_CHARSET: \"UNSUPPORTED_CHARSET\",\n ACK_NO_CORRELATION_ID: \"ACK_NO_CORRELATION_ID\",\n MERGE_MISSING_PRIOR_OR_SURVIVOR: \"MERGE_MISSING_PRIOR_OR_SURVIVOR\",\n BATCH_COUNT_MISMATCH: \"BATCH_COUNT_MISMATCH\",\n BATCH_MISSING_TRAILER: \"BATCH_MISSING_TRAILER\",\n UNTERMINATED_STREAM_MESSAGE: \"UNTERMINATED_STREAM_MESSAGE\",\n} as const;\n\n/**\n * Discriminant type for `Hl7ParseWarning.code`. Narrowing a warning by this\n * code lets consumers write exhaustive `switch` blocks (enabled by the\n * `switch-exhaustiveness-check` lint rule) and guarantees a typo-free\n * comparison against the `WARNING_CODES` registry.\n *\n * @example\n * ```ts\n * import type { Hl7ParseWarning, WarningCode } from \"@cosyte/hl7\";\n * function describe(w: Hl7ParseWarning): string {\n * const code: WarningCode = w.code;\n * switch (code) {\n * case \"MLLP_FRAMING_STRIPPED\":\n * return \"stripped MLLP framing\";\n * default:\n * return `warning: ${code}`;\n * }\n * }\n * ```\n */\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Data shape for every Tier-2 warning emitted by the parser. Warnings are\n * plain data (distinct from `Hl7ParseError`, which is a thrown `Error`\n * subclass) so they can be safely accumulated into\n * `Hl7Message.warnings` and passed to `onWarning` callbacks.\n *\n * @example\n * ```ts\n * import type { Hl7ParseWarning } from \"@cosyte/hl7\";\n * const w: Hl7ParseWarning = {\n * code: \"UNKNOWN_SEGMENT\",\n * message: \"Unknown segment: ZZZ\",\n * position: { segmentIndex: 4 },\n * };\n * ```\n */\nexport interface Hl7ParseWarning {\n readonly code: WarningCode;\n readonly message: string;\n readonly position: Hl7Position;\n}\n\n/**\n * Build a `MLLP_FRAMING_STRIPPED` warning. Emitted once per parse when the\n * preprocessor detects and removes MLLP framing bytes (`0x0B` / `0x1C` /\n * trailing `0x0D`) from the input.\n *\n * @example\n * ```ts\n * import { mllpFramingStripped } from \"@cosyte/hl7\";\n * const w = mllpFramingStripped({ segmentIndex: 0 });\n * ```\n */\nexport function mllpFramingStripped(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.MLLP_FRAMING_STRIPPED,\n message: \"MLLP framing bytes (VT/FS/CR) were stripped from the input.\",\n position,\n };\n}\n\n/**\n * Build a `FIELD_WHITESPACE_TRIMMED` warning. Emitted when the parser trims\n * leading or trailing whitespace from a field value (the `trimFields`\n * option, on by default). The message carries only the leading/trailing\n * character **counts**: NEVER the field value itself (before or after\n * trimming): so no PHI is exposed; the trimmed value is still preserved\n * verbatim in the parsed output.\n *\n * @example\n * ```ts\n * import { fieldWhitespaceTrimmed } from \"@cosyte/hl7\";\n * const w = fieldWhitespaceTrimmed({ segmentIndex: 1, fieldIndex: 5 }, 2, 1);\n * ```\n */\nexport function fieldWhitespaceTrimmed(\n position: Hl7Position,\n leadingCount: number,\n trailingCount: number,\n): Hl7ParseWarning {\n const parts: string[] = [];\n if (leadingCount > 0) parts.push(`${String(leadingCount)} leading`);\n if (trailingCount > 0) parts.push(`${String(trailingCount)} trailing`);\n const summary = parts.length > 0 ? parts.join(\" + \") : \"0\";\n return {\n code: WARNING_CODES.FIELD_WHITESPACE_TRIMMED,\n message: `Field had ${summary} whitespace character(s) trimmed.`,\n position,\n };\n}\n\n/**\n * The standard HL7 v2 escape-identifier letters/prefixes (§2.7): the\n * single-character escapes (`F S T R E X C M Z H N`) and the `.`-prefixed\n * formatting escapes. These are structural HL7 grammar, not sender content,\n * safe to name in a warning message even when the escape body as a whole is\n * unrecognized (e.g. a malformed `\\Cxx\\` or a vendor `\\Z...\\`).\n *\n * @internal\n */\nconst KNOWN_ESCAPE_TYPE_LETTERS: ReadonlySet<string> = new Set([\n \"F\",\n \"S\",\n \"T\",\n \"R\",\n \"E\",\n \"X\",\n \"C\",\n \"M\",\n \"Z\",\n \"H\",\n \"N\",\n]);\n\n/**\n * Identify the structural \"type\" of an escape-sequence body for PHI-safe\n * warning reporting: the leading character when it is one of the standard\n * HL7 escape-identifier letters (`F S T R E X C M Z H N`) or a `.`-prefixed\n * formatting escape, `null` otherwise. A `null` result means the body is not\n * recognizable HL7 escape grammar at all (i.e. it is untrusted field text\n * that happened to follow a stray escape character) and must not be named in\n * a warning.\n *\n * @internal\n */\nexport function classifyEscapeType(body: string): string | null {\n if (body.startsWith(\".\")) return \".\";\n const first = body.charAt(0);\n return KNOWN_ESCAPE_TYPE_LETTERS.has(first) ? first : null;\n}\n\n/**\n * Build an `UNKNOWN_ESCAPE_SEQUENCE` warning for a **terminated** escape\n * sequence (`\\..\\`) whose body is not a recognized HL7 escape. The message\n * NEVER embeds the escape body: only its length and, when the body's first\n * character is a recognized HL7 escape-identifier letter (structural HL7\n * grammar, not PHI: e.g. `Z` for a vendor escape, `.` for a formatting\n * escape), that single letter. A body that doesn't start with a known escape\n * letter is untrusted field text and names no character at all. The sequence\n * itself is still preserved verbatim in the parsed output: only the WARNING\n * message is PHI-safe.\n *\n * @example\n * ```ts\n * import { unknownEscapeSequence } from \"@cosyte/hl7\";\n * const w = unknownEscapeSequence({ segmentIndex: 2, fieldIndex: 3 }, \"Z99\");\n * // message: `Unknown HL7 escape sequence of type \"Z\" (3 chars) preserved verbatim.`\n * ```\n */\nexport function unknownEscapeSequence(position: Hl7Position, body: string): Hl7ParseWarning {\n const type = classifyEscapeType(body);\n const typeClause = type !== null ? ` of type \"${type}\"` : \"\";\n return {\n code: WARNING_CODES.UNKNOWN_ESCAPE_SEQUENCE,\n message: `Unknown HL7 escape sequence${typeClause} (${String(body.length)} chars) preserved verbatim.`,\n position,\n };\n}\n\n/**\n * Build an `UNKNOWN_ESCAPE_SEQUENCE` warning for an **unterminated** escape\n * (an escape character with no closing partner before end-of-input). The\n * \"body\" in this case is the entire remainder of the field, so the message\n * carries NEITHER the body NOR its length (the length of a truncated tail is\n * itself derivable field-shape information): just the fact that an\n * unterminated escape was found, and the position. The remainder is still\n * preserved verbatim in the parsed output.\n *\n * @example\n * ```ts\n * import { unterminatedEscapeSequence } from \"@cosyte/hl7\";\n * const w = unterminatedEscapeSequence({ segmentIndex: 2, fieldIndex: 3 });\n * // message: `Unterminated HL7 escape sequence preserved verbatim.`\n * ```\n */\nexport function unterminatedEscapeSequence(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNKNOWN_ESCAPE_SEQUENCE,\n message: \"Unterminated HL7 escape sequence preserved verbatim.\",\n position,\n };\n}\n\n/**\n * Build a `TIMESTAMP_FALLBACK_FORMAT` warning. Emitted when a date/time\n * field could not be parsed with its primary (strict HL7) format but a\n * fallback format from `ParseOptions.dateFormats` or built-in fallbacks\n * succeeded.\n *\n * @example\n * ```ts\n * import { timestampFallbackFormat } from \"@cosyte/hl7\";\n * const w = timestampFallbackFormat(\n * { segmentIndex: 1, fieldIndex: 7 },\n * \"YYYY-MM-DD\",\n * );\n * ```\n */\nexport function timestampFallbackFormat(\n position: Hl7Position,\n matchedFormat: string,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.TIMESTAMP_FALLBACK_FORMAT,\n message: `Timestamp parsed with fallback format \"${matchedFormat}\" (not the strict HL7 format).`,\n position,\n };\n}\n\n/**\n * Build a `SEGMENT_CASE` warning. Emitted when a segment identifier is not\n * all-uppercase (e.g. `pid` instead of `PID`). The parser accepts the\n * segment; the warning alerts consumers to non-conforming senders.\n *\n * @example\n * ```ts\n * import { segmentCase } from \"@cosyte/hl7\";\n * const w = segmentCase({ segmentIndex: 3 }, \"pid\");\n * ```\n */\nexport function segmentCase(position: Hl7Position, observed: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.SEGMENT_CASE,\n message: `Segment identifier \"${observed}\" is not uppercase; normalized to \"${observed.toUpperCase()}\".`,\n position,\n };\n}\n\n/**\n * Build an `EXTRA_FIELDS` warning. Emitted when a segment contains more\n * fields than the profile definition (or HL7 spec) declares: the extras\n * are preserved on `RawSegment.fields` but flagged for consumers.\n *\n * @example\n * ```ts\n * import { extraFields } from \"@cosyte/hl7\";\n * const w = extraFields({ segmentIndex: 4 }, \"PID\", 3);\n * ```\n */\nexport function extraFields(\n position: Hl7Position,\n segmentName: string,\n extraCount: number,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.EXTRA_FIELDS,\n message: `Segment \"${segmentName}\" has ${String(extraCount)} more field(s) than the profile declares.`,\n position,\n };\n}\n\n/**\n * Build an `UNKNOWN_SEGMENT` warning. Emitted when a segment identifier is\n * not in the HL7 spec's standard set and not registered in the active\n * profile's `customSegments`.\n *\n * @example\n * ```ts\n * import { unknownSegment } from \"@cosyte/hl7\";\n * const w = unknownSegment({ segmentIndex: 7 }, \"ZZZ\");\n * ```\n */\nexport function unknownSegment(position: Hl7Position, segmentName: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNKNOWN_SEGMENT,\n message: `Unknown segment \"${segmentName}\": not in HL7 spec and no profile claim.`,\n position,\n };\n}\n\n/**\n * Build a `DUPLICATE_REQUIRED_SEGMENT` warning. Emitted when a segment the\n * profile marks as singleton appears more than once (e.g. two `MSH`\n * segments). The parser keeps both; the warning alerts the consumer to\n * potential sender bugs.\n *\n * @example\n * ```ts\n * import { duplicateRequiredSegment } from \"@cosyte/hl7\";\n * const w = duplicateRequiredSegment({ segmentIndex: 1 }, \"MSH\");\n * ```\n */\nexport function duplicateRequiredSegment(\n position: Hl7Position,\n segmentName: string,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.DUPLICATE_REQUIRED_SEGMENT,\n message: `Required singleton segment \"${segmentName}\" appears more than once.`,\n position,\n };\n}\n\n/**\n * Build an `ENCODING_MISMATCH` warning. Emitted when the MSH-2 encoding\n * characters declared by the sender do not match what the parser observed\n * downstream (e.g. the sender declares `^~\\&` but uses `!@#$` as actual\n * separators in later segments).\n *\n * @example\n * ```ts\n * import { encodingMismatch } from \"@cosyte/hl7\";\n * const w = encodingMismatch({ segmentIndex: 0 }, \"MSH-2 declares ^~\\\\& but segment used !@#$\");\n * ```\n */\nexport function encodingMismatch(position: Hl7Position, detail: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.ENCODING_MISMATCH,\n message: `Encoding mismatch: ${detail}`,\n position,\n };\n}\n\n/**\n * Build a `MISSING_REQUIRED_FIELD` warning. Emitted when a field the active\n * profile marks as required is empty or missing. Distinct from the\n * `NO_MSH_SEGMENT` fatal, which escalates a missing MSH altogether.\n *\n * @example\n * ```ts\n * import { missingRequiredField } from \"@cosyte/hl7\";\n * const w = missingRequiredField({ segmentIndex: 0, fieldIndex: 3 }, \"MSH\", 3);\n * ```\n */\nexport function missingRequiredField(\n position: Hl7Position,\n segmentName: string,\n fieldIndex: number,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.MISSING_REQUIRED_FIELD,\n message: `Required field ${segmentName}-${String(fieldIndex)} is missing or empty.`,\n position,\n };\n}\n\n/**\n * Build a `MISSING_EXPECTED_GROUP` warning (roadmap Phase G). Emitted once per\n * absent Required segment group when the message's (MSH-9.1, MSH-9.2) type is\n * one the structure safety net recognizes and an expected group is entirely\n * missing: e.g. an `ORU^R01` carrying no `OBR`/`OBX` result group, the\n * signature of a truncated or misrouted feed. Tier-2 and additive: lenient\n * parse never throws on it, `strict` mode may promote it. The message carries\n * only the structural fact (message type, group name, anchor segment names),\n * NEVER a field value, so no PHI is exposed. `position` references MSH-9.\n *\n * @example\n * ```ts\n * import { missingExpectedGroup } from \"@cosyte/hl7\";\n * const w = missingExpectedGroup(\n * { segmentIndex: 0, fieldIndex: 9 },\n * \"ORU^R01\",\n * \"result\",\n * [\"OBR\", \"OBX\"],\n * );\n * ```\n */\nexport function missingExpectedGroup(\n position: Hl7Position,\n messageType: string,\n groupName: string,\n anchorSegments: readonly string[],\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.MISSING_EXPECTED_GROUP,\n message:\n `Message type \"${messageType}\" is missing its expected \"${groupName}\" segment group ` +\n `(no ${anchorSegments.join(\"/\")}); message may be truncated or misrouted.`,\n position,\n };\n}\n\n/**\n * Build an `OUT_OF_ORDER_SEGMENT` warning. Emitted when a segment appears\n * outside the order the active profile declares (e.g. `EVN` appearing\n * before `MSH` in a typical ADT message).\n *\n * @example\n * ```ts\n * import { outOfOrderSegment } from \"@cosyte/hl7\";\n * const w = outOfOrderSegment({ segmentIndex: 2 }, \"EVN\");\n * ```\n */\nexport function outOfOrderSegment(position: Hl7Position, segmentName: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.OUT_OF_ORDER_SEGMENT,\n message: `Segment \"${segmentName}\" appears out of the order declared by the active profile.`,\n position,\n };\n}\n\n/**\n * Build a `VERSION_MISMATCH` warning. Emitted when MSH-12 declares an HL7\n * version that does not match what the active profile or `ParseOptions`\n * expected.\n *\n * @example\n * ```ts\n * import { versionMismatch } from \"@cosyte/hl7\";\n * const w = versionMismatch({ segmentIndex: 0, fieldIndex: 12 }, \"2.9\", \"2.5\");\n * ```\n */\nexport function versionMismatch(\n position: Hl7Position,\n declared: string,\n expected: string,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.VERSION_MISMATCH,\n message: `HL7 version mismatch: message declares \"${declared}\", expected \"${expected}\".`,\n position,\n };\n}\n\n/**\n * Build an `UNKNOWN_CHARSET` warning. Emitted when MSH-18 (or an\n * `options.charset` override) declares a value that is **not a recognized HL7\n * Table-0211 character set**. The parser never guesses an encoding: it reads the\n * raw bytes as `latin1` (a 1:1 byte mapping) so single-byte content stays\n * recoverable, rather than corrupting it with replacement characters. The\n * message carries the charset code only, never a decoded field value, so no\n * PHI is exposed.\n *\n * @example\n * ```ts\n * import { unknownCharset } from \"@cosyte/hl7\";\n * const w = unknownCharset({ segmentIndex: 0, fieldIndex: 18 }, \"ISO IR 999\");\n * ```\n */\nexport function unknownCharset(position: Hl7Position, requested: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNKNOWN_CHARSET,\n message: `Unrecognized character set \"${requested}\"; not decoded, bytes read as latin1.`,\n position,\n };\n}\n\n/**\n * Build an `UNSUPPORTED_CHARSET` warning. Emitted when a **recognized**\n * Table-0211 character set is not decoded into text: either because this parser\n * does not decode it (the multibyte / ISO-2022-switched East-Asian sets: JIS,\n * GB 18030, KS X 1001, CNS 11643, BIG-5: and the wide Unicode transforms\n * UTF-16 / UTF-32), or because a strict decode of a decodable set **failed** (a\n * byte invalid / undefined for the declared set, or an ICU build lacking the\n * label). In every case the raw bytes are read as `latin1`, never guessed at, so\n * the parser does not emit replacement-char-corrupted text. Single-byte content\n * stays byte-recoverable; multibyte content is best-effort (a content byte can\n * coincide with a structural delimiter: see the parser's known-limitations).\n * The switch escapes (`\\Cxxyy\\` / `\\Mxxyyzz\\`) are recognized and preserved by\n * the escape layer; full stateful decoding is a documented non-goal. The message\n * carries the charset code only, never a decoded field value, so no PHI is\n * exposed.\n *\n * @example\n * ```ts\n * import { unsupportedCharset } from \"@cosyte/hl7\";\n * const w = unsupportedCharset({ segmentIndex: 0, fieldIndex: 18 }, \"ISO IR87\");\n * ```\n */\nexport function unsupportedCharset(position: Hl7Position, code: string): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNSUPPORTED_CHARSET,\n message: `Character set \"${code}\" was not decoded; bytes read as latin1.`,\n position,\n };\n}\n\n/**\n * Build an `ACK_NO_CORRELATION_ID` warning. Emitted by `buildAck` (Phase C),\n * not by the parser: the inbound message carried no MSH-10 message control ID,\n * so the generated ACK leaves MSA-2 empty and, when a positive accept was\n * requested, downgrades it to an error code rather than fabricating an\n * unverifiable `AA`/`CA`. The `position` references the inbound MSH segment.\n * The message NEVER echoes a PHI value: only the structural fact.\n *\n * @example\n * ```ts\n * import { buildAck, WARNING_CODES } from \"@cosyte/hl7\";\n * const ack = buildAck(inbound, { code: \"AA\" }); // inbound has no MSH-10\n * ack.warnings.some((w) => w.code === WARNING_CODES.ACK_NO_CORRELATION_ID); // true\n * ```\n */\nexport function ackNoCorrelationId(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.ACK_NO_CORRELATION_ID,\n message:\n \"Inbound message has no MSH-10 control ID; ACK MSA-2 left empty and any \" +\n \"positive accept downgraded to an error code (no fabricated AA/CA).\",\n position,\n };\n}\n\n/**\n * Build a `MERGE_MISSING_PRIOR_OR_SURVIVOR` warning (roadmap Phase K). Emitted\n * by `identityEvents()` (a read-side helper: it attaches to the returned\n * `IdentityEvent.warnings`, never to `Hl7Message.warnings`) when a merge/move\n * trigger event (A18/A34/A35/A36/A39/A40/A41/A42/A43/A44) is missing one side\n * of the spec-mandated MRG (prior) → PID (surviving) pair: or when that side\n * carries no usable identity field: no MRG segment in the patient group, no\n * PID for an orphaned MRG, or a PID/MRG whose identifier, account, and visit\n * fields are all empty or version-gated (a v2.7+ MRG whose only content was\n * the withdrawn MRG-4 must not read as \"nothing to retire\"). The helper\n * surfaces whatever IS present and never\n * guesses the merge direction: this warning is the signal that the pair is\n * incomplete.\n *\n * The message carries only the structural facts (trigger event code + which\n * role is missing): NEVER an identifier, name, or any other field value, so\n * no PHI is exposed (HL7 v2 Ch. 3: the PID carries surviving and the MRG\n * carries non-surviving identity information).\n *\n * @example\n * ```ts\n * import { mergeMissingPriorOrSurvivor } from \"@cosyte/hl7\";\n * const w = mergeMissingPriorOrSurvivor({ segmentIndex: 1 }, \"A40\", \"prior\");\n * ```\n */\nexport function mergeMissingPriorOrSurvivor(\n position: Hl7Position,\n eventType: string,\n missing: \"prior\" | \"survivor\",\n): Hl7ParseWarning {\n const detail =\n missing === \"prior\"\n ? \"no MRG segment carries a usable prior (non-surviving) identifier\"\n : \"no PID segment carries a usable surviving identifier\";\n return {\n code: WARNING_CODES.MERGE_MISSING_PRIOR_OR_SURVIVOR,\n message:\n `Identity event \"${eventType}\" is missing its ${missing} role: ${detail}. ` +\n \"Surfacing what is present; the MRG->PID merge direction is not guessed.\",\n position,\n };\n}\n\n/**\n * Build a `BATCH_COUNT_MISMATCH` warning (roadmap Phase L). Emitted by\n * `splitBatch()`: attached to the returned `BatchSplitResult.warnings`, never\n * to `Hl7Message.warnings`: when a declared envelope count does not equal the\n * count actually split out: a **BTS-1** batch message count that differs from\n * the messages found in that batch, or an **FTS-1** file batch count that\n * differs from the batches found in the file (HL7 v2 Ch. 2 §2.10.3; BTS-1 / FTS-1\n * per the BTS / FTS segment definitions in §2.15).\n * The splitter **never drops the tail** to make the numbers agree: the\n * mismatch is surfaced and every message is still returned; the caller decides\n * whether to reject.\n *\n * The message carries only the declared-vs-actual **integers** and the unit\n * (`message` for BTS-1, `batch` for FTS-1): NEVER a field value, facility\n * identifier, or any other content, so no PHI is exposed. `position` references\n * the trailer segment (`BTS`/`FTS`) that declared the count.\n *\n * @example\n * ```ts\n * import { batchCountMismatch } from \"@cosyte/hl7\";\n * const w = batchCountMismatch({ segmentIndex: 4 }, \"message\", 3, 2);\n * ```\n */\nexport function batchCountMismatch(\n position: Hl7Position,\n unit: \"message\" | \"batch\",\n declared: number,\n actual: number,\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.BATCH_COUNT_MISMATCH,\n message:\n `Batch envelope declares ${String(declared)} ${unit}(s) but ${String(actual)} ` +\n `were found; the count mismatch is surfaced and nothing was dropped.`,\n position,\n };\n}\n\n/**\n * Build a `BATCH_MISSING_TRAILER` warning (roadmap Phase L). Emitted by\n * `splitBatch()` (attached to `BatchSplitResult.warnings`) when an envelope\n * header opens a scope that is never closed: a **BHS** batch header with no\n * matching **BTS** trailer, or an **FHS** file header with no matching **FTS**\n * trailer (HL7 v2 Ch. 2 §2.10.3: each envelope segment is optional, but a\n * profile such as an IIS file-submission spec may mandate the full frame).\n * `splitBatch` **does not enforce** such a rule: it splits, warns, and leaves\n * the accept/reject decision to the caller; the parse never throws for this.\n *\n * The message carries only the header/trailer segment names: NEVER a field\n * value, so no PHI is exposed. `position` references the unmatched header\n * segment (`FHS`/`BHS`).\n *\n * @example\n * ```ts\n * import { batchMissingTrailer } from \"@cosyte/hl7\";\n * const w = batchMissingTrailer({ segmentIndex: 0 }, \"BHS\", \"BTS\");\n * ```\n */\nexport function batchMissingTrailer(\n position: Hl7Position,\n header: \"FHS\" | \"BHS\",\n expectedTrailer: \"FTS\" | \"BTS\",\n): Hl7ParseWarning {\n return {\n code: WARNING_CODES.BATCH_MISSING_TRAILER,\n message:\n `Batch envelope header \"${header}\" has no matching \"${expectedTrailer}\" trailer; ` +\n \"splitBatch surfaces this but does not reject: a profile that mandates the full envelope may.\",\n position,\n };\n}\n\n/**\n * Build an `UNTERMINATED_STREAM_MESSAGE` warning (roadmap Phase S). Emitted by\n * `parseStream()`: attached to a {@link StreamMessageEntry}'s `streamWarnings`,\n * NOT to `Hl7Message.warnings`: when the **final** message in a stream ends\n * without a segment terminator (its last segment ran to end-of-stream with no\n * trailing `\\r`/`\\r\\n`/`\\n`). The message is still parsed and yielded **in\n * full**; this is the fail-safe signal that the tail may have been truncated\n * mid-message (a cut-off feed), never a reason to drop it and never a throw.\n * Only the last message can be unterminated: every earlier message is closed by\n * the terminator that precedes the next `MSH`/envelope boundary.\n *\n * The message carries only the structural fact, NEVER a field value, so no PHI\n * is exposed. `position` references the message's `MSH` segment index.\n *\n * @example\n * ```ts\n * import { unterminatedStreamMessage } from \"@cosyte/hl7\";\n * const w = unterminatedStreamMessage({ segmentIndex: 6 });\n * ```\n */\nexport function unterminatedStreamMessage(position: Hl7Position): Hl7ParseWarning {\n return {\n code: WARNING_CODES.UNTERMINATED_STREAM_MESSAGE,\n message:\n \"The final message in the stream ended without a segment terminator; it is still yielded \" +\n \"in full. If the source terminates every segment, this may indicate a truncated feed.\",\n position,\n };\n}\n","/**\n * MLLP (Minimal Lower Layer Protocol) framing byte removal for the\n * `@cosyte/hl7` parser pipeline. MLLP wraps an HL7 v2 message with a\n * start-block byte (`0x0B` / VT) and an end-block pair (`0x1C` / FS followed\n * by `0x0D` / CR). This module strips those control bytes and flags the event\n * via the `MLLP_FRAMING_STRIPPED` Tier-2 warning (TOL-06).\n *\n * Per CONTEXT.md D-03, MLLP stripping runs after BOM strip and before\n * line-ending normalization in the overall pipeline. Plan 06 composes the\n * full pipeline; this module stays standalone so Plan 06 can invoke it in the\n * exact right position.\n */\n\nimport { mllpFramingStripped } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Result of an MLLP framing strip. `wasFramed` is `true` iff any of the three\n * MLLP control bytes (VT = `0x0B`, FS = `0x1C`, trailing CR = `0x0D` paired\n * with an FS) were removed from the input: the signal downstream code uses\n * to decide whether to emit an `MLLP_FRAMING_STRIPPED` warning.\n *\n * @example\n * ```ts\n * import { stripMllp, type StripMllpResult } from \"@cosyte/hl7\";\n * const r: StripMllpResult = stripMllp(\"\\u000BMSH|...\\u001C\\u000D\");\n * // r.stripped === \"MSH|...\"; r.wasFramed === true\n * ```\n */\nexport interface StripMllpResult {\n readonly stripped: string;\n readonly wasFramed: boolean;\n}\n\n/**\n * Strip MLLP framing bytes from a raw HL7 message string. Removes all\n * occurrences of VT (`\\u000B`) and FS (`\\u001C`); additionally removes a\n * single trailing CR (`\\u000D`) if and only if it was paired with a trailing\n * FS (the MLLP end-block convention). Data CRs in the middle of the payload\n * are preserved as segment terminators.\n *\n * Pure function: safe to call on any string. Returns the original string\n * unchanged with `wasFramed: false` when no framing bytes are present.\n *\n * @example\n * ```ts\n * import { stripMllp } from \"@cosyte/hl7\";\n * const { stripped, wasFramed } = stripMllp(\"\\u000BMSH|^~\\\\&|APP\\rPID|1\\u001C\\u000D\");\n * // stripped === \"MSH|^~\\\\&|APP\\rPID|1\"; wasFramed === true\n * ```\n */\nexport function stripMllp(input: string): StripMllpResult {\n const hasVt = input.includes(\"\\u000B\");\n const hasFs = input.includes(\"\\u001C\");\n if (!hasVt && !hasFs) {\n return { stripped: input, wasFramed: false };\n }\n\n const originalEndedWithFsCr = /\\u001C\\u000D$/u.test(input);\n let s = input.replace(/[\\u000B\\u001C]/gu, \"\");\n if (originalEndedWithFsCr && s.endsWith(\"\\u000D\")) {\n s = s.slice(0, -1);\n }\n return { stripped: s, wasFramed: true };\n}\n\n/**\n * Emit an `MLLP_FRAMING_STRIPPED` warning via the supplied callback when the\n * given strip result indicates framing bytes were removed. No-op when\n * `result.wasFramed` is false. Kept as a companion helper (rather than\n * collapsed into `stripMllp`) so the two concerns (transform and emit)\n * stay testable in isolation, per CLAUDE.md guardrails.\n *\n * @example\n * ```ts\n * import { stripMllp, emitIfFramed } from \"@cosyte/hl7\";\n * const result = stripMllp(raw);\n * emitIfFramed(result, (w) => console.warn(w.code), { segmentIndex: 0 });\n * ```\n */\nexport function emitIfFramed(\n result: StripMllpResult,\n emit: (warning: Hl7ParseWarning) => void,\n position: Hl7Position,\n): void {\n if (result.wasFramed) {\n emit(mllpFramingStripped(position));\n }\n}\n","/**\n * HL7 v2 **Table 0211 (Alternate Character Sets)** resolution for the parser's\n * `Buffer`-decode stage (Phase O). Mirrors the frozen read-only registries\n * `KNOWN_SEGMENTS` / `KNOWN_CODING_SYSTEMS`: a single source of truth mapping an\n * MSH-18 character-set code to how the parser treats it: **decode** (single-byte\n * ISO-8859 family + Unicode UTF-8) or **preserve-verbatim** (the multibyte /\n * ISO-2022-switched East-Asian sets and UTF-16/32, which HL7 renders through\n * stateful `\\Mxxyyzz\\` escapes this phase deliberately does not fully decode).\n *\n * Spec traceability: HL7 v2 Chapter 2, **MSH-18** (item 00692) + **Table 0211**\n * (OID 2.16.840.1.113883.18.116). MSH-18 is **repeating**: the first occurrence\n * is the message's default encoding, later occurrences are alternates activated\n * mid-message by the §2.7.4 charset-switch escapes (`\\Cxxyy\\` single-byte,\n * `\\Mxxyyzz\\` multi-byte). A **blank** MSH-18 means 7-bit ASCII (the default).\n *\n * Fail-safe design: a set we do not decode is NEVER silently guessed as another\n * encoding. The caller preserves the raw bytes as a 1:1 `latin1` reading (every\n * byte 0x00..0xFF → U+0000..U+00FF) and emits a warning. For a **single-byte**\n * undecoded charset (an unrecognized label, or a recognized single-byte set) this\n * is byte-recoverable: the HL7 structural bytes (segment terminator CR, and the\n * `|^~\\&` delimiters) are unambiguous, so a field's content bytes survive and can\n * be re-decoded downstream via `Buffer.from(value, \"latin1\")`. For a **multibyte**\n * set (UTF-16/32, the East-Asian DBCS/ISO-2022 sets) a content byte can coincide\n * with a structural byte, so tokenization runs on raw bytes and framing is\n * best-effort, not byte-recoverable: which is exactly why decoding those sets is\n * deferred (see the parser's known-limitations). Because a recognized-but-undecoded\n * set and an unrecognized label both preserve bytes, the exact Table-0211 spelling\n * of the multibyte codes is not load-bearing for safety: only for which warning\n * (`UNSUPPORTED_CHARSET` vs `UNKNOWN_CHARSET`) fires.\n */\n\n/**\n * How the parser treats a resolved MSH-18 character set.\n *\n * - `decode`: decode the byte stream to text with {@link CharsetResolution.decoder}.\n * - `verbatim`: read the raw bytes as a 1:1 `latin1` mapping; do not decode\n * (byte-recoverable for single-byte content: see the module header).\n */\nexport type CharsetTreatment = \"decode\" | \"verbatim\";\n\n/**\n * The outcome of resolving an MSH-18 label (or `options.charset` override)\n * against Table 0211.\n */\nexport interface CharsetResolution {\n /**\n * The canonical Table-0211 code the label resolved to (e.g. `\"UTF-8\"`,\n * `\"8859/1\"`, `\"ISO IR87\"`). For an unrecognized label this is the input\n * trimmed + upper-cased, so it is still a stable key for comparison.\n */\n readonly canonical: string;\n /** Whether the parser decodes this set or preserves its bytes verbatim. */\n readonly treatment: CharsetTreatment;\n /**\n * The WHATWG `TextDecoder` label to decode with when `treatment === \"decode\"`.\n * Empty when `treatment === \"verbatim\"`.\n */\n readonly decoder: string;\n /**\n * `true` when the label is a recognized HL7 Table-0211 code (whether or not\n * the parser decodes it); `false` when the label is not in Table 0211.\n * Drives the warning code on the verbatim path: recognized-but-`verbatim`\n * → `UNSUPPORTED_CHARSET`, unrecognized → `UNKNOWN_CHARSET`.\n */\n readonly recognized: boolean;\n}\n\n/** A frozen Table-0211 registry entry. */\ninterface CharsetEntry {\n readonly canonical: string;\n readonly treatment: CharsetTreatment;\n readonly decoder: string;\n}\n\n/**\n * Normalize an MSH-18 label to a lookup key: trim, upper-case, and collapse\n * internal runs of whitespace to a single space so `\"unicode utf-8\"` and\n * `\"UNICODE UTF-8\"` resolve alike. HL7 codes are ASCII, so an ASCII-safe\n * upper-case is sufficient and locale-independent.\n *\n * @internal\n */\nfunction normalizeLabel(raw: string): string {\n return raw.trim().replace(/\\s+/gu, \" \").toUpperCase();\n}\n\n/** Build a decode entry. @internal */\nfunction decodeEntry(canonical: string, decoder: string): CharsetEntry {\n return { canonical, treatment: \"decode\", decoder };\n}\n\n/** Build a verbatim (recognized-but-not-decoded) entry. @internal */\nfunction verbatimEntry(canonical: string): CharsetEntry {\n return { canonical, treatment: \"verbatim\", decoder: \"\" };\n}\n\n/**\n * Assemble the frozen alias → entry table. Multiple aliases (HL7 spellings +\n * common `ISO-8859-N` synonyms) point at one canonical entry.\n *\n * @internal\n */\nfunction buildTable(): ReadonlyMap<string, CharsetEntry> {\n const table = new Map<string, CharsetEntry>();\n const add = (aliases: readonly string[], entry: CharsetEntry): void => {\n for (const alias of aliases) table.set(normalizeLabel(alias), entry);\n };\n\n // 7-bit ASCII (ISO IR6): the Table-0211 default. Decoded as UTF-8: for\n // conformant 7-bit content the result is byte-identical, and it tolerates the\n // ubiquitous undeclared-UTF-8 feed without corruption (ASCII ⊂ UTF-8).\n add([\"ASCII\", \"US-ASCII\", \"ISO IR6\"], decodeEntry(\"ASCII\", \"utf-8\"));\n\n // Unicode UTF-8 and its HL7 spellings. `UNICODE` (bare) is the deprecated\n // pre-UTF-8 code that real feeds use to mean UTF-8.\n add([\"UTF-8\", \"UTF8\", \"UNICODE UTF-8\", \"UNICODE\"], decodeEntry(\"UTF-8\", \"utf-8\"));\n\n // ISO-8859-1 (Latin-1): decoded via Node's `latin1`, which is the TRUE\n // ISO-8859-1 (every byte 0x00–0xFF maps 1:1, byte-exact, never fails). Node's\n // WHATWG `TextDecoder(\"iso-8859-1\")` is actually windows-1252: it remaps the\n // C1 range (0x80 → €), so it is deliberately NOT used here.\n add([\"8859/1\", \"ISO-8859-1\", \"ISO 8859-1\", \"ISO8859-1\"], decodeEntry(\"8859/1\", \"latin1\"));\n\n // The rest of the single-byte ISO 8859 family that Node's ICU decodes\n // FAITHFULLY: i.e. the C1 range 0x80–0x9F maps to U+0080–U+009F (controls),\n // matching the true ISO-8859-N code page (audited empirically). Decoded\n // strictly (see normalizeBuffer): a byte genuinely undefined in the set fails\n // the decode and preserves verbatim rather than emitting a silent U+FFFD.\n //\n // 8859/9 and 8859/11 are DELIBERATELY EXCLUDED: Node/ICU aliases their labels\n // to windows-1254 / windows-874, which *define* the C1 range as typographic\n // characters (byte 0x80 → €), diverging from true ISO-8859-9/11. A strict\n // decode would NOT throw on those bytes: it would silently emit a wrong,\n // non-recoverable character: so they are preserved verbatim below instead of\n // mis-decoded. (8859/1 is handled byte-exactly above via `latin1`.)\n for (const n of [2, 3, 4, 5, 6, 7, 8, 10, 13, 14, 15, 16]) {\n add(\n [`8859/${n}`, `ISO-8859-${n}`, `ISO 8859-${n}`, `ISO8859-${n}`],\n decodeEntry(`8859/${n}`, `iso-8859-${n}`),\n );\n }\n // Recognized but NOT decoded: Node's ICU has no faithful decoder (windows\n // codepage alias remaps the C1 range); preserved verbatim (byte-recoverable)\n // rather than silently mis-decoded. See the note above.\n add([\"8859/9\", \"ISO-8859-9\", \"ISO 8859-9\", \"ISO8859-9\"], verbatimEntry(\"8859/9\"));\n add([\"8859/11\", \"ISO-8859-11\", \"ISO 8859-11\", \"ISO8859-11\"], verbatimEntry(\"8859/11\"));\n\n // Recognized Table-0211 multibyte / ISO-2022-switched East-Asian sets and\n // the wide Unicode transforms: recognized, but preserved verbatim this phase\n // (full stateful decoding is deferred: see the module header).\n add([\"ISO IR14\", \"JIS X 0201\"], verbatimEntry(\"ISO IR14\"));\n add([\"ISO IR87\", \"JIS X 0208\"], verbatimEntry(\"ISO IR87\"));\n add([\"ISO IR159\", \"JIS X 0212\"], verbatimEntry(\"ISO IR159\"));\n add([\"GB 18030-2000\", \"GB18030\", \"GB 18030\"], verbatimEntry(\"GB 18030-2000\"));\n add([\"KS X 1001\", \"KSX1001\", \"KS C 5601\"], verbatimEntry(\"KS X 1001\"));\n add([\"CNS 11643-1992\", \"CNS 11643\"], verbatimEntry(\"CNS 11643-1992\"));\n add([\"BIG-5\", \"BIG5\"], verbatimEntry(\"BIG-5\"));\n add([\"UNICODE UTF-16\", \"UTF-16\"], verbatimEntry(\"UNICODE UTF-16\"));\n add([\"UNICODE UTF-32\", \"UTF-32\"], verbatimEntry(\"UNICODE UTF-32\"));\n\n return table;\n}\n\n/**\n * The frozen HL7 v2 Table-0211 registry, keyed by normalized label. Read-only,\n * built once at module load, never mutated.\n */\nconst CHARSET_TABLE: ReadonlyMap<string, CharsetEntry> = buildTable();\n\n/**\n * The default resolution for a blank / absent MSH-18: **7-bit ASCII** per\n * Table 0211, decoded as its UTF-8 superset. Recognized, no warning.\n *\n * @internal\n */\nconst DEFAULT_RESOLUTION: CharsetResolution = Object.freeze({\n canonical: \"ASCII\",\n treatment: \"decode\",\n decoder: \"utf-8\",\n recognized: true,\n});\n\n/**\n * Resolve an MSH-18 label (or an `options.charset` override) to a\n * {@link CharsetResolution}. A blank / `undefined` label resolves to the ASCII\n * default. A recognized Table-0211 code returns its registry entry. An\n * unrecognized label resolves to a `verbatim`, `recognized: false` outcome so\n * the caller preserves bytes and emits `UNKNOWN_CHARSET`.\n *\n * @example\n * ```ts\n * import { resolveCharset } from \"@cosyte/hl7\";\n * resolveCharset(\"UNICODE UTF-8\"); // { canonical: \"UTF-8\", treatment: \"decode\", ... }\n * resolveCharset(\"ISO IR87\"); // { canonical: \"ISO IR87\", treatment: \"verbatim\", recognized: true }\n * resolveCharset(\"WINDOWS-1252\"); // { canonical: \"WINDOWS-1252\", treatment: \"verbatim\", recognized: false }\n * ```\n */\nexport function resolveCharset(raw: string | undefined): CharsetResolution {\n if (raw === undefined) return DEFAULT_RESOLUTION;\n const key = normalizeLabel(raw);\n if (key === \"\") return DEFAULT_RESOLUTION;\n const entry = CHARSET_TABLE.get(key);\n if (entry !== undefined) {\n return {\n canonical: entry.canonical,\n treatment: entry.treatment,\n decoder: entry.decoder,\n recognized: true,\n };\n }\n return { canonical: key, treatment: \"verbatim\", decoder: \"\", recognized: false };\n}\n\n/**\n * The canonical Table-0211 code for a label, for equality comparison (e.g. the\n * MSH-18-vs-`options.charset` `ENCODING_MISMATCH` check). Synonyms collapse to\n * one canonical string (`\"UNICODE UTF-8\"` and `\"UTF-8\"` → `\"UTF-8\"`), so a\n * synonym pair does not raise a false mismatch; an unrecognized label returns\n * its normalized form so two genuinely different labels still differ.\n *\n * @example\n * ```ts\n * import { canonicalCharset } from \"@cosyte/hl7\";\n * canonicalCharset(\"unicode utf-8\") === canonicalCharset(\"UTF-8\"); // true\n * ```\n */\nexport function canonicalCharset(raw: string): string {\n return resolveCharset(raw).canonical;\n}\n","/**\n * Input normalization stage for the `@cosyte/hl7` parser pipeline.\n * Normalizes mixed line endings (`\\r\\n`, `\\n`, `\\r`) to a single `\\r` terminator\n * and (for `Buffer` input) decodes bytes into a string using MSH-18 charset\n * resolution with a UTF-8 fallback.\n *\n * Per CONTEXT.md D-03 the canonical preprocessing order is:\n * 1. EMPTY_INPUT check (fatal)\n * 2. BOM strip (silent)\n * 3. MLLP strip\n * 4. Line-ending normalization (this module)\n *\n * Plan 06's `parseHL7` composition owns steps 1–3 explicitly so the ordering is\n * inspectable at the pipeline site. This module is a pure string/Buffer\n * transform that does NOT throw and does NOT strip BOM.\n */\n\nimport { resolveCharset } from \"./charset.js\";\nimport { unknownCharset, unsupportedCharset } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\n\n/**\n * Position attached to every charset warning: MSH (segment 0), field 18. The\n * message carries the charset code only, never a field value, so no PHI is\n * exposed.\n *\n * @internal\n */\nconst CHARSET_POSITION = { segmentIndex: 0, fieldIndex: 18 } as const;\n\n/**\n * Preserve a byte stream as a 1:1 `latin1` reading (every byte 0x00..0xFF →\n * U+0000..U+00FF) and normalize line endings for segment splitting. The\n * fail-safe for any charset the parser does not decode.\n *\n * Recoverability is exact for **single-byte** content: the HL7 structural bytes\n * (CR/LF terminators, `|^~\\&`) are unambiguous, so a field's content bytes\n * survive and re-encode via `Buffer.from(value, \"latin1\")`. For **multibyte**\n * content a code-unit byte can equal a structural byte (e.g. a UTF-16 `0x0D`);\n * line-ending normalization and segment splitting then act on it, so framing is\n * best-effort: the documented reason multibyte decode is deferred, not claimed.\n *\n * @internal\n */\nfunction preserveVerbatim(input: Buffer): string {\n return normalize(input.toString(\"latin1\"));\n}\n\n/**\n * Callback shape for warning emission during `normalizeBuffer`. Plan 06 wires\n * the real chokepoint (push onto `Hl7Message.warnings`, invoke `onWarning`,\n * escalate in strict mode). This type is internal to the parser modules.\n *\n * @internal\n */\ntype EmitFn = (warning: Hl7ParseWarning) => void;\n\n/**\n * Normalize line endings in an HL7 message string to a single `\\r` terminator.\n *\n * Converts `\\r\\n` and standalone `\\n` characters to `\\r`; existing `\\r`\n * characters are preserved. The replacement order matters: `\\r\\n` is handled\n * first so the sequence is not counted twice. Empty and whitespace-only input\n * is returned unchanged: the `EMPTY_INPUT` fatal is Plan 06's responsibility.\n * A leading UTF-8 BOM is preserved; BOM stripping is also Plan 06's job.\n *\n * @example\n * ```ts\n * import { normalize } from \"@cosyte/hl7\";\n * const clean = normalize(\"MSH|^~\\\\&|APP\\r\\nPID|1\\nEVN|A\");\n * // clean === \"MSH|^~\\\\&|APP\\rPID|1\\rEVN|A\"\n * ```\n */\nexport function normalize(input: string): string {\n return input.replace(/\\r\\n/g, \"\\r\").replace(/\\n/g, \"\\r\");\n}\n\n/**\n * Decode a `Buffer` of raw HL7 bytes into a string, then apply line-ending\n * normalization. Charset resolution runs through the frozen HL7 Table-0211\n * registry ({@link resolveCharset}):\n *\n * - `8859/1` (Latin-1) is decoded via `latin1`: byte-exact, never fails;\n * - the other faithfully-decodable sets (ASCII, `8859/2`–`8859/8`/`10`/`13`–`16`,\n * UTF-8) are decoded **strictly** (`fatal: true`); a byte invalid / undefined\n * for the declared set (or an ICU build lacking the label) falls through to\n * the verbatim fail-safe rather than emitting a silent `U+FFFD`. (`8859/9` and\n * `8859/11` are NOT decoded: Node's ICU aliases them to windows-1254/874,\n * which remap the C1 range: so they take the verbatim path below);\n * - a **recognized-but-not-decoded** set (the multibyte / ISO-2022 East-Asian\n * sets, UTF-16/32) preserves the bytes verbatim and emits `UNSUPPORTED_CHARSET`;\n * - an **unrecognized** label preserves the bytes verbatim and emits\n * `UNKNOWN_CHARSET`.\n *\n * The fail-safe never guesses an encoding and never silently corrupts: an\n * undecoded / un-decodable set is preserved as a `latin1` byte reading, not\n * replacement characters, so single-byte content stays byte-recoverable. A blank\n * / `undefined` charset is the ASCII default, decoded strictly as UTF-8 (a\n * superset that renders 7-bit content identically and handles the common\n * undeclared-UTF-8 feed); non-UTF-8 bytes under that default preserve verbatim +\n * warn rather than corrupt.\n *\n * Callers (Plan 06) remain responsible for the `EMPTY_INPUT` fatal check,\n * BOM stripping, and MLLP framing removal on the returned text.\n *\n * @example\n * ```ts\n * import { normalizeBuffer } from \"@cosyte/hl7\";\n * const text = normalizeBuffer(\n * Buffer.from(\"MSH|^~\\\\&|APP\\rPID|1\", \"utf-8\"),\n * \"UTF-8\",\n * (w) => console.warn(w.code),\n * );\n * ```\n */\nexport function normalizeBuffer(input: Buffer, charset: string | undefined, emit: EmitFn): string {\n const resolution = resolveCharset(charset);\n if (resolution.treatment === \"decode\") {\n if (resolution.decoder === \"latin1\") {\n // True ISO-8859-1: latin1 maps every byte losslessly and cannot fail.\n // (Node's `TextDecoder(\"iso-8859-1\")` is windows-1252: wrong for the C1\n // range: so it is intentionally not used here.)\n return normalize(input.toString(\"latin1\"));\n }\n try {\n // STRICT decode (fatal: true): a byte that is invalid / undefined for the\n // declared set throws rather than silently becoming U+FFFD (irreversible\n // loss). On failure: malformed content, or an ICU build lacking the\n // label: we preserve the bytes verbatim + warn instead of emitting\n // replacement-char-corrupted text. Valid content still decodes; this is\n // NOT a wholesale wrong-encoding guess.\n const decoder = new TextDecoder(resolution.decoder, { fatal: true });\n return normalize(decoder.decode(input));\n } catch {\n emit(unsupportedCharset(CHARSET_POSITION, resolution.canonical));\n return preserveVerbatim(input);\n }\n }\n // Verbatim path: recognized-but-not-decoded → UNSUPPORTED_CHARSET;\n // unrecognized label → UNKNOWN_CHARSET.\n if (resolution.recognized) {\n emit(unsupportedCharset(CHARSET_POSITION, resolution.canonical));\n } else {\n emit(unknownCharset(CHARSET_POSITION, charset ?? \"\"));\n }\n return preserveVerbatim(input);\n}\n","/**\n * HL7 escape-sequence handling for the `@cosyte/hl7` parser pipeline\n *: expands reserved-delimiter escapes on parse (`unescape`) and re-escapes\n * them back when emitting spec-clean HL7 on serialize (`reescape`).\n *\n * The HL7 v2 spec reserves the delimiter characters (field, component,\n * repetition, escape, subcomponent, and the v2.7+ truncation char) plus the\n * newline shorthand `\\.br\\`. Whenever a sender needs one of those characters\n * to appear inside user data, it must escape it using the active escape\n * character (default `\\`).\n *\n * **Recognition vs decoding.** The HL7 spec defines four families of escape\n * sequences. We **decode** sequences whose meaning is byte-exact (delimiter\n * back-substitution, hex, newline, truncation char). We **recognize and\n * preserve verbatim** sequences whose intent is presentational or sender-\n * specific: decoding them would either lose information (formatting/charset)\n * or invent a rendering policy the spec leaves to the consumer. Either way,\n * a recognized standard sequence never emits `UNKNOWN_ESCAPE_SEQUENCE`;\n * that warning is reserved for genuinely-unknown bodies (`\\Z..\\`, garbage).\n *\n * Decoded sequences (consumed by `expandSequence`):\n * \\F\\ → enc.field (field separator)\n * \\S\\ → enc.component (component separator)\n * \\T\\ → enc.subcomponent (subcomponent separator)\n * \\R\\ → enc.repetition (repetition separator)\n * \\E\\ → enc.escape (escape character itself)\n * \\P\\ → enc.truncation ?? \"#\" (truncation char, HL7 v2.7+ §2.5.5.2)\n * \\.br\\ → \"\\n\" (newline shorthand)\n * \\X..\\ → hex decode (2 hex digits per byte; 0x00..0xFF code points)\n *\n * Recognized but preserved verbatim (no decoding, no warning):\n * \\H\\, \\N\\ highlight start / normal text (§2.7.1)\n * \\.sp\\, \\.in\\, \\.ti\\, \\.fi\\, formatting commands (§2.7.6, kept as\n * \\.nf\\, \\.ce\\ semantic sentinels for a renderer)\n * \\Cxxyy\\, \\Mxxyyzz\\ single- / multi-byte charset switch\n * (§2.7.4: sender-local byte sequences;\n * decoding requires charset context\n * this module does not have)\n *\n * Genuinely unknown (still warns + preserve verbatim):\n * \\Z..\\ → vendor-specific. Profiles may register vendor handlers later.\n * anything else (garbage, unterminated)\n */\n\nimport type { EncodingCharacters, Hl7Position } from \"./types.js\";\nimport {\n unknownEscapeSequence,\n unterminatedEscapeSequence,\n type Hl7ParseWarning,\n} from \"./warnings.js\";\n\n/**\n * Expand HL7 escape sequences (`\\F\\`, `\\S\\`, `\\T\\`, `\\R\\`, `\\E\\`, `\\.br\\`,\n * `\\X..\\`, vendor-specific `\\Z..\\`) inside a field, component, or\n * subcomponent string. The escape delimiter comes from `enc.escape` (default\n * `\\`), so senders using a non-default escape character are handled\n * transparently.\n *\n * Unknown or malformed sequences are preserved VERBATIM in the output and\n * emit an `UNKNOWN_ESCAPE_SEQUENCE` warning via `emit`. Unterminated escapes\n * (an escape character with no closing partner before end-of-input) are also\n * preserved in full and warn once: the scan is strictly O(n) and cannot\n * infinite-loop on malformed input.\n *\n * @example\n * ```ts\n * import { unescape, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const warnings: Array<unknown> = [];\n * const out = unescape(\n * \"patient\\\\F\\\\name\\\\.br\\\\DOB\",\n * DEFAULT_ENCODING_CHARACTERS,\n * (w) => warnings.push(w),\n * { segmentIndex: 1, fieldIndex: 5 },\n * );\n * // out === \"patient|name\\nDOB\"\n * ```\n */\nexport function unescape(\n input: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n): string {\n const esc = enc.escape;\n if (!input.includes(esc)) return input;\n\n let out = \"\";\n let i = 0;\n while (i < input.length) {\n const ch = input.charAt(i);\n if (ch !== esc) {\n out += ch;\n i++;\n continue;\n }\n const close = input.indexOf(esc, i + 1);\n if (close === -1) {\n // Unterminated escape: preserve the rest verbatim, warn once, stop.\n // The warning carries NEITHER the tail content NOR its length (the\n // remainder is arbitrary field text, potentially PHI): only the fact\n // and position.\n emit(unterminatedEscapeSequence(position));\n out += input.slice(i);\n break;\n }\n const seq = input.slice(i + 1, close);\n const expanded = expandSequence(seq, enc);\n if (expanded !== null) {\n out += expanded;\n } else if (isRecognizedPreservedEscape(seq)) {\n // Standard sequence we deliberately do not decode (formatting / highlight\n // / charset). Preserve verbatim so round-trip is exact; no warning.\n out += esc + seq + esc;\n } else {\n emit(unknownEscapeSequence(position, seq));\n out += esc + seq + esc;\n }\n i = close + 1;\n }\n return out;\n}\n\n/** Spec default truncation char per HL7 v2.7+ §2.5.5.2. */\nconst DEFAULT_TRUNCATION_CHAR = \"#\";\n\n/** Highlight and formatting escapes that we recognize-but-preserve. */\nconst RECOGNIZED_PRESERVED_SET: ReadonlySet<string> = new Set([\n \"H\", // begin highlighting (§2.7.1)\n \"N\", // normal text: end highlighting (§2.7.1)\n \".sp\", // vertical skip (§2.7.6)\n \".in\", // indent\n \".ti\", // temporary indent\n \".fi\", // begin word wrap\n \".nf\", // end word wrap\n \".ce\", // center next line\n]);\n\n/**\n * Returns true for a spec-defined escape body the parser recognizes but\n * deliberately does not decode: recognizing it suppresses the\n * `UNKNOWN_ESCAPE_SEQUENCE` warning while preserving the sequence verbatim\n * so the serializer round-trips it byte-for-byte. Covers HL7 v2 §2.7.1\n * highlight, §2.7.6 formatting commands, and §2.7.4 charset switches\n * (`\\Cxxyy\\` single-byte, `\\Mxxyyzz\\` multi-byte; xx/yy/zz are hex digit\n * pairs).\n *\n * @internal\n */\nfunction isRecognizedPreservedEscape(seq: string): boolean {\n if (RECOGNIZED_PRESERVED_SET.has(seq)) return true;\n // \\Cxxyy\\: single-byte char set switch (2 hex byte pairs = 4 hex digits).\n if (seq.length === 5 && seq.charAt(0) === \"C\" && /^[0-9A-Fa-f]{4}$/u.test(seq.slice(1))) {\n return true;\n }\n // \\Mxxyyzz\\: multi-byte char set switch (2 or 3 hex byte pairs = 4 or 6 digits).\n if (\n seq.charAt(0) === \"M\" &&\n (seq.length === 5 || seq.length === 7) &&\n /^[0-9A-Fa-f]+$/u.test(seq.slice(1))\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Expand a known HL7 escape body (the characters between the two escape\n * delimiters) to its decoded value. Returns `null` for any body this\n * function does not decode: `unescape` then routes the body through\n * `isRecognizedPreservedEscape` to decide warn-or-preserve.\n *\n * @internal\n */\nfunction expandSequence(seq: string, enc: EncodingCharacters): string | null {\n if (seq === \"F\") return enc.field;\n if (seq === \"S\") return enc.component;\n if (seq === \"T\") return enc.subcomponent;\n if (seq === \"R\") return enc.repetition;\n if (seq === \"E\") return enc.escape;\n // \\P\\: truncation character (HL7 v2.7+ §2.5.5.2). Decodes to enc.truncation\n // when MSH-2 declared one (5-char form), otherwise the spec default `#`.\n if (seq === \"P\") return enc.truncation ?? DEFAULT_TRUNCATION_CHAR;\n if (seq === \".br\") return \"\\n\";\n if (seq.startsWith(\"X\")) {\n const hex = seq.slice(1);\n if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9A-Fa-f]+$/u.test(hex)) {\n return null;\n }\n let decoded = \"\";\n for (let j = 0; j < hex.length; j += 2) {\n const byte = parseInt(hex.slice(j, j + 2), 16);\n decoded += String.fromCharCode(byte);\n }\n return decoded;\n }\n // \\Z..\\ is vendor-specific; Phase 2 maintains no allow-list, so callers\n // receive `null` and emit the UNKNOWN_ESCAPE_SEQUENCE warning. Future\n // Phase 6 profiles can register their own vendor handlers.\n return null;\n}\n\n/**\n * Re-escape reserved characters back into their `\\X\\` forms so the serializer\n * can emit spec-clean HL7. This is the inverse of `unescape` for every\n * delimiter-bearing character; round-trip cleanliness\n * (`unescape(reescape(x, enc), enc, emit, pos) === x`) is a documented\n * property covered by tests.\n *\n * The characters re-escaped:\n * enc.escape → \\E\\\n * enc.field → \\F\\\n * enc.component → \\S\\\n * enc.subcomponent → \\T\\\n * enc.repetition → \\R\\\n * enc.truncation → \\P\\ (only when MSH-2 declared one, v2.7+)\n * \"\\n\" (LF) → \\.br\\\n * \"\\r\" (CR) → \\X0D\\ (a decoded CR is the HL7 segment separator;\n * emitting it raw would corrupt wire framing, so\n * it re-encodes to its hex escape: see below)\n *\n * **Lossy by construction for the non-delimiter escape families.** `reescape`\n * only knows about the reserved characters above: it cannot reconstruct a\n * recognize-and-preserve escape (`\\H\\`, formatting, charset, `\\Z..\\`) or the\n * original bytes of a hex escape (`\\X41\\` decoded to `A`; casing of `\\X0d\\`),\n * because those decode to ordinary characters that carry no \"I was an escape\"\n * marker. Byte-verbatim emit for those families is the serializer's job via\n * the `RawComponent.rawSubcomponents` overlay (see {@link escapeFidelityRaw});\n * `reescape` is the fallback for content that has no overlay (constructed\n * values, `Field`-level re-escapes).\n *\n * Iteration uses `for..of`, which walks Unicode code points (not UTF-16 code\n * units), so user-supplied content containing non-BMP characters round-trips\n * correctly without special surrogate-pair handling.\n *\n * @example\n * ```ts\n * import { reescape, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * reescape(\"Smith|John\", DEFAULT_ENCODING_CHARACTERS); // \"Smith\\\\F\\\\John\"\n * reescape(\"line1\\nline2\", DEFAULT_ENCODING_CHARACTERS); // \"line1\\\\.br\\\\line2\"\n * ```\n */\nexport function reescape(input: string, enc: EncodingCharacters): string {\n if (input.length === 0) return input;\n const trunc = enc.truncation;\n let out = \"\";\n for (const ch of input) {\n if (ch === enc.escape) out += enc.escape + \"E\" + enc.escape;\n else if (ch === enc.field) out += enc.escape + \"F\" + enc.escape;\n else if (ch === enc.component) out += enc.escape + \"S\" + enc.escape;\n else if (ch === enc.subcomponent) out += enc.escape + \"T\" + enc.escape;\n else if (ch === enc.repetition) out += enc.escape + \"R\" + enc.escape;\n // \\P\\: only emitted when MSH-2 declared a truncation character (v2.7+);\n // for pre-v2.7 encodings the character has no reserved meaning and\n // round-trips as a literal.\n else if (trunc !== undefined && ch === trunc) out += enc.escape + \"P\" + enc.escape;\n else if (ch === \"\\n\") out += enc.escape + \".br\" + enc.escape;\n // A literal CR in decoded content (reachable via a spec-legal \\X0D\\ hex\n // escape on parse) is the HL7 segment separator: emitting it raw would\n // CORRUPT the wire framing (a phantom segment split mid-field, silently).\n // Re-emit it as its hex escape so the round-trip is stable and the\n // emitted message always stays structurally intact.\n else if (ch === \"\\r\") out += enc.escape + \"X0D\" + enc.escape;\n else out += ch;\n }\n return out;\n}\n\n/**\n * Decide the **escape-fidelity overlay** entry for one subcomponent: the\n * original wire bytes (`rawSub`) to emit verbatim, or `undefined` when the\n * decoded form already re-escapes back to those exact bytes.\n *\n * The rule is a single equality check (`reescape(decoded) === rawSub`) which\n * captures every family correctly by construction:\n * - **Delimiter escapes** (`\\F\\`→`|`, `\\E\\`→`\\`, `\\.br\\`→`\\n`, `\\X0D\\`→CR) all\n * re-escape back to their exact wire bytes, so they get **no overlay** and\n * ride the `reescape` fast path: no per-subcomponent memory cost.\n * - **Recognize-and-preserve escapes** (`\\H\\`, `\\N\\`, formatting, charset,\n * `\\Z..\\`) decode to a literal backslash-bearing string that `reescape`\n * would double-escape (`\\H\\` → `\\E\\H\\E\\`), so `reescape(decoded) !== rawSub`\n * and the overlay pins the original bytes.\n * - **Hex escapes** (`\\X41\\`→`A`, non-canonical casing `\\X0d\\`) decode away\n * their `\\X..\\` shape, so the overlay preserves the sender's exact bytes\n * (value/casing) rather than canonicalizing.\n *\n * Called once per escape-bearing subcomponent during tokenization; the\n * `rawSub.includes(enc.escape)` guard in the caller skips it entirely for the\n * common no-escape subcomponent, so this never runs on plain content.\n *\n * @internal\n */\nexport function escapeFidelityRaw(\n rawSub: string,\n decoded: string,\n enc: EncodingCharacters,\n): string | undefined {\n return reescape(decoded, enc) === rawSub ? undefined : rawSub;\n}\n","/**\n * Tokenizer stage for the `@cosyte/hl7` parser pipeline. Decomposes\n * an ordered list of segment strings into the nested positional tree that\n * `Hl7Message` holds: `RawSegment` -> `RawField` -> `RawRepetition` ->\n * `RawComponent` -> subcomponent strings. Honors custom encoding characters\n * so PARSE-02 (non-default delimiters) flows through downstream stages\n * without re-derivation.\n *\n * Adopts the unified HL7 1-indexed convention for ALL segments:\n * `fields[0]` is the segment-name / separator placeholder slot (never a\n * data field); `fields[N]` for N >= 1 is the HL7 N-th field. MSH: `fields[0]`\n * holds the field separator char (MSH-1), `fields[1]` holds the encoding\n * chars string (MSH-2). Non-MSH (PID, EVN, ZPI, ...): `fields[0]` holds the\n * segment name, `fields[1]` holds the HL7 first field (PID-1).\n *\n * Escape expansion (Phase 5 round-trip contract): each subcomponent is run\n * through `unescape()` during tokenization, so the raw tree holds DECODED\n * strings (e.g. `Smith|Jones`, not `Smith\\F\\Jones`). This is the exact\n * inverse of `reescape()` in `src/serialize/emit-field.ts`, which is how the\n * serializer produces spec-clean output and how SER-02 structural round-trip\n * equivalence holds: `parseHL7(msg.toString()).rawSegments` deeply equals\n * `msg.rawSegments`. `UNKNOWN_ESCAPE_SEQUENCE` warnings from `unescape`\n * propagate through the `emit` callback.\n *\n * Escape-fidelity overlay (HL7-ESC): `reescape` is a faithful inverse only for\n * the delimiter/newline escapes: recognize-and-preserve escapes (`\\H\\`,\n * charset, formatting, `\\Z..\\`) and hex escapes (`\\X41\\`) decode to plain\n * characters that would re-emit canonicalized (`\\H\\` → `\\E\\H\\E\\`; `\\X41\\` → `A`),\n * not byte-verbatim. So tokenization also records the **original wire bytes** of\n * exactly those subcomponents in `RawComponent.rawSubcomponents`, which the\n * serializer emits verbatim. The decoded `subcomponents` surface is unchanged;\n * only emit consults the overlay. The MSH-1 / MSH-2 positional\n * placeholders (`fields[0]`, `fields[1]`) are intentionally NOT unescaped,\n * they hold the literal delimiter / encoding chars and participate in\n * serialization via the D-06 special-case path, not via `emitField`.\n */\n\nimport { escapeFidelityRaw, unescape } from \"./escapes.js\";\nimport { fieldWhitespaceTrimmed } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type {\n EncodingCharacters,\n Hl7Position,\n RawComponent,\n RawField,\n RawRepetition,\n RawSegment,\n} from \"./types.js\";\n\n/**\n * Decompose an ordered list of segment strings into the raw positional tree\n * consumed by `Hl7Message`. Honors custom encoding characters from `enc`.\n * Empty field (`||`) vs HL7 explicit null (`\"\"`) are distinguished via\n * `RawField.isNull`.\n *\n * When `trimFields` is true and a field value had non-trivial leading or\n * trailing whitespace (i.e. whitespace around non-whitespace content), a\n * `FIELD_WHITESPACE_TRIMMED` warning is emitted via `emit`. All-whitespace\n * fields and fields without surrounding whitespace do not emit. Escape\n * sequence expansion is deferred to Plan 04's on-access escape stage.\n *\n * @example\n * ```ts\n * import { tokenize, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const tree = tokenize(\n * [\"MSH|^~\\\\&|APP\", \"PID|1||Doe^Jane\"],\n * DEFAULT_ENCODING_CHARACTERS,\n * () => {},\n * true,\n * );\n * // tree[1].name === \"PID\"\n * // tree[1].fields[3].repetitions[0].components[0].subcomponents[0] === \"Doe\"\n * ```\n */\nexport function tokenize(\n segments: readonly string[],\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n trimFields: boolean,\n): readonly RawSegment[] {\n const out: RawSegment[] = [];\n for (let sIdx = 0; sIdx < segments.length; sIdx++) {\n const segStr = segments[sIdx];\n if (segStr === undefined) continue;\n\n // Preserve empty middle segments (from consecutive \\r) as zero-field,\n // empty-name RawSegment so segmentIndex stays stable downstream.\n if (segStr.length === 0) {\n out.push({ name: \"\", fields: [] });\n continue;\n }\n\n const firstSepIdx = segStr.indexOf(enc.field);\n const name = firstSepIdx === -1 ? segStr : segStr.slice(0, firstSepIdx);\n const rest = firstSepIdx === -1 ? \"\" : segStr.slice(firstSepIdx + 1);\n\n if (name === \"MSH\") {\n out.push(tokenizeMshSegment(segStr, enc, emit, sIdx, trimFields));\n } else {\n const namePlaceholder: RawField = {\n repetitions: [{ components: [{ subcomponents: [name] }] }],\n isNull: false,\n };\n const dataFields =\n rest.length === 0 ? [] : splitAndTokenizeFields(rest, enc, emit, sIdx, 0, trimFields);\n out.push({ name, fields: [namePlaceholder, ...dataFields] });\n }\n }\n return out;\n}\n\n/**\n * Tokenize an MSH segment. MSH is the one segment where the field separator\n * is encoded in-band as MSH-1: `MSH|^~\\&|APP|...`. We synthesize `fields[0]`\n * as a single-component holding the separator char and `fields[1]` as a\n * single-component holding the raw MSH-2 encoding chars string; the\n * remainder (MSH-3, MSH-4, ...) is parsed by `splitAndTokenizeFields` with\n * `fieldStartOffset = 2` so the 1-indexed `fieldIndex` on emitted warnings\n * matches the HL7 position (MSH-3 emits `fieldIndex: 3`).\n *\n * @internal\n */\nfunction tokenizeMshSegment(\n segStr: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n sIdx: number,\n trimFields: boolean,\n): RawSegment {\n const msh1: RawField = {\n repetitions: [{ components: [{ subcomponents: [enc.field] }] }],\n isNull: false,\n };\n\n const sepAfterMsh2 = segStr.indexOf(enc.field, 4);\n const msh2RawEnd = sepAfterMsh2 === -1 ? segStr.length : sepAfterMsh2;\n const msh2Raw = segStr.slice(4, msh2RawEnd);\n const msh2: RawField = {\n repetitions: [{ components: [{ subcomponents: [msh2Raw] }] }],\n isNull: false,\n };\n\n const remainder = sepAfterMsh2 === -1 ? \"\" : segStr.slice(sepAfterMsh2 + 1);\n const tailFields =\n remainder.length === 0 ? [] : splitAndTokenizeFields(remainder, enc, emit, sIdx, 2, trimFields);\n return { name: \"MSH\", fields: [msh1, msh2, ...tailFields] };\n}\n\n/**\n * Split a segment's post-name field region into `RawField[]` using the\n * caller-supplied field-index offset so warning positions stay on the HL7\n * 1-indexed convention. Non-MSH callers pass `fieldStartOffset = 0` so the\n * first data field (PID-1) emits `fieldIndex: 1`; MSH callers pass\n * `fieldStartOffset = 2` so the first tail field (MSH-3) emits\n * `fieldIndex: 3`.\n *\n * The returned array is DATA-ONLY: the caller is responsible for\n * prepending the `fields[0]` name/separator placeholder so the unified\n * 1-indexed convention holds on the final `RawSegment.fields`.\n *\n * @internal\n */\nfunction splitAndTokenizeFields(\n region: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n sIdx: number,\n fieldStartOffset: number,\n trimFields: boolean,\n): RawField[] {\n const fields = region.split(enc.field);\n const out: RawField[] = [];\n for (let fIdx = 0; fIdx < fields.length; fIdx++) {\n const raw = fields[fIdx];\n if (raw === undefined) continue;\n out.push(\n tokenizeField(\n raw,\n enc,\n emit,\n { segmentIndex: sIdx, fieldIndex: fieldStartOffset + fIdx + 1 },\n trimFields,\n ),\n );\n }\n return out;\n}\n\n/**\n * Tokenize a single field string into a `RawField`. Handles the empty\n * (`\"\"`-the-JS-empty-string) vs explicit-null (`\"\"`-the-HL7-literal) split\n * per PARSE-06, then performs optional whitespace trim with warning\n * emission, then delegates repetition splitting.\n *\n * @internal\n */\nfunction tokenizeField(\n raw: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n trimFields: boolean,\n): RawField {\n if (raw === \"\") return { repetitions: [], isNull: false };\n if (raw === '\"\"') return { repetitions: [], isNull: true };\n\n let value = raw;\n if (trimFields) {\n const trimmed = raw.trim();\n if (trimmed.length > 0 && trimmed !== raw) {\n const trimStart = raw.length - raw.trimStart().length;\n const trimEnd = raw.length - raw.trimEnd().length;\n emit(fieldWhitespaceTrimmed(position, trimStart, trimEnd));\n value = trimmed;\n }\n }\n\n const reps = value.split(enc.repetition);\n const repetitions: RawRepetition[] = [];\n for (let rIdx = 0; rIdx < reps.length; rIdx++) {\n const rep = reps[rIdx];\n if (rep === undefined) continue;\n repetitions.push(\n tokenizeRepetition(rep, enc, emit, { ...position, repetitionIndex: rIdx + 1 }),\n );\n }\n return { repetitions, isNull: false };\n}\n\n/** @internal */\nfunction tokenizeRepetition(\n raw: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n): RawRepetition {\n const comps = raw.split(enc.component);\n const components: RawComponent[] = [];\n for (let cIdx = 0; cIdx < comps.length; cIdx++) {\n const c = comps[cIdx];\n if (c === undefined) continue;\n components.push(tokenizeComponent(c, enc, emit, { ...position, componentIndex: cIdx + 1 }));\n }\n return { components };\n}\n\n/**\n * Tokenize a single component into its subcomponents, running each\n * subcomponent string through `unescape` so the raw tree stores DECODED\n * values (inverse of `reescape` at emit time). This is load-bearing for\n * SER-02 structural round-trip equivalence: without it, the raw tree would\n * store literal `\\F\\` / `\\E\\` / `\\.br\\` sequences and emit would double-\n * escape them into `\\E\\F\\E\\` / etc.\n *\n * `UNKNOWN_ESCAPE_SEQUENCE` warnings from `unescape` propagate through the\n * `emit` callback with the full positional context (segment, field, rep,\n * component, subcomponent all 1-indexed).\n *\n * @internal\n */\nfunction tokenizeComponent(\n raw: string,\n enc: EncodingCharacters,\n emit: (w: Hl7ParseWarning) => void,\n position: Hl7Position,\n): RawComponent {\n const subs = raw.split(enc.subcomponent);\n const decoded: string[] = [];\n // Escape-fidelity overlay (HL7-ESC): the original wire bytes for any\n // subcomponent whose decoded form does not re-escape back to those exact\n // bytes (recognize-and-preserve escapes like `\\H\\`; hex escapes like\n // `\\X41\\`). Stays `undefined`-per-entry for the common case, and the whole\n // array is dropped when nothing needs it: so a plain message's raw tree is\n // shaped exactly as before this overlay existed.\n let rawSubcomponents: (string | undefined)[] | undefined;\n for (let sIdx = 0; sIdx < subs.length; sIdx++) {\n const sub = subs[sIdx];\n if (sub === undefined) {\n decoded.push(\"\");\n continue;\n }\n const decodedSub = unescape(sub, enc, emit, { ...position, subcomponentIndex: sIdx + 1 });\n decoded.push(decodedSub);\n // Only escape-bearing subcomponents can ever need the overlay: the\n // `includes(enc.escape)` guard keeps this off the hot path for plain data.\n if (sub.includes(enc.escape)) {\n const fidelity = escapeFidelityRaw(sub, decodedSub, enc);\n if (fidelity !== undefined) {\n (rawSubcomponents ??= new Array<string | undefined>(subs.length).fill(undefined))[sIdx] =\n fidelity;\n }\n }\n }\n return rawSubcomponents === undefined\n ? { subcomponents: decoded }\n : { subcomponents: decoded, rawSubcomponents };\n}\n","/**\n * Message-type & structure awareness (roadmap Phase G): a conservative\n * **misroute / truncation safety net**, NOT an abstract-message-syntax\n * validator.\n *\n * It answers one question per message: **\"for this trigger event, are the\n * core segment groups the spec marks Required actually present?\"** When an\n * expected group is entirely absent (e.g. an `ORU^R01` carrying no `OBR`/`OBX`\n * result group: the classic signature of a truncated or misrouted feed), the\n * parser emits a single additive Tier-2 `MISSING_EXPECTED_GROUP` warning. It\n * never throws, never refuses, never rewrites the message.\n *\n * Design constraints (all accuracy-driven, to guarantee ZERO spec\n * false-positives):\n *\n * - **Per trigger event, never per family.** The claim that an ADT family\n * shares one shape is false: events diverge by version and trigger. Every\n * definition keys on the (messageCode, triggerEvent) pair.\n * - **Required (R) anchors only.** A group is modelled only when its anchor\n * segment is genuinely Required by the v2.5.1 abstract syntax for that\n * event. Optional groups (e.g. PID in ORU, RXA in VXU, OBR in OML) are\n * deliberately excluded so a conformant-but-sparse message never warns.\n * - **Presence is liberal.** A group counts as present if ANY of its anchor\n * segments appears: the conservative direction (it suppresses a warning\n * rather than inventing one).\n * - **Unrecognized = silent.** A message whose type has no definition here\n * produces an unrecognized structure summary and zero structural warnings.\n *\n * Spec traceability: HL7 v2.5.1: Ch. 3 (ADT), Ch. 4 (orders), Ch. 6\n * (financial: DFT), Ch. 7 (observation: ORU), Ch. 9 (MDM), Ch. 10\n * (scheduling: SIU), Ch. 2 (ACK), CDC IG (VXU). Per-entry sourcing lives in\n * `docs-content/spec-notes-structure.md`.\n *\n * Zero runtime deps: pure data + pure functions.\n */\n\n/**\n * One expected segment group for a recognized trigger event. The group is\n * considered **present** when at least one of its `anchorSegments` appears in\n * the parsed message; its total absence is what signals a truncated or\n * misrouted message.\n */\nexport interface ExpectedSegmentGroup {\n /** Human-readable group label, e.g. `\"result\"`, `\"patient\"`, `\"order\"`. */\n readonly name: string;\n /**\n * The segment name(s) whose presence proves this group is present. Only\n * segments the HL7 v2.5.1 abstract syntax marks **Required (R)** for the\n * owning trigger event appear here, so a conformant message can never lack\n * all of them.\n */\n readonly anchorSegments: readonly string[];\n}\n\n/**\n * The expected structure of one recognized message type, keyed on the\n * (messageCode, triggerEvent) pair. A definition with an empty `triggerEvents`\n * list matches on `messageCode` alone (used for `ACK`, which carries no\n * trigger event in MSH-9.2).\n */\nexport interface MessageStructureDefinition {\n /** MSH-9.1 message code, e.g. `\"ORU\"`. */\n readonly messageCode: string;\n /**\n * The MSH-9.2 trigger events this definition applies to, e.g. `[\"R01\"]`.\n * An empty list means \"match on message code alone\" (e.g. `ACK`).\n */\n readonly triggerEvents: readonly string[];\n /** The Required (R) segment groups expected for these events. */\n readonly expectedGroups: readonly ExpectedSegmentGroup[];\n}\n\n/**\n * The conservative, Required-only expected-group registry. Each entry's spec\n * source is recorded in `docs-content/spec-notes-structure.md`. Deliberately\n * narrow: it recognizes the common message types' **core Required groups\n * only** and is NOT a conformance validator. Frozen (data, not config).\n *\n * @example\n * ```ts\n * import { MESSAGE_STRUCTURE_DEFINITIONS } from \"@cosyte/hl7\";\n * const oru = MESSAGE_STRUCTURE_DEFINITIONS.find((d) => d.messageCode === \"ORU\");\n * console.log(oru?.expectedGroups[0]?.name); // \"result\"\n * ```\n */\nexport const MESSAGE_STRUCTURE_DEFINITIONS: readonly MessageStructureDefinition[] = Object.freeze([\n // ── ADT (Ch. 3): patient identification (PID) + visit (PV1) are Required\n // for these admit/transfer/discharge/register/update/cancel events.\n // EVN is intentionally excluded: real senders omit it freely, making it\n // a weak (false-positive-prone) signal.\n Object.freeze({\n messageCode: \"ADT\",\n triggerEvents: Object.freeze([\"A01\", \"A02\", \"A03\", \"A04\", \"A05\", \"A08\", \"A11\", \"A13\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n Object.freeze({ name: \"visit\", anchorSegments: Object.freeze([\"PV1\"]) }),\n ]),\n }),\n // ── ORU^R01 (Ch. 7): the OBR/OBX result group is the Required payload.\n // PID is excluded (the patient-result group's PID is R within the group,\n // but a result-only relay can legitimately omit it at the top: keep the\n // anchor on the result segments themselves, the true truncation signal).\n Object.freeze({\n messageCode: \"ORU\",\n triggerEvents: Object.freeze([\"R01\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"result\", anchorSegments: Object.freeze([\"OBR\", \"OBX\"]) }),\n ]),\n }),\n // ── Orders (Ch. 4): ORC is the Required common-order segment across the\n // order message family. OBR is excluded: it is Optional in several of\n // these (OML/OMG/OMI carry it inside an optional observation-request\n // group), so anchoring only on ORC avoids a false positive.\n Object.freeze({\n messageCode: \"ORM\",\n triggerEvents: Object.freeze([\"O01\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OML\",\n triggerEvents: Object.freeze([\"O21\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OMG\",\n triggerEvents: Object.freeze([\"O19\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OMP\",\n triggerEvents: Object.freeze([\"O09\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n Object.freeze({\n messageCode: \"OMI\",\n triggerEvents: Object.freeze([\"O23\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"order\", anchorSegments: Object.freeze([\"ORC\"]) }),\n ]),\n }),\n // ── SIU scheduling (Ch. 10): SCH (schedule activity) is Required for every\n // S12–S26 event. The patient group (PID) is Optional in the SIU abstract\n // syntax, so it is excluded.\n Object.freeze({\n messageCode: \"SIU\",\n triggerEvents: Object.freeze([\n \"S12\",\n \"S13\",\n \"S14\",\n \"S15\",\n \"S16\",\n \"S17\",\n \"S18\",\n \"S19\",\n \"S20\",\n \"S21\",\n \"S22\",\n \"S23\",\n \"S24\",\n \"S26\",\n ]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"schedule\", anchorSegments: Object.freeze([\"SCH\"]) }),\n ]),\n }),\n // ── MDM (Ch. 9): document management: PID + the TXA document header are\n // Required for T02 (original document) and T06 (document addendum).\n Object.freeze({\n messageCode: \"MDM\",\n triggerEvents: Object.freeze([\"T02\", \"T06\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n Object.freeze({ name: \"document\", anchorSegments: Object.freeze([\"TXA\"]) }),\n ]),\n }),\n // ── DFT^P03 (Ch. 6): financial transaction: PID + at least one FT1\n // financial-transaction segment are Required.\n Object.freeze({\n messageCode: \"DFT\",\n triggerEvents: Object.freeze([\"P03\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n Object.freeze({ name: \"financial\", anchorSegments: Object.freeze([\"FT1\"]) }),\n ]),\n }),\n // ── VXU^V04 (CDC IG): immunization update: PID is Required. RXA is\n // excluded: it lives in the Optional order group of the CDC IG, so a\n // query-shaped VXU with no administered vaccine must not warn.\n Object.freeze({\n messageCode: \"VXU\",\n triggerEvents: Object.freeze([\"V04\"]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"patient\", anchorSegments: Object.freeze([\"PID\"]) }),\n ]),\n }),\n // ── ACK (Ch. 2): a general acknowledgment: MSA (message acknowledgment) is\n // Required. Matched on message code alone (no trigger event in MSH-9.2).\n Object.freeze({\n messageCode: \"ACK\",\n triggerEvents: Object.freeze([]),\n expectedGroups: Object.freeze([\n Object.freeze({ name: \"acknowledgment\", anchorSegments: Object.freeze([\"MSA\"]) }),\n ]),\n }),\n]);\n\n/**\n * The presence verdict for one expected group of a recognized message type.\n */\nexport interface StructureGroup {\n /** The group label from its `ExpectedSegmentGroup`, e.g. `\"result\"`. */\n readonly name: string;\n /** The anchor segment name(s) whose presence would satisfy this group. */\n readonly anchorSegments: readonly string[];\n /** `true` when at least one anchor segment is present in the message. */\n readonly present: boolean;\n}\n\n/**\n * The structure summary for a parsed message: the data behind\n * `Hl7Message.structure`. For an unrecognized type, `recognized` is `false`,\n * `expectedGroups` is empty, and `missingGroups` is empty (the safety net is\n * deliberately silent on types it does not model).\n */\nexport interface MessageStructure {\n /** `true` when a `MESSAGE_STRUCTURE_DEFINITIONS` entry matched the type. */\n readonly recognized: boolean;\n /** MSH-9.1 message code observed on the message (empty string if absent). */\n readonly messageCode: string;\n /** MSH-9.2 trigger event observed on the message (empty string if absent). */\n readonly triggerEvent: string;\n /** Per-expected-group presence verdicts (empty when unrecognized). */\n readonly expectedGroups: readonly StructureGroup[];\n /** Names of the expected groups that are entirely absent (the warnings). */\n readonly missingGroups: readonly string[];\n}\n\n/**\n * Find the structure definition for a (messageCode, triggerEvent) pair, or\n * `undefined` when the type is not modelled. A definition with an empty\n * `triggerEvents` list matches on message code alone.\n *\n * @internal\n */\nfunction findDefinition(\n messageCode: string,\n triggerEvent: string,\n): MessageStructureDefinition | undefined {\n for (const def of MESSAGE_STRUCTURE_DEFINITIONS) {\n if (def.messageCode !== messageCode) continue;\n if (def.triggerEvents.length === 0 || def.triggerEvents.includes(triggerEvent)) {\n return def;\n }\n }\n return undefined;\n}\n\n/**\n * Analyze a parsed message's structure against the conservative expected-group\n * registry. Pure: it takes the message code, trigger event, and the set of\n * segment names actually present, and returns a `MessageStructure` summary. It\n * decides nothing about whether to warn: the caller (parser) emits one\n * `MISSING_EXPECTED_GROUP` warning per name in `missingGroups`.\n *\n * @param messageCode - MSH-9.1 (e.g. `\"ORU\"`); empty string if absent.\n * @param triggerEvent - MSH-9.2 (e.g. `\"R01\"`); empty string if absent.\n * @param presentSegmentNames - the set of segment names present in the message.\n *\n * @example\n * ```ts\n * import { analyzeMessageStructure } from \"@cosyte/hl7\";\n * const s = analyzeMessageStructure(\"ORU\", \"R01\", new Set([\"MSH\", \"PID\"]));\n * console.log(s.recognized); // true\n * console.log(s.missingGroups); // [\"result\"] (no OBR/OBX)\n * ```\n */\nexport function analyzeMessageStructure(\n messageCode: string,\n triggerEvent: string,\n presentSegmentNames: ReadonlySet<string>,\n): MessageStructure {\n const def = findDefinition(messageCode, triggerEvent);\n if (def === undefined) {\n return Object.freeze({\n recognized: false,\n messageCode,\n triggerEvent,\n expectedGroups: Object.freeze([]),\n missingGroups: Object.freeze([]),\n });\n }\n\n const groups: StructureGroup[] = [];\n const missing: string[] = [];\n for (const expected of def.expectedGroups) {\n const present = expected.anchorSegments.some((name) => presentSegmentNames.has(name));\n groups.push(\n Object.freeze({\n name: expected.name,\n anchorSegments: expected.anchorSegments,\n present,\n }),\n );\n if (!present) missing.push(expected.name);\n }\n\n return Object.freeze({\n recognized: true,\n messageCode,\n triggerEvent,\n expectedGroups: Object.freeze(groups),\n missingGroups: Object.freeze(missing),\n });\n}\n","/**\n * Dot-path tokenizer and resolver for the `@cosyte/hl7` structural\n * model. Parses strings like `PID.5.1`, `OBX[2].5`, `PID.3[0].1` into a\n * discriminated-token descriptor, then resolves that descriptor against a\n * `readonly RawSegment[]` tree to produce the decoded leaf string (or\n * `undefined` on missing path). Zero runtime deps: a hand-rolled linear scan\n * (analog: `src/parser/dates.ts::matchTokenFormat`).\n *\n * Indexing conventions (locked in Phase 3 CONTEXT.md):\n * - `[N]` is ALWAYS 0-indexed: applies to segment repeats AND field repeats (D-01).\n * - Dot-numbers are ALWAYS 1-indexed: matches HL7 spec and Phase 2's 1-indexed\n * `RawSegment.fields` (D-02). `PID.5` → `fields[5]`.\n * - MSH.1 / MSH.2 are the separator char and encoding-chars string, both\n * stored at `fields[0]` / `fields[1]` by Phase 2 tokenize.ts (D-05).\n * - Missing subcomponent on a single-sub component returns the component\n * string (depth-collapse, D-04).\n * - Leaf reads return the subcomponent verbatim: the tokenizer (parser-02)\n * already unescaped it once on parse, so the stored value is decoded and a\n * second `unescape` here would double-decode it (HL7-VALUE-REDECODE).\n */\n\nimport type { EncodingCharacters, RawSegment } from \"../parser/types.js\";\n\n/**\n * Parsed representation of a dot-path string. Produced by `parsePath`,\n * consumed by `resolvePath`. All numeric indices are normalized to the\n * internal convention (segmentIndex = 0-based occurrence, fieldIndex =\n * 1-based HL7 field number, repetitionIndex = 0-based rep, componentIndex\n * and subcomponentIndex = 1-based HL7 positions).\n *\n * @example\n * ```ts\n * import { parsePath } from \"@cosyte/hl7\";\n * parsePath(\"OBX[2].5.1\");\n * // { segmentType: \"OBX\", segmentIndex: 2, fieldIndex: 5,\n * // repetitionIndex: 0, componentIndex: 1 }\n * ```\n */\nexport interface DotPath {\n /** 3-char segment identifier (e.g. `\"PID\"`, `\"OBX\"`, `\"ZPI\"`). */\n readonly segmentType: string;\n /** 0-based occurrence of this segment type in the message. */\n readonly segmentIndex: number;\n /** 1-based HL7 field number; maps to `RawSegment.fields[fieldIndex]`. */\n readonly fieldIndex: number;\n /** 0-based repetition index; defaults to 0 when `[N]` is omitted. */\n readonly repetitionIndex?: number;\n /** 1-based HL7 component position (within a repetition). */\n readonly componentIndex?: number;\n /** 1-based HL7 subcomponent position (within a component). */\n readonly subcomponentIndex?: number;\n}\n\n/** Mutable local view for building a `DotPath` with `exactOptionalPropertyTypes` discipline. @internal */\ninterface MutableDotPath {\n segmentType: string;\n segmentIndex: number;\n fieldIndex: number;\n repetitionIndex?: number;\n componentIndex?: number;\n subcomponentIndex?: number;\n}\n\n/** Segment-name shape: `[A-Z][A-Z0-9]{2}` (D-19 symmetry with addSegment). Matches standard HL7 v2 segment names (PID, PV1, OBX, NK1, DG1, IN1…) and Z-segment customs (ZPI, ZX1…). @internal */\nconst SEGMENT_NAME_RE = /^[A-Z][A-Z0-9]{2}$/u;\n\n/**\n * Parse an HL7 dot-path string into a `DotPath` descriptor. Accepts shapes\n * like `SEG`, `SEG[n]`, `SEG.N`, `SEG.N[r]`, `SEG.N.C`, `SEG.N.C.S`, and all\n * combinations up to `SEG[n].N[r].C.S`. Throws `TypeError` with the offending\n * path string on any malformed input.\n *\n * @example\n * ```ts\n * import { parsePath } from \"@cosyte/hl7\";\n * parsePath(\"PID.5.1\"); // { segmentType: \"PID\", segmentIndex: 0, fieldIndex: 5, componentIndex: 1 }\n * parsePath(\"OBX[2].5\"); // { segmentType: \"OBX\", segmentIndex: 2, fieldIndex: 5 }\n * parsePath(\"PID.3[1].1\"); // { segmentType: \"PID\", segmentIndex: 0, fieldIndex: 3, repetitionIndex: 1, componentIndex: 1 }\n * ```\n */\nexport function parsePath(path: string): DotPath {\n if (path.length === 0) {\n throw new TypeError(`Invalid HL7 dot-path: \"\" (empty).`);\n }\n\n // 1. Segment name: must be 3 chars matching [A-Z][A-Z0-9]{2}.\n if (path.length < 3) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (segment name too short).`);\n }\n const segmentType = path.slice(0, 3);\n if (!SEGMENT_NAME_RE.test(segmentType)) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (segment name must match [A-Z][A-Z0-9]{2}).`,\n );\n }\n let i = 3;\n\n const out: MutableDotPath = {\n segmentType,\n segmentIndex: 0,\n fieldIndex: 0,\n };\n\n // 2. Optional [n] segment occurrence.\n if (i < path.length && path.charAt(i) === \"[\") {\n const { value, next } = readBracket(path, i);\n out.segmentIndex = value;\n i = next;\n }\n\n // If the path ends here, the caller only asked for a segment: the\n // resolver can't produce a string value from a segment-only DotPath,\n // but we accept the shape so callers can probe structure.\n if (i === path.length) {\n // fieldIndex defaults to 0: sentinel meaning \"no field component\".\n return freezeDotPath(out);\n }\n\n // 3. Expect `.` then a field number (1-indexed), plus optional `[r]`.\n if (path.charAt(i) !== \".\") {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (expected '.' after segment at position ${String(i)}).`,\n );\n }\n i += 1;\n if (i === path.length) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (trailing dot).`);\n }\n {\n const { value, next } = readDigits(path, i);\n out.fieldIndex = value;\n i = next;\n }\n if (i < path.length && path.charAt(i) === \"[\") {\n const { value, next } = readBracket(path, i);\n out.repetitionIndex = value;\n i = next;\n }\n\n // 4. Optional `.C` component (1-indexed).\n if (i < path.length) {\n if (path.charAt(i) !== \".\") {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (unexpected '${path.charAt(i)}' at position ${String(i)}).`,\n );\n }\n i += 1;\n if (i === path.length) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (trailing dot).`);\n }\n const { value, next } = readDigits(path, i);\n out.componentIndex = value;\n i = next;\n }\n\n // 5. Optional `.S` subcomponent (1-indexed).\n if (i < path.length) {\n if (path.charAt(i) !== \".\") {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (unexpected '${path.charAt(i)}' at position ${String(i)}).`,\n );\n }\n i += 1;\n if (i === path.length) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (trailing dot).`);\n }\n const { value, next } = readDigits(path, i);\n out.subcomponentIndex = value;\n i = next;\n }\n\n // 6. Any trailing content → malformed (e.g. `PID.5.1.1.1`, `PID.5xyz`).\n if (i !== path.length) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (trailing content at position ${String(i)}: too deep or malformed).`,\n );\n }\n\n return freezeDotPath(out);\n}\n\n/**\n * Resolve a dot-path string against a raw segment tree to its decoded\n * leaf value. Returns `undefined` whenever the path does not resolve (missing\n * segment, out-of-range field/component/subcomponent/repetition), and never\n * throws on a missing value. Throws `TypeError` only when `path` itself is\n * malformed: callers relying on \"never throws\" should pre-validate or wrap\n * in try/catch.\n *\n * @example\n * ```ts\n * import { parseHL7, resolvePath } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * resolvePath(\"PID.5.1\", msg.rawSegments, msg.encodingCharacters); // \"Smith\"\n * resolvePath(\"NOT.9\", msg.rawSegments, msg.encodingCharacters); // undefined\n * ```\n */\nexport function resolvePath(\n path: string,\n segments: readonly RawSegment[],\n _enc: EncodingCharacters,\n): string | undefined {\n const parsed = parsePath(path);\n\n // A segment-only path (no field specified) has no string value.\n if (parsed.fieldIndex === 0) return undefined;\n\n const found = findSegment(segments, parsed.segmentType, parsed.segmentIndex);\n if (found === undefined) return undefined;\n\n const { seg } = found;\n\n // MSH indexing is offset by -1 relative to the internal `fields[]` array:\n // Phase 2 tokenize placed the field-separator char at `fields[0]` and the\n // encoding-chars string at `fields[1]`, so MSH-1 → fields[0], MSH-2 →\n // fields[1], MSH-3 → fields[2], ..., MSH-12 → fields[11]. All other\n // segments use a straight 1:1 mapping (PID.5 → fields[5]) because\n // `fields[0]` is the segment-name placeholder (D-02, D-05 in\n // 03-CONTEXT.md; verified by test/parser-tokenize.test.ts:29-36).\n const rawFieldIndex = parsed.segmentType === \"MSH\" ? parsed.fieldIndex - 1 : parsed.fieldIndex;\n const field = seg.fields[rawFieldIndex];\n if (field === undefined) return undefined;\n\n const repIndex = parsed.repetitionIndex ?? 0;\n const rep = field.repetitions[repIndex];\n if (rep === undefined) return undefined;\n\n const compIndex = (parsed.componentIndex ?? 1) - 1;\n const comp = rep.components[compIndex];\n if (comp === undefined) return undefined;\n\n const subIndex = (parsed.subcomponentIndex ?? 1) - 1;\n const sub = comp.subcomponents[subIndex];\n\n if (sub !== undefined) {\n // The tokenizer already unescaped every subcomponent on parse (parser-02),\n // so the stored value is decoded: return it directly. A second unescape\n // would double-decode a value whose own bytes look like an escape (wire\n // `\\E\\F\\E\\` → decoded `\\F\\`, which a second pass would wrongly turn into\n // `|`). Emit fidelity is handled separately by the raw overlay (HL7-ESC).\n return sub;\n }\n\n // D-04 depth-collapse: when the caller asked for subcomponent 1 and\n // the component has exactly one subcomponent, returning\n // `comp.subcomponents[0]` already covered that case above. The edge\n // case here is when `subIndex > subcomponents.length - 1`: we fall\n // through to `undefined`. No additional branch needed.\n return undefined;\n}\n\n/**\n * Locate the `occurrence`-th segment of `segmentType` in document order.\n * Returns the matched `RawSegment`.\n *\n * @internal\n */\nfunction findSegment(\n segments: readonly RawSegment[],\n segmentType: string,\n occurrence: number,\n): { readonly seg: RawSegment } | undefined {\n let seen = 0;\n for (const s of segments) {\n if (s === undefined) continue;\n if (s.name === segmentType) {\n if (seen === occurrence) return { seg: s };\n seen++;\n }\n }\n return undefined;\n}\n\n/**\n * Consume a run of ASCII digits from `path` starting at `start`. Returns the\n * parsed non-negative integer and the next cursor position. Throws\n * `TypeError` when `path[start]` is not a digit (e.g. after a trailing dot\n * with no number, or a negative sign).\n *\n * @internal\n */\nfunction readDigits(path: string, start: number): { value: number; next: number } {\n let j = start;\n while (j < path.length) {\n const ch = path.charCodeAt(j);\n if (ch < 0x30 || ch > 0x39) break;\n j += 1;\n }\n if (j === start) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (expected digit at position ${String(start)}).`,\n );\n }\n const slice = path.slice(start, j);\n // Safe: we just verified every char is 0-9.\n return { value: parseInt(slice, 10), next: j };\n}\n\n/**\n * Consume a `[N]` bracket expression from `path` starting at `start` (which\n * must be the `[`). Returns the non-negative integer and the next cursor\n * position. Throws `TypeError` on empty brackets, non-digit content, missing\n * close bracket, or negative index.\n *\n * @internal\n */\nfunction readBracket(path: string, start: number): { value: number; next: number } {\n // Caller guarantees path.charAt(start) === \"[\"\n const close = path.indexOf(\"]\", start + 1);\n if (close === -1) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (unclosed '[' at position ${String(start)}).`,\n );\n }\n const inner = path.slice(start + 1, close);\n if (inner.length === 0) {\n throw new TypeError(`Invalid HL7 dot-path: \"${path}\" (empty brackets).`);\n }\n if (!/^\\d+$/u.test(inner)) {\n throw new TypeError(\n `Invalid HL7 dot-path: \"${path}\" (bracket content \"${inner}\" is not a non-negative integer).`,\n );\n }\n return { value: parseInt(inner, 10), next: close + 1 };\n}\n\n/**\n * Return a `DotPath` from a mutable builder, honoring\n * `exactOptionalPropertyTypes`: optional keys are only present on the\n * returned object when their builder value is defined.\n *\n * @internal\n */\nfunction freezeDotPath(m: MutableDotPath): DotPath {\n const base: {\n segmentType: string;\n segmentIndex: number;\n fieldIndex: number;\n repetitionIndex?: number;\n componentIndex?: number;\n subcomponentIndex?: number;\n } = {\n segmentType: m.segmentType,\n segmentIndex: m.segmentIndex,\n fieldIndex: m.fieldIndex,\n };\n if (m.repetitionIndex !== undefined) base.repetitionIndex = m.repetitionIndex;\n if (m.componentIndex !== undefined) base.componentIndex = m.componentIndex;\n if (m.subcomponentIndex !== undefined) base.subcomponentIndex = m.subcomponentIndex;\n return base;\n}\n","/**\n * HL7 emit primitives for the `@cosyte/hl7` serializer pipeline,\n * walks a `RawField` / `RawSegment` tree and produces spec-clean HL7 text\n * by joining repetitions, components, and subcomponents with the active\n * delimiters and re-escaping user content via `reescape`.\n *\n * Decisions honored:\n * - D-02: trailing empty components and subcomponents are stripped;\n * `RawField.isNull === true` is preserved as the two-character literal `\"\"`.\n * - D-04: a subcomponent with no fidelity overlay passes through\n * `reescape(sub, enc)`: the 5 active delimiters + `\\n` (via `\\.br\\`) + a\n * decoded CR (via `\\X0D\\`) are re-escaped; other already-decoded text passes\n * through as plain characters. A subcomponent whose parse recorded original\n * wire bytes in `RawComponent.rawSubcomponents` (HL7-ESC: a recognize-and-\n * preserve escape like `\\H\\`/`\\Z..\\`, or a hex escape like `\\X41\\`) is\n * emitted from that overlay **verbatim**, so those families round-trip\n * byte-for-byte instead of canonicalizing.\n * - D-06 guard: `emitSegment` throws when called with an MSH segment,\n * MSH must be routed through `to-string.ts`'s special-case path, which\n * inlines MSH-1 and MSH-2 instead of running them through `emitField`\n * (running MSH-2 through `emitField` would re-escape the encoding chars\n * and produce garbage). The throw is a deliberate deviation from D-07\n * purity: it catches programmer misuse at the call site instead of\n * silently corrupting wire output.\n * - D-07: pure for all non-MSH inputs: never warns, never throws.\n *\n * Not part of the public API (no re-export from `src/index.ts`). Phase 6\n * profile hooks may compose around `emitSegment` / `emitField`.\n * @internal\n */\n\nimport { reescape } from \"../parser/escapes.js\";\nimport type { EncodingCharacters, RawField, RawRepetition, RawSegment } from \"../parser/types.js\";\n\n/**\n * Emit a single HL7 field as its spec-clean string fragment. Joins\n * repetitions with `enc.repetition`; each repetition renders its\n * components (joined with `enc.component`), each component renders its\n * subcomponents (joined with `enc.subcomponent`), and each subcomponent\n * runs through `reescape` (D-04).\n *\n * D-02 rules:\n * - `field.isNull === true` returns the two-character string `\"\"` (literal\n * quote-quote: HL7 explicit null), regardless of repetitions content.\n * - Trailing empty subcomponents inside a component are stripped.\n * - Trailing empty components inside a repetition are stripped.\n * - A field with zero repetitions renders as the empty string.\n *\n * @internal\n */\nexport function emitField(field: RawField, enc: EncodingCharacters): string {\n if (field.isNull) return '\"\"';\n if (field.repetitions.length === 0) return \"\";\n const repStrings: string[] = [];\n for (const rep of field.repetitions) {\n repStrings.push(emitRepetition(rep, enc));\n }\n return repStrings.join(enc.repetition);\n}\n\n/** @internal */\nfunction emitRepetition(rep: RawRepetition, enc: EncodingCharacters): string {\n const compStrings: string[] = [];\n for (const comp of rep.components) {\n const overlay = comp.rawSubcomponents;\n const subStrings: string[] = [];\n for (let i = 0; i < comp.subcomponents.length; i++) {\n // Escape-fidelity overlay (HL7-ESC): when the tokenizer recorded the\n // subcomponent's original wire bytes (a preserve-or-hex escape whose\n // decoded form does not re-escape byte-verbatim), emit them verbatim,\n // otherwise re-escape the decoded value. Delimiter escapes have no\n // overlay and take the reescape path, exactly as before.\n const raw = overlay?.[i];\n subStrings.push(raw ?? reescape(comp.subcomponents[i] ?? \"\", enc));\n }\n // D-02 trailing-empty strip at subcomponent level.\n while (subStrings.length > 0 && subStrings[subStrings.length - 1] === \"\") {\n subStrings.pop();\n }\n compStrings.push(subStrings.join(enc.subcomponent));\n }\n // D-02 trailing-empty strip at component level.\n while (compStrings.length > 0 && compStrings[compStrings.length - 1] === \"\") {\n compStrings.pop();\n }\n return compStrings.join(enc.component);\n}\n\n/**\n * Emit a single non-MSH HL7 segment as its spec-clean string fragment:\n * `<seg.name>` + `enc.field` + `<fields[1..N] joined by enc.field>`.\n *\n * **IMPORTANT: MSH guard:** If `seg.name === \"MSH\"` this function\n * THROWS. MSH requires D-06's special-case emission (MSH-1 = single\n * delimiter char, MSH-2 = 4 literal encoding chars: neither is routed\n * through `emitField`, because running MSH-2 through `emitField` would\n * re-escape the encoding chars and produce garbage output). The only\n * correct caller for MSH is `to-string.ts::emitMessage`, which inlines\n * MSH-1/MSH-2 before handing MSH-3..N off to `emitField`. This guard\n * is a deliberate deviation from D-07 \"never throws\": it catches\n * programmer misuse loudly at the call site rather than silently\n * corrupting wire output.\n *\n * For non-MSH segments (PID, OBX, etc.) this function is pure: it\n * skips `fields[0]` (name placeholder) and joins `fields[1..N]` via\n * `emitField` with `enc.field` separators.\n *\n * @internal\n */\nexport function emitSegment(seg: RawSegment, enc: EncodingCharacters): string {\n if (seg.name === \"MSH\") {\n throw new Error(\n \"emitSegment: MSH must be routed through to-string.ts's MSH path per D-06 \" +\n \"(special-case MSH-1/MSH-2 encoding-char emission). Running MSH through \" +\n \"emitSegment would re-escape the encoding chars and produce garbage output.\",\n );\n }\n const parts: string[] = [seg.name];\n for (let i = 1; i < seg.fields.length; i++) {\n const f = seg.fields[i];\n parts.push(f === undefined ? \"\" : emitField(f, enc));\n }\n return parts.join(enc.field);\n}\n","/**\n * Formatted-text rendering for `@cosyte/hl7`: turns HL7 v2 §2.7\n * escape/formatting-bearing field content into a **normalized display model**\n * a human (or a downstream display / FHIR `.text`) can read, instead of the\n * raw `\\H\\`/`\\.br\\` sentinels the lenient parser preserves.\n *\n * This is the read-projection half of Phase R: `renderText` never mutates the\n * raw field value (rendering is opt-in on top of the tolerant parse), and it\n * **never fabricates**: an escape it cannot render is preserved as its literal\n * characters AND flagged in {@link RenderedText.unrenderedSequences}, never\n * dropped and never replaced with a guessed glyph.\n *\n * **Clinical-safety angle.** A lab/clinical narrative surfaced with raw\n * `\\.br\\` / `\\H\\` sentinels is *misread* by a human; that is the harm this\n * prevents. Formatting commands become real whitespace/line-breaks and\n * highlight boundaries are dropped from the plain text (and exposed as\n * `highlighted` runs for consumers that want emphasis), so what a reader sees\n * is the intended text: never a sentinel and never an invented character.\n *\n * ## Spec traceability (HL7 v2 Chapter 2, §2.7: confirmed firsthand\n * 2026-07-21 against the v2.5.1 and v2.8.2 chapter text; section numbers shift\n * by version)\n *\n * - **§2.7.1 formatting codes**: the delimiter/escape substitutions\n * `\\F\\ \\S\\ \\T\\ \\R\\ \\E\\` (→ the message's own field/component/subcomponent/\n * repetition/escape characters), the highlight pair `\\H\\` (start) / `\\N\\`\n * (normal, i.e. end), and (v2.7+) `\\P\\` (the truncation character).\n * - **§2.7.2/2.7.3 charset switch**: `\\Cxxyy\\` (single-byte) / `\\Mxxyyzz\\`\n * (multi-byte, `zz` optional): selects an alternate MSH-18 character set for\n * the following run. Decoding requires stateful charset context this module\n * does not have, so a switch is **preserved + flagged**, never guessed.\n * - **§2.7.5/2.7.6 hex**: `\\Xdddd…\\`: consecutive **pairs** of hex digits,\n * each pair one 8-bit byte.\n * - **§2.7.6/2.7.7 formatting commands** (FT data type): `\\.br\\` `\\.sp\\`\n * `\\.in\\` `\\.ti\\` `\\.fi\\` `\\.nf\\` `\\.ce\\` `\\.sk\\`; `.sp` takes an optional\n * positive count, `.in`/`.ti` a signed indent, `.sk` a space count. Rendered\n * to a conservative plain-text normalization (see the table below).\n * - **§2.7.7/2.7.8 locally-defined**: `\\Zdddd…\\`: opaque, meaning is a\n * sender/receiver agreement, so **preserved + flagged**, never interpreted.\n *\n * ## Normalization policy (conservative, documented: not a page-layout engine)\n *\n * | Escape | Rendered as |\n * | --------------------------- | --------------------------------------------- |\n * | `\\F\\ \\S\\ \\T\\ \\R\\ \\E\\ \\P\\` | the literal delimiter / escape / trunc char |\n * | `\\Xdddd…\\` | the decoded byte(s) |\n * | `\\H\\` / `\\N\\` | dropped from text; toggles a `highlighted` run |\n * | `\\.br\\` | one line break |\n * | `\\.sp\\` / `\\.sp <n>\\` | `n` line breaks (default 1, clamped to 100) |\n * | `\\.ce\\` | one line break (centering dropped) |\n * | `\\.in <n>\\` / `\\.ti <n>\\` | dropped (indentation: exact column math is a defer) |\n * | `\\.fi\\` / `\\.nf\\` | dropped (word-wrap mode: no content) |\n * | `\\.sk <n>\\` | `n` spaces (default 1, clamped to 100) |\n * | `\\Cxxyy\\` `\\Mxxyyzz\\` `\\Zdddd…\\`, malformed / unterminated | literal chars, **preserved + flagged** |\n *\n * A raw CR / LF / CRLF already present in the input (e.g. a `\\.br\\` the parser\n * already decoded to `\\n`, or a hex-encoded `\\X0D\\`/`\\X0A\\`) is normalized to\n * one line break too, so rendering a pre-decoded `Field.value` and rendering\n * the wire text agree. A `\\.sp <n>\\`/`\\.sk <n>\\` count is clamped to a small\n * maximum (a conservative renderer need not honor a pathological skip, and an\n * unbounded count is a memory / `RangeError` foot-gun on a hostile feed).\n *\n * @packageDocumentation\n */\n\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { EncodingCharacters } from \"../parser/types.js\";\n\n/**\n * One contiguous run of rendered display text, tagged with whether it fell\n * inside a `\\H\\`…\\`\\N\\` highlight span. Runs preserve emphasis boundaries that\n * the flat {@link RenderedText.text} intentionally drops.\n */\nexport interface TextRun {\n /**\n * The literal display text of this run: escape sentinels already resolved\n * (delimiter/hex decoded, formatting → whitespace/line breaks). Never\n * contains a formatting sentinel; may contain the newline used for breaks.\n */\n readonly text: string;\n /** `true` when this run is inside a `\\H\\`…`\\N\\` highlight span. */\n readonly highlighted: boolean;\n}\n\n/**\n * The normalized display model produced by {@link renderText}: a flat\n * plain-text string plus the structured highlight-aware runs, plus an\n * honesty list of the escape sequences that were preserved rather than\n * rendered.\n */\nexport interface RenderedText {\n /**\n * The full plain-text normalization: formatting commands become\n * whitespace / line breaks and highlight boundaries are dropped. This is\n * the string to show a human or feed a downstream `.text`. Equal to the\n * concatenation of every {@link runs} entry's `text`.\n */\n readonly text: string;\n /**\n * The structured, highlight-aware form: `{ text, highlighted }` runs in\n * document order. Empty runs are elided. Use this to preserve emphasis\n * (bold / reverse-video / etc.) that the flat {@link text} drops.\n */\n readonly runs: readonly TextRun[];\n /**\n * The escape sequences `renderText` **preserved verbatim instead of\n * rendering**: vendor `\\Zdddd…\\`, charset switches `\\Cxxyy\\`/`\\Mxxyyzz\\`,\n * and any malformed / unterminated sequence. Their literal characters ALSO\n * appear in {@link text}/{@link runs} (never silently dropped); this list\n * exists so a consumer can detect that a non-render decision was made and\n * surface or route those sequences deliberately. Empty when everything\n * rendered cleanly.\n */\n readonly unrenderedSequences: readonly string[];\n}\n\n/** Options for {@link renderText}. */\nexport interface RenderTextOptions {\n /**\n * The string emitted for each line break (`\\.br\\`, `\\.sp\\`, `\\.ce\\`, and a\n * raw CR/LF/CRLF in the input). Defaults to `\"\\n\"`. Set `\"\\r\\n\"` for\n * Windows-style display, or `\" \"` to flatten a note to a single line.\n */\n readonly newline?: string;\n}\n\n/** The eight FT formatting commands and their argument shapes. @internal */\nconst FORMATTING_RE = /^\\.(br|sp|in|ti|fi|nf|ce|sk)[ +]?([+-]?\\d+)?$/u;\n\n/** Spec-default truncation char (HL7 v2.7+ §2.5.5.2) when MSH-2 declared none. */\nconst DEFAULT_TRUNCATION_CHAR = \"#\";\n\n/**\n * Upper bound on a `\\.sp <n>\\` / `\\.sk <n>\\` repeat count. A conservative\n * normalization does not need to honor a pathological vertical/horizontal skip,\n * and an unbounded count is a memory-exhaustion / `RangeError` foot-gun on a\n * corrupted or adversarial feed (a ~15-byte field could otherwise demand a\n * multi-hundred-MB allocation). Clamped, documented, and fail-safe.\n * @internal\n */\nconst MAX_FORMAT_REPEAT = 100;\n\n/** Normalize any CR / LF / CRLF inside decoded output to the break string. @internal */\nfunction normalizeBreaks(s: string, newline: string): string {\n return s.replace(/\\r\\n|\\r|\\n/gu, newline);\n}\n\n/** Parse and clamp a formatting-command repeat count to `[1, MAX_FORMAT_REPEAT]`. @internal */\nfunction clampCount(arg: string | undefined): number {\n if (arg === undefined) return 1;\n // `arg` is regex-validated as `[+-]?\\d+`, so Number is finite; a value < 1\n // (absent or negative skip) is meaningless → treat as 1.\n const n = Math.trunc(Number(arg));\n if (!Number.isFinite(n) || n < 1) return 1;\n return Math.min(n, MAX_FORMAT_REPEAT);\n}\n\n/**\n * Render an HL7 v2 escape/formatting-bearing string into a normalized display\n * model (plain text + highlight-aware runs). A **read projection**: it never\n * mutates the underlying field, and it never fabricates: an escape it cannot\n * render is preserved as literal characters and flagged in\n * {@link RenderedText.unrenderedSequences}.\n *\n * `input` is the field's escape-bearing text. Pass the **wire form** (e.g.\n * `Field.text`, byte-verbatim for parsed content) for the most faithful\n * result: a wire `\\E\\H\\E\\` (an escaped literal backslash-H-backslash) then\n * renders as the three literal characters `\\H\\`, never as a highlight. Passing\n * an already-decoded `Field.value` also works: its `\\.br\\` is already a\n * newline (rendered as one line break) and its `\\H\\`/formatting sentinels are\n * still recognized.\n *\n * Never throws for any input.\n *\n * @param input - the escape-bearing field text to render.\n * @param enc - the message's encoding characters (for `\\F\\`/`\\S\\`/… targets);\n * defaults to the HL7 standard `|^~\\&`.\n * @param opts - see {@link RenderTextOptions}.\n * @returns the normalized {@link RenderedText}.\n *\n * @example\n * ```ts\n * import { renderText } from \"@cosyte/hl7\";\n *\n * const r = renderText(\"Specimen received.\\\\.br\\\\Gross exam \\\\H\\\\normal\\\\N\\\\.\");\n * r.text;\n * // \"Specimen received.\\nGross exam normal.\"\n * r.runs;\n * // [ { text: \"Specimen received.\\nGross exam \", highlighted: false },\n * // { text: \"normal\", highlighted: true },\n * // { text: \".\", highlighted: false } ]\n * r.unrenderedSequences; // []\n * ```\n */\nexport function renderText(\n input: string,\n enc: EncodingCharacters = DEFAULT_ENCODING_CHARACTERS,\n opts?: RenderTextOptions,\n): RenderedText {\n const esc = enc.escape;\n const newline = opts?.newline ?? \"\\n\";\n const runs: TextRun[] = [];\n const unrendered: string[] = [];\n\n let highlighted = false;\n let current = \"\";\n\n const flush = (): void => {\n if (current !== \"\") {\n runs.push({ text: current, highlighted });\n current = \"\";\n }\n };\n\n let i = 0;\n const len = input.length;\n while (i < len) {\n const ch = input.charAt(i);\n\n // Already-decoded line breaks (raw CR / LF / CRLF, e.g. a \\.br\\ the parser\n // decoded upstream) normalize to one break so wire-form and decoded-form\n // input agree.\n if (ch === \"\\r\" || ch === \"\\n\") {\n current += newline;\n i += ch === \"\\r\" && input.charAt(i + 1) === \"\\n\" ? 2 : 1;\n continue;\n }\n\n if (ch !== esc) {\n current += ch;\n i++;\n continue;\n }\n\n // An escape character: find its closing partner.\n const close = input.indexOf(esc, i + 1);\n if (close === -1) {\n // Unterminated: preserve the remainder verbatim and flag it. Never a\n // throw; the scan is strictly O(n).\n const tail = input.slice(i);\n current += tail;\n unrendered.push(tail);\n break;\n }\n\n const body = input.slice(i + 1, close);\n const literal = esc + body + esc;\n\n if (body === \"H\") {\n flush();\n highlighted = true;\n } else if (body === \"N\") {\n flush();\n highlighted = false;\n } else {\n const decoded = decodeBody(body, enc, newline);\n if (decoded !== null) {\n current += decoded;\n } else {\n // Known-but-unrenderable (charset switch), vendor (\\Z..\\), or\n // malformed/garbage: preserve literal + flag. Never dropped, never\n // guessed.\n current += literal;\n unrendered.push(literal);\n }\n }\n i = close + 1;\n }\n\n flush();\n const text = runs.reduce((acc, r) => acc + r.text, \"\");\n return { text, runs, unrenderedSequences: unrendered };\n}\n\n/**\n * Decode one escape body to its rendered display text, or `null` when the body\n * is not renderable (charset switch, vendor `\\Z..\\`, or malformed) and must be\n * preserved + flagged by the caller.\n *\n * @internal\n */\nfunction decodeBody(body: string, enc: EncodingCharacters, newline: string): string | null {\n // §2.7.1 delimiter / escape / truncation substitutions → the literal char.\n switch (body) {\n case \"F\":\n return enc.field;\n case \"S\":\n return enc.component;\n case \"T\":\n return enc.subcomponent;\n case \"R\":\n return enc.repetition;\n case \"E\":\n return enc.escape;\n case \"P\":\n return enc.truncation ?? DEFAULT_TRUNCATION_CHAR;\n default:\n break;\n }\n\n // §2.7.6 formatting commands (FT) → conservative whitespace normalization.\n if (body.charAt(0) === \".\") {\n const m = FORMATTING_RE.exec(body);\n if (m !== null) return renderFormatting(m[1] ?? \"\", m[2], newline);\n // A dot body that is not one of the eight known commands is not a\n // formatting command: fall through to unknown handling.\n return null;\n }\n\n // §2.7.5 hex: consecutive hex-digit PAIRS, each pair one byte.\n if (body.charAt(0) === \"X\") {\n const hex = body.slice(1);\n if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9A-Fa-f]+$/u.test(hex)) {\n return null;\n }\n let out = \"\";\n for (let j = 0; j < hex.length; j += 2) {\n out += String.fromCharCode(parseInt(hex.slice(j, j + 2), 16));\n }\n // A hex-encoded CR/LF (a legitimate wire encoding of a line break) must\n // normalize to a break exactly like a raw CR/LF, so rendering the wire form\n // and a pre-decoded value agree.\n return normalizeBreaks(out, newline);\n }\n\n // §2.7.2/2.7.3 charset switch and §2.7.7 vendor \\Z..\\ are recognized but\n // cannot be rendered without state we do not carry → preserve + flag.\n return null;\n}\n\n/**\n * Render one recognized FT formatting command to conservative whitespace.\n * `cmd` is the command letters (`br`/`sp`/…); `arg` the optional numeric\n * argument (already validated as an integer by {@link FORMATTING_RE}).\n *\n * @internal\n */\nfunction renderFormatting(cmd: string, arg: string | undefined, newline: string): string {\n switch (cmd) {\n case \"br\":\n case \"ce\":\n // Hard line break (centering is dropped: we are not a layout engine).\n return newline;\n case \"sp\":\n // Vertical skip: n line breaks, default 1 (clamped: see MAX_FORMAT_REPEAT).\n return newline.repeat(clampCount(arg));\n case \"sk\":\n // Horizontal skip: n spaces, default 1 (clamped: see MAX_FORMAT_REPEAT).\n return \" \".repeat(clampCount(arg));\n case \"in\":\n case \"ti\":\n case \"fi\":\n case \"nf\":\n default:\n // Indentation and word-wrap mode toggles carry no textual content in a\n // plain-text projection; exact column math is a documented defer.\n return \"\";\n }\n}\n","/**\n * Internal helpers shared across the 10 composite parsers (XPN, XAD, CX, CWE,\n * CE, XTN, PL, TS, NM, HD). Centralizes the \"read subcomponent, return undefined\n * on absent\" pattern so composites stay short and every composite handles\n * missing/empty components identically.\n *\n * Subcomponents are returned VERBATIM: the tokenizer (parser-02) already\n * unescaped each one on parse, so the stored value is decoded: a second\n * `unescape` here would double-decode a value whose own bytes look like an\n * escape (HL7-VALUE-REDECODE). The `enc` params are retained for signature\n * uniformity across the composite read path.\n *\n * Not part of the public API: never re-exported from `src/index.ts`.\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\n/**\n * Read `subcomponents[index]` from a component and return it (already decoded\n * by the tokenizer: see the module header). Returns `undefined` when:\n * - `component` is `undefined` (missing component).\n * - `index` is out of range.\n * - the subcomponent is the empty string `\"\"`.\n *\n * The empty-string → undefined mapping is deliberate: composite interfaces\n * use OPTIONAL fields, which must be OMITTED when absent\n * (exactOptionalPropertyTypes). Callers use the `undefined` return as the\n * signal to skip assignment.\n *\n * @internal\n */\nexport function readSubcomponent(\n component: RawComponent | undefined,\n index: number,\n _enc: EncodingCharacters,\n): string | undefined {\n if (component === undefined) return undefined;\n const sub = component.subcomponents[index];\n if (sub === undefined || sub === \"\") return undefined;\n // The tokenizer already unescaped every subcomponent on parse (parser-02), so\n // the stored value is decoded: return it directly. A second unescape would\n // double-decode a value whose own bytes look like an escape (wire `\\E\\F\\E\\` →\n // decoded `\\F\\`, which a second pass would wrongly turn into `|`). Emit\n // fidelity is handled separately by the raw overlay (HL7-ESC). `_enc` is\n // retained for signature uniformity across the composite read helpers.\n return sub;\n}\n\n/**\n * Read the first subcomponent of `components[index]` and return it (already\n * decoded by the tokenizer). Shorthand for\n * `readSubcomponent(rep.components[index], 0, enc)`. Most composite fields\n * are single-subcomponent values: this helper keeps composite parsers\n * declarative.\n *\n * @internal\n */\nexport function readComponent(\n rep: RawRepetition,\n index: number,\n enc: EncodingCharacters,\n): string | undefined {\n return readSubcomponent(rep.components[index], 0, enc);\n}\n\n/**\n * Read every component at or beyond `fromIndex`: the components a fixed-shape\n * composite parser does NOT model: so a coded element that grew across HL7\n * versions (e.g. the v2.7 CWE second-alternate triplet + coding-system OIDs at\n * components 10–22) is never silently truncated. Each entry is the\n * first-subcomponent value (already decoded), positionally aligned: an absent\n * interior component is preserved as `\"\"` so a caller can map an index back to\n * its HL7 component number (`fromIndex + i`).\n *\n * Trailing empties are stripped (D-02 parity), and the whole result is\n * `undefined` when there is nothing beyond `fromIndex` or every extra component\n * is empty: so the optional `extraComponents` key is OMITTED rather than set\n * to an empty array (exactOptionalPropertyTypes). The returned array is frozen.\n *\n * @internal\n */\nexport function readExtraComponents(\n rep: RawRepetition,\n fromIndex: number,\n enc: EncodingCharacters,\n): readonly string[] | undefined {\n const total = rep.components.length;\n if (total <= fromIndex) return undefined;\n\n const collected: string[] = [];\n let lastContentAt = -1;\n for (let i = fromIndex; i < total; i++) {\n const value = readComponent(rep, i, enc);\n if (value !== undefined) {\n lastContentAt = collected.length;\n collected.push(value);\n } else {\n collected.push(\"\");\n }\n }\n\n if (lastContentAt === -1) return undefined;\n return Object.freeze(collected.slice(0, lastContentAt + 1));\n}\n","/**\n * CE: HL7 v2 Coded Element composite. 6-component coded-element shape\n * parsed from a `RawRepetition` on demand by `Field.asCe()` (wired in Plan\n * 04). Fields are OMITTED when absent (exactOptionalPropertyTypes): NEVER\n * set to `undefined`.\n *\n * CE is the older, simpler sibling of CWE: 6 components, no version ids,\n * no originalText. Still common in OBX.3 and similar observation-identifier\n * slots on older messages. CE was deprecated at HL7 v2.5 and withdrawn at\n * v2.6 in favor of CWE; the two are read uniformly here: reading a\n * CWE-shaped value through `asCe()` preserves components 7+ on\n * `extraComponents` rather than dropping them, so neither accessor is lossy.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent, readExtraComponents } from \"./_shared.js\";\n\n/**\n * HL7 v2 Coded Element (CE): coded element per HL7 Chapter 2. All 6\n * components are optional. Fields are OMITTED when the underlying component\n * is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. identifier (e.g. \"GLU\")\n * 2. text (human-readable, e.g. \"Glucose\")\n * 3. nameOfCodingSystem (e.g. \"LN\" for LOINC)\n * 4. alternateIdentifier\n * 5. alternateText\n * 6. nameOfAlternateCodingSystem\n *\n * Components 7+ (present when a CWE-shaped value is read through the CE\n * accessor: e.g. version ids, originalText) are surfaced verbatim on\n * `extraComponents` rather than dropped.\n *\n * @example\n * ```ts\n * import type { CE } from \"@cosyte/hl7\";\n * const code: CE = { identifier: \"GLU\", text: \"Glucose\", nameOfCodingSystem: \"LN\" };\n * ```\n */\nexport interface CE {\n readonly identifier?: string;\n readonly text?: string;\n readonly nameOfCodingSystem?: string;\n readonly alternateIdentifier?: string;\n readonly alternateText?: string;\n readonly nameOfAlternateCodingSystem?: string;\n /**\n * Components beyond the modeled 6 (HL7 component 7 onward), preserved\n * verbatim and in order. Non-empty only when a CWE-shaped value is read\n * through the CE accessor; OMITTED otherwise. An absent interior component\n * is preserved as `\"\"` so `extraComponents[i]` maps to HL7 component\n * `7 + i`.\n */\n readonly extraComponents?: readonly string[];\n}\n\n/**\n * Parse an HL7 v2 CE repetition into a structured `CE` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseCe, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"GLU\"] },\n * { subcomponents: [\"Glucose\"] },\n * { subcomponents: [\"LN\"] },\n * ] };\n * const ce = parseCe(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(ce.identifier); // \"GLU\"\n * ```\n */\nexport function parseCe(rep: RawRepetition, enc: EncodingCharacters): CE {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<CE> = {};\n\n const identifier = readComponent(rep, 0, enc);\n if (identifier !== undefined) out.identifier = identifier;\n\n const text = readComponent(rep, 1, enc);\n if (text !== undefined) out.text = text;\n\n const nameOfCodingSystem = readComponent(rep, 2, enc);\n if (nameOfCodingSystem !== undefined) out.nameOfCodingSystem = nameOfCodingSystem;\n\n const alternateIdentifier = readComponent(rep, 3, enc);\n if (alternateIdentifier !== undefined) out.alternateIdentifier = alternateIdentifier;\n\n const alternateText = readComponent(rep, 4, enc);\n if (alternateText !== undefined) out.alternateText = alternateText;\n\n const nameOfAlternateCodingSystem = readComponent(rep, 5, enc);\n if (nameOfAlternateCodingSystem !== undefined) {\n out.nameOfAlternateCodingSystem = nameOfAlternateCodingSystem;\n }\n\n const extraComponents = readExtraComponents(rep, 6, enc);\n if (extraComponents !== undefined) out.extraComponents = extraComponents;\n\n return out;\n}\n","/**\n * CWE: HL7 v2 Coded with Exceptions composite. 9-component coded-element\n * shape parsed from a `RawRepetition` on demand by `Field.asCwe()` (wired in\n * Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes),\n * NEVER set to `undefined`.\n *\n * Note: full HL7 v2.6+ CWE has 22 components. v1 of this library ships the 9\n * core components: identifier, text, coding-system trio + version ids, and\n * originalText: which cover the common HL7 v2.5 use cases. v2 may restore\n * the full shape. Components 10+ that a newer (v2.7+) sender supplies: the\n * second-alternate triplet and the coding-system / value-set OIDs: are NOT\n * dropped: they are preserved verbatim on `extraComponents` so the typed view\n * is lossless across versions.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent, readExtraComponents } from \"./_shared.js\";\n\n/**\n * HL7 v2 Coded with Exceptions (CWE): coded element per HL7 Chapter 2. All\n * 9 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. identifier (e.g. \"GLU\")\n * 2. text (human-readable, e.g. \"Glucose\")\n * 3. nameOfCodingSystem (e.g. \"LN\" for LOINC, \"SCT\" for SNOMED CT)\n * 4. alternateIdentifier\n * 5. alternateText\n * 6. nameOfAlternateCodingSystem\n * 7. codingSystemVersionId\n * 8. alternateCodingSystemVersionId\n * 9. originalText\n *\n * Components 10+ (present only on v2.7+ senders) are surfaced verbatim, in\n * order, on `extraComponents`: never silently truncated.\n *\n * @example\n * ```ts\n * import type { CWE } from \"@cosyte/hl7\";\n * const code: CWE = { identifier: \"GLU\", text: \"Glucose\", nameOfCodingSystem: \"LN\" };\n * ```\n */\nexport interface CWE {\n readonly identifier?: string;\n readonly text?: string;\n readonly nameOfCodingSystem?: string;\n readonly alternateIdentifier?: string;\n readonly alternateText?: string;\n readonly nameOfAlternateCodingSystem?: string;\n readonly codingSystemVersionId?: string;\n readonly alternateCodingSystemVersionId?: string;\n readonly originalText?: string;\n /**\n * Components beyond the modeled 9 (HL7 component 10 onward), preserved\n * verbatim and in order for forward-compatibility with v2.7+ senders that\n * carry the second-alternate triplet or coding-system / value-set OIDs.\n * OMITTED when the element has no components past the 9th. An absent interior\n * component is preserved as `\"\"` so `extraComponents[i]` maps to HL7\n * component `10 + i`.\n */\n readonly extraComponents?: readonly string[];\n}\n\n/**\n * Parse an HL7 v2 CWE repetition into a structured `CWE` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseCwe, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"GLU\"] },\n * { subcomponents: [\"Glucose\"] },\n * { subcomponents: [\"LN\"] },\n * ] };\n * const cwe = parseCwe(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(cwe.identifier); // \"GLU\"\n * ```\n */\nexport function parseCwe(rep: RawRepetition, enc: EncodingCharacters): CWE {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<CWE> = {};\n\n const identifier = readComponent(rep, 0, enc);\n if (identifier !== undefined) out.identifier = identifier;\n\n const text = readComponent(rep, 1, enc);\n if (text !== undefined) out.text = text;\n\n const nameOfCodingSystem = readComponent(rep, 2, enc);\n if (nameOfCodingSystem !== undefined) out.nameOfCodingSystem = nameOfCodingSystem;\n\n const alternateIdentifier = readComponent(rep, 3, enc);\n if (alternateIdentifier !== undefined) out.alternateIdentifier = alternateIdentifier;\n\n const alternateText = readComponent(rep, 4, enc);\n if (alternateText !== undefined) out.alternateText = alternateText;\n\n const nameOfAlternateCodingSystem = readComponent(rep, 5, enc);\n if (nameOfAlternateCodingSystem !== undefined) {\n out.nameOfAlternateCodingSystem = nameOfAlternateCodingSystem;\n }\n\n const codingSystemVersionId = readComponent(rep, 6, enc);\n if (codingSystemVersionId !== undefined) out.codingSystemVersionId = codingSystemVersionId;\n\n const alternateCodingSystemVersionId = readComponent(rep, 7, enc);\n if (alternateCodingSystemVersionId !== undefined) {\n out.alternateCodingSystemVersionId = alternateCodingSystemVersionId;\n }\n\n const originalText = readComponent(rep, 8, enc);\n if (originalText !== undefined) out.originalText = originalText;\n\n const extraComponents = readExtraComponents(rep, 9, enc);\n if (extraComponents !== undefined) out.extraComponents = extraComponents;\n\n return out;\n}\n","/**\n * HD: HL7 v2 Hierarchic Designator composite. 3-component structured\n * identifier (namespace + universal id + universal id type) parsed from a\n * `RawRepetition` on demand. Fields are OMITTED when absent\n * (exactOptionalPropertyTypes): NEVER set to `undefined`.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Hierarchic Designator (HD): per HL7 Chapter 2 data type. All 3\n * components are optional. Fields are OMITTED when the underlying component\n * is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. namespaceId: application- or facility-scoped identifier (e.g. \"EPIC\").\n * 2. universalId: globally-unique id (e.g. an OID or UUID string).\n * 3. universalIdType: classifier for `universalId` (ISO, GUID, UUID, DNS,\n * URI, HL7, HCD, Random, etc.).\n *\n * @example\n * ```ts\n * import type { HD } from \"@cosyte/hl7\";\n * const authority: HD = { namespaceId: \"EPIC\", universalId: \"1.2.840.114350\", universalIdType: \"ISO\" };\n * ```\n */\nexport interface HD {\n readonly namespaceId?: string;\n readonly universalId?: string;\n readonly universalIdType?: string;\n}\n\n/**\n * Parse an HL7 v2 HD repetition into a structured `HD` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseHd, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"EPIC\"] },\n * { subcomponents: [\"1.2.840.114350\"] },\n * { subcomponents: [\"ISO\"] },\n * ] };\n * const hd = parseHd(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(hd.namespaceId); // \"EPIC\"\n * console.log(hd.universalIdType); // \"ISO\"\n * ```\n */\nexport function parseHd(rep: RawRepetition, enc: EncodingCharacters): HD {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<HD> = {};\n\n const namespaceId = readComponent(rep, 0, enc);\n if (namespaceId !== undefined) out.namespaceId = namespaceId;\n\n const universalId = readComponent(rep, 1, enc);\n if (universalId !== undefined) out.universalId = universalId;\n\n const universalIdType = readComponent(rep, 2, enc);\n if (universalIdType !== undefined) out.universalIdType = universalIdType;\n\n return out;\n}\n","/**\n * CX: HL7 v2 Extended Composite ID (with check digit) composite.\n * 10-component structured-identifier shape parsed from a `RawRepetition` on\n * demand by `Field.asCx()` (wired in Plan 04). Fields are OMITTED when\n * absent (exactOptionalPropertyTypes): NEVER set to `undefined`.\n *\n * Component 4 (`assigningAuthority`) is the ONE nested-composite field in\n * this plan: its subcomponents form a 3-field HD (namespaceId, universalId,\n * universalIdType). To reuse `parseHd` without duplicating logic, the parser\n * synthesises a `RawRepetition` whose components wrap the subcomponents of\n * CX component 4.\n *\n * Component 6 (`assigningFacility`) is simplified to a flat `string` in v1\n *: the HL7 spec treats it as HD-shaped, but v1 favours simplicity. Callers\n * who need the full HD can parse the raw string separately.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\nimport { parseHd, type HD } from \"./hd.js\";\n\n/**\n * HL7 v2 Extended Composite ID (CX): structured identifier per HL7 Chapter\n * 2. All 10 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes). `assigningAuthority`\n * uses the nested `HD` shape; `assigningFacility` is flattened to a plain\n * string in v1.\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. idNumber\n * 2. checkDigit\n * 3. checkDigitScheme (ISO 7064, M10, M11, NPI)\n * 4. assigningAuthority (nested HD: 3 subcomponents form a HD composite)\n * 5. identifierTypeCode (MR, SSN, DL, MC, ...)\n * 6. assigningFacility (v1: flattened to string; spec is HD-shaped)\n * 7. effectiveDate (raw HL7 TS string)\n * 8. expirationDate (raw HL7 TS string)\n * 9. assigningJurisdiction (v1: flattened to string)\n * 10. assigningAgencyOrDepartment (v1: flattened to string)\n *\n * @example\n * ```ts\n * import type { CX } from \"@cosyte/hl7\";\n * const mrn: CX = {\n * idNumber: \"123456\",\n * assigningAuthority: { namespaceId: \"EPIC\", universalId: \"1.2.840.114350\", universalIdType: \"ISO\" },\n * identifierTypeCode: \"MR\",\n * };\n * ```\n */\nexport interface CX {\n readonly idNumber?: string;\n readonly checkDigit?: string;\n readonly checkDigitScheme?: string;\n readonly assigningAuthority?: HD;\n readonly identifierTypeCode?: string;\n readonly assigningFacility?: string;\n readonly effectiveDate?: string;\n readonly expirationDate?: string;\n readonly assigningJurisdiction?: string;\n readonly assigningAgencyOrDepartment?: string;\n}\n\n/**\n * Parse CX component 4 (assigningAuthority) from its subcomponents into an\n * `HD`. The 3 HD subfields live as subcomponents of the CX component; we\n * build a synthetic `RawRepetition` where each synthetic component wraps one\n * subcomponent of the CX component as its own single subcomponent. This\n * lets `parseHd` consume the value via its existing `(rep, enc)` signature\n * without reimplementing the read.\n *\n * Returns `undefined` when the source component is missing or every\n * subcomponent is the empty string: prevents stub empty HD objects from\n * leaking into CX output (T-03-02-02 mitigation).\n *\n * @internal\n */\nfunction parseAssigningAuthority(\n comp: RawComponent | undefined,\n enc: EncodingCharacters,\n): HD | undefined {\n if (comp === undefined) return undefined;\n if (comp.subcomponents.every((s) => s === \"\")) return undefined;\n const synthetic: RawRepetition = {\n components: comp.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const hd = parseHd(synthetic, enc);\n return Object.keys(hd).length === 0 ? undefined : hd;\n}\n\n/**\n * Parse an HL7 v2 CX repetition into a structured `CX` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Component 4\n * (`assigningAuthority`) is parsed as a nested `HD`; see component table in\n * the `CX` interface JSDoc for the v1 simplifications on components 6/9/10.\n *\n * @example\n * ```ts\n * import { parseCx, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"123\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"EPIC\", \"1.2.840.114350\", \"ISO\"] },\n * { subcomponents: [\"MR\"] },\n * ] };\n * const cx = parseCx(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(cx.idNumber); // \"123\"\n * console.log(cx.assigningAuthority?.namespaceId); // \"EPIC\"\n * ```\n */\nexport function parseCx(rep: RawRepetition, enc: EncodingCharacters): CX {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<CX> = {};\n\n const idNumber = readComponent(rep, 0, enc);\n if (idNumber !== undefined) out.idNumber = idNumber;\n\n const checkDigit = readComponent(rep, 1, enc);\n if (checkDigit !== undefined) out.checkDigit = checkDigit;\n\n const checkDigitScheme = readComponent(rep, 2, enc);\n if (checkDigitScheme !== undefined) out.checkDigitScheme = checkDigitScheme;\n\n const assigningAuthority = parseAssigningAuthority(rep.components[3], enc);\n if (assigningAuthority !== undefined) out.assigningAuthority = assigningAuthority;\n\n const identifierTypeCode = readComponent(rep, 4, enc);\n if (identifierTypeCode !== undefined) out.identifierTypeCode = identifierTypeCode;\n\n const assigningFacility = readComponent(rep, 5, enc);\n if (assigningFacility !== undefined) out.assigningFacility = assigningFacility;\n\n const effectiveDate = readComponent(rep, 6, enc);\n if (effectiveDate !== undefined) out.effectiveDate = effectiveDate;\n\n const expirationDate = readComponent(rep, 7, enc);\n if (expirationDate !== undefined) out.expirationDate = expirationDate;\n\n const assigningJurisdiction = readComponent(rep, 8, enc);\n if (assigningJurisdiction !== undefined) out.assigningJurisdiction = assigningJurisdiction;\n\n const assigningAgencyOrDepartment = readComponent(rep, 9, enc);\n if (assigningAgencyOrDepartment !== undefined) {\n out.assigningAgencyOrDepartment = assigningAgencyOrDepartment;\n }\n\n return out;\n}\n","/**\n * NM: HL7 v2 Numeric composite. Parses the raw HL7 numeric string into a\n * `number` via the stricter `Number(raw)` (not `parseFloat`, which tolerates\n * trailing garbage like \"12abc\" → 12). `NaN` is normalized to `undefined`\n * per the same no-throw discipline as TS/DTM (D-24 analogous).\n *\n * The raw string is preserved verbatim on the composite so callers needing\n * to round-trip or render with the original precision/formatting can.\n *\n * Zero runtime deps: pure function over the raw tree + `unescape` + stdlib\n * `Number`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\n/**\n * HL7 v2 Numeric (NM) composite. Carries both the raw HL7 numeric string\n * and the parsed JS `number`. `.value` is `undefined` when the raw string\n * is empty or not fully numeric: NEVER throws.\n *\n * Unlike most composites in this phase, both `raw` and `value` are\n * ALWAYS-PRESENT keys (not optional): `value` is explicitly typed as\n * `number | undefined` so callers can destructure uniformly.\n *\n * @example\n * ```ts\n * import type { NM } from \"@cosyte/hl7\";\n * const glucose: NM = { raw: \"120\", value: 120 };\n * const bad: NM = { raw: \"N/A\", value: undefined };\n * ```\n */\nexport interface NM {\n readonly raw: string;\n readonly value: number | undefined;\n}\n\n/**\n * Parse an HL7 v2 NM repetition into `{ raw, value }`. Uses `Number(raw)`\n * for strict numeric parsing: trailing non-numeric characters produce\n * `NaN`, normalized to `undefined`. Empty raw also produces `undefined`.\n *\n * `Number(\"\")` is `0` in JS: which is the wrong answer for an empty HL7\n * numeric field. The explicit empty-string check below returns\n * `{ raw: \"\", value: undefined }` so empty inputs match missing inputs.\n *\n * @example\n * ```ts\n * import { parseNm, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [{ subcomponents: [\"120.5\"] }] };\n * const nm = parseNm(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(nm.value); // 120.5\n * ```\n */\nexport function parseNm(rep: RawRepetition, _enc: EncodingCharacters): NM {\n const comp = rep.components[0];\n // The tokenizer already unescaped every subcomponent on parse (parser-02), so\n // the stored value is decoded: use it directly, never a second unescape (that\n // would double-decode a value whose bytes look like an escape). `_enc` is kept\n // for composite-parser signature uniformity.\n const raw = comp?.subcomponents[0] ?? \"\";\n if (raw === \"\") return { raw, value: undefined };\n const n = Number(raw);\n const value = Number.isNaN(n) ? undefined : n;\n return { raw, value };\n}\n","/**\n * PL: HL7 v2 Person Location composite. 11-component structured-location\n * shape (v1 trimmed from the HL7 v2.5 full 12-component PL: slot 12\n * `entityIdentifier` is rarely used; v2 may restore the full shape) parsed\n * from a `RawRepetition` on demand by `Field.asPl()` (wired in Plan 04).\n * Fields are OMITTED when absent (exactOptionalPropertyTypes): NEVER set\n * to `undefined`.\n *\n * Component 4 (`facility`) is the ONE nested-composite field in this\n * parser: its subcomponents form a 3-field HD (namespaceId, universalId,\n * universalIdType): same synthesis pattern used in `parseCx` for\n * `assigningAuthority`. To reuse `parseHd` without duplicating logic, the\n * parser synthesises a `RawRepetition` whose components wrap the\n * subcomponents of PL component 4.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\nimport { parseHd, type HD } from \"./hd.js\";\n\n/**\n * HL7 v2 Person Location (PL): structured location per HL7 Chapter 2. All\n * 11 v1 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes). `facility` uses the\n * nested `HD` shape; `assigningAuthorityForLocation` is flattened to a\n * plain string in v1 (HL7 spec treats it as HD-shaped).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. pointOfCare: e.g. \"ICU\", \"ED\"\n * 2. room\n * 3. bed\n * 4. facility: nested HD (3 subcomponents form an HD composite)\n * 5. locationStatus: O=Occupied, U=Unoccupied, K=Contaminated, C=Closed,\n * H=Housekeeping, I=Isolated\n * 6. personLocationType: C=Clinic, D=Department, H=Home, N=Nursing Unit,\n * O=Office, R=Revenue Location\n * 7. building\n * 8. floor\n * 9. locationDescription: free-text\n * 10. comprehensiveLocationId\n * 11. assigningAuthorityForLocation (v1: flattened to string)\n *\n * @example\n * ```ts\n * import type { PL } from \"@cosyte/hl7\";\n * const bed: PL = {\n * pointOfCare: \"ICU\",\n * room: \"101\",\n * bed: \"A\",\n * facility: { namespaceId: \"HOSP\", universalId: \"1.2.3\", universalIdType: \"UUID\" },\n * };\n * ```\n */\nexport interface PL {\n readonly pointOfCare?: string;\n readonly room?: string;\n readonly bed?: string;\n readonly facility?: HD;\n readonly locationStatus?: string;\n readonly personLocationType?: string;\n readonly building?: string;\n readonly floor?: string;\n readonly locationDescription?: string;\n readonly comprehensiveLocationId?: string;\n readonly assigningAuthorityForLocation?: string;\n}\n\n/**\n * Parse PL component 4 (facility) from its subcomponents into an `HD`. The\n * 3 HD subfields live as subcomponents of the PL component; we build a\n * synthetic `RawRepetition` where each synthetic component wraps one\n * subcomponent of the PL component as its own single subcomponent. This\n * lets `parseHd` consume the value via its existing `(rep, enc)` signature\n * without reimplementing the read.\n *\n * Returns `undefined` when the source component is missing or every\n * subcomponent is the empty string: prevents stub empty HD objects from\n * leaking into PL output (T-03-03 analogue of CX's T-03-02-02 mitigation).\n *\n * @internal\n */\nfunction parseFacility(comp: RawComponent | undefined, enc: EncodingCharacters): HD | undefined {\n if (comp === undefined) return undefined;\n if (comp.subcomponents.every((s) => s === \"\")) return undefined;\n const synthetic: RawRepetition = {\n components: comp.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const hd = parseHd(synthetic, enc);\n return Object.keys(hd).length === 0 ? undefined : hd;\n}\n\n/**\n * Parse an HL7 v2 PL repetition into a structured `PL` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Component 4\n * (`facility`) is parsed as a nested `HD`; see component table in the `PL`\n * interface JSDoc for the v1 simplifications.\n *\n * @example\n * ```ts\n * import { parsePl, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"ICU\"] },\n * { subcomponents: [\"101\"] },\n * { subcomponents: [\"A\"] },\n * { subcomponents: [\"HOSP\", \"1.2.3\", \"UUID\"] },\n * ] };\n * const pl = parsePl(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(pl.pointOfCare); // \"ICU\"\n * console.log(pl.facility?.namespaceId); // \"HOSP\"\n * ```\n */\nexport function parsePl(rep: RawRepetition, enc: EncodingCharacters): PL {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<PL> = {};\n\n const pointOfCare = readComponent(rep, 0, enc);\n if (pointOfCare !== undefined) out.pointOfCare = pointOfCare;\n\n const room = readComponent(rep, 1, enc);\n if (room !== undefined) out.room = room;\n\n const bed = readComponent(rep, 2, enc);\n if (bed !== undefined) out.bed = bed;\n\n const facility = parseFacility(rep.components[3], enc);\n if (facility !== undefined) out.facility = facility;\n\n const locationStatus = readComponent(rep, 4, enc);\n if (locationStatus !== undefined) out.locationStatus = locationStatus;\n\n const personLocationType = readComponent(rep, 5, enc);\n if (personLocationType !== undefined) out.personLocationType = personLocationType;\n\n const building = readComponent(rep, 6, enc);\n if (building !== undefined) out.building = building;\n\n const floor = readComponent(rep, 7, enc);\n if (floor !== undefined) out.floor = floor;\n\n const locationDescription = readComponent(rep, 8, enc);\n if (locationDescription !== undefined) out.locationDescription = locationDescription;\n\n const comprehensiveLocationId = readComponent(rep, 9, enc);\n if (comprehensiveLocationId !== undefined) out.comprehensiveLocationId = comprehensiveLocationId;\n\n const assigningAuthorityForLocation = readComponent(rep, 10, enc);\n if (assigningAuthorityForLocation !== undefined) {\n out.assigningAuthorityForLocation = assigningAuthorityForLocation;\n }\n\n return out;\n}\n","/**\n * SN: HL7 v2 Structured Numeric composite (HL7 Chapter 2A). Parses an OBX-5\n * value declared as `OBX-2 = SN` into its four positional components so a\n * comparator or a range/ratio is preserved as TYPED data instead of being\n * flattened to a string (where everything past the first component is lost).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. comparator (ST): `>` `<` `>=` `<=` `=` `<>`; absent ⇒ `=`\n * 2. num1 (NM)\n * 3. separatorOrSuffix (ST): `-` (range), `:` / `/` (ratio), `+` (suffix), `.`\n * 4. num2 (NM)\n *\n * Usage examples (the literal OBX-5 string ⇒ what this parses):\n * `>^100` ⇒ greater-than 100 → { comparator: \">\", num1: 100 }\n * `<^10` ⇒ less-than 10 → { comparator: \"<\", num1: 10 }\n * `^100^-^200` ⇒ range 100–200 → { num1: 100, separatorOrSuffix: \"-\", num2: 200 }\n * `^1^:^128` ⇒ titer/ratio 1:128 → { num1: 1, separatorOrSuffix: \":\", num2: 128 }\n *\n * Safety: `num1`/`num2` are parsed with the same strict `Number()` discipline\n * as NM: non-numeric input becomes `undefined`, NEVER `NaN` and never a\n * silently wrong number. The comparator is surfaced ONLY when SN.1 is a\n * recognized operator, so a non-operator value in the comparator slot is never\n * passed off as a real relation.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * The canonical HL7 SN comparator operator set (HL7 Ch 2A SN.1). An absent\n * comparator means `=` per the spec; a value outside this set is treated as\n * non-conformant and is not surfaced as a comparator (fail-safe).\n *\n * @internal\n */\nconst SN_COMPARATORS: ReadonlySet<string> = new Set([\">\", \"<\", \">=\", \"<=\", \"=\", \"<>\"]);\n\n/**\n * HL7 v2 Structured Numeric (SN) composite. `num1` and `num2` are\n * ALWAYS-PRESENT keys (typed `number | undefined`) so callers can destructure\n * uniformly, mirroring `NM`; `comparator` and `separatorOrSuffix` are OMITTED\n * when absent (`exactOptionalPropertyTypes`).\n *\n * An absent `comparator` means the default `=` relation per HL7 Chapter 2A.\n * This library surfaces the structure only: it does not evaluate the\n * inequality, validate the unit, or convert values.\n *\n * @example\n * ```ts\n * import type { SN } from \"@cosyte/hl7\";\n * const gfr: SN = { comparator: \">\", num1: 90, num2: undefined }; // >90\n * const range: SN = { num1: 100, separatorOrSuffix: \"-\", num2: 200 }; // 100-200\n * ```\n */\nexport interface SN {\n /** SN.1 comparator: one of `>` `<` `>=` `<=` `=` `<>`. Omitted ⇒ default `=`. */\n readonly comparator?: string;\n /** SN.2 first numeric value. `undefined` when absent or non-numeric (never `NaN`). */\n readonly num1: number | undefined;\n /** SN.3 separator/suffix: `-` (range), `:`/`/` (ratio), `+` (suffix), `.`. Omitted when absent. */\n readonly separatorOrSuffix?: string;\n /** SN.4 second numeric value. `undefined` when absent or non-numeric (never `NaN`). */\n readonly num2: number | undefined;\n}\n\n/** Strict numeric coercion mirroring NM: empty/non-numeric ⇒ undefined, never NaN. @internal */\nfunction numericOrUndefined(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n return Number.isNaN(n) ? undefined : n;\n}\n\n/**\n * Parse an HL7 v2 SN repetition into a structured `SN`, or `undefined` when the\n * field carries no usable structured-numeric content (empty, or so malformed\n * that no comparator, number, or separator can be recovered). Components are\n * returned verbatim (already decoded by the tokenizer); `num1`/`num2` use strict `Number()` parsing.\n *\n * Fail-safe: a non-operator value in the comparator slot (SN.1) is dropped\n * rather than surfaced as a relation, and a non-numeric SN.2/SN.4 becomes\n * `undefined`: the parser never emits a confident wrong comparator or number.\n *\n * @example\n * ```ts\n * import { parseSn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\">\"] },\n * { subcomponents: [\"90\"] },\n * ] };\n * const sn = parseSn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(sn?.comparator, sn?.num1); // \">\" 90\n * ```\n */\nexport function parseSn(rep: RawRepetition, enc: EncodingCharacters): SN | undefined {\n const rawComparator = readComponent(rep, 0, enc);\n const num1 = numericOrUndefined(readComponent(rep, 1, enc));\n const separatorOrSuffix = readComponent(rep, 2, enc);\n const num2 = numericOrUndefined(readComponent(rep, 3, enc));\n\n const comparator =\n rawComparator !== undefined && SN_COMPARATORS.has(rawComparator) ? rawComparator : undefined;\n\n // Malformed / empty SN: nothing usable recovered → undefined (never a wrong number).\n if (\n comparator === undefined &&\n num1 === undefined &&\n separatorOrSuffix === undefined &&\n num2 === undefined\n ) {\n return undefined;\n }\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<SN> = { num1, num2 };\n if (comparator !== undefined) out.comparator = comparator;\n if (separatorOrSuffix !== undefined) out.separatorOrSuffix = separatorOrSuffix;\n return out as SN;\n}\n","/**\n * HL7 v2 TS/DTM datetime handling for the `@cosyte/hl7` parser pipeline.\n *\n * Phase N (datetime precision + timezone fidelity) reworked this module from a\n * `Date`-coercing helper into a **fidelity-first** parser. The HL7 v2 Ch. 2A\n * DTM datatype is `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`, where the\n * number of populated characters (excluding the offset) sets the precision and\n * a missing offset \"defaults to that of the local time zone of the sender\",\n * NOT UTC and NOT the parser's zone. The old behavior (zero-fill truncations,\n * assume-UTC on a missing offset, eager `Date`) is an architectural defect\n * [S-DTM-IMPL]: it silently shifts a day-only birth date (`|19880705|`) by a\n * day in any negative-offset zone.\n *\n * This module therefore:\n * - `parseDtm(raw)` decodes the DTM into typed **parts** (`DtmParts`),\n * precision preserved, no zero-fill, no `Date`, no UTC assumption.\n * - `formatDtm(parts)` reconstructs the DTM string from parts (round-trip).\n * - `dtmToDate(parts, opts)` materializes an absolute `Date` **only on\n * explicit caller request**, refusing to guess a zone for an offset-less\n * value unless the caller supplies one.\n * - `parseDtmCascade(raw, opts)` is the lenient wrapper (strict DTM → user\n * formats → built-in fallbacks) used by non-composite callers such as\n * `msg.meta.timestamp`; it emits `TIMESTAMP_FALLBACK_FORMAT` on a fallback.\n *\n * Zero runtime deps: only the JS stdlib `Date` / `Date.UTC` APIs and\n * hand-rolled regex / token matchers. No date-fns, no luxon, no moment.\n */\n\nimport { timestampFallbackFormat } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type { Hl7Position } from \"./types.js\";\n\n/**\n * Stated precision of a parsed HL7 DTM value: the number of populated\n * characters (excluding the timezone offset) determines which level applies.\n * A value's precision is preserved verbatim: `|1970|` is `\"year\"`, never\n * silently promoted to a full timestamp.\n *\n * @example\n * ```ts\n * import { parseDtm } from \"@cosyte/hl7\";\n * console.log(parseDtm(\"1970\").precision); // \"year\"\n * console.log(parseDtm(\"198807050000\").precision); // \"minute\"\n * ```\n */\nexport type DtmPrecision = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\" | \"fraction\";\n\n/**\n * Parsed HL7 v2 TS/DTM value: the raw string plus its structural parts, with\n * the stated **precision** and **timezone fidelity** preserved. This is the\n * shape of the `TS` composite (`field.asTs()`) and every helper datetime.\n *\n * The parts are only populated when `valid` is `true`. `month`/`day`/… are\n * **spec-native** (`month` is 1–12, NOT the JS `Date` 0–11). `offsetMinutes`\n * is present iff `hasTimezone` is `true` and is signed minutes east of UTC\n * (`+0500` → `300`, `-0430` → `-270`). A missing offset is **flagged**\n * (`hasTimezone: false`), never resolved to UTC: the consumer decides how to\n * localize with {@link dtmToDate}.\n *\n * @example\n * ```ts\n * import type { DtmParts } from \"@cosyte/hl7\";\n * const dob: DtmParts = {\n * raw: \"19880705\", valid: true, precision: \"day\",\n * year: 1988, month: 7, day: 5, hasTimezone: false,\n * };\n * ```\n */\nexport interface DtmParts {\n /** The original HL7 string, exactly as it appeared (already unescaped). */\n readonly raw: string;\n /**\n * `true` when `raw` is a well-formed, in-range HL7 DTM (or a matched\n * fallback format). `false` for empty, malformed, or calendar-out-of-range\n * input: in which case only `raw` and `hasTimezone: false` are meaningful.\n */\n readonly valid: boolean;\n /** Stated precision; absent when `valid` is `false`. */\n readonly precision?: DtmPrecision;\n /** Four-digit year. */\n readonly year?: number;\n /** Month, 1–12 (spec-native, NOT JS 0–11). */\n readonly month?: number;\n /** Day of month, 1–31. */\n readonly day?: number;\n /** Hour, 0–23. */\n readonly hour?: number;\n /** Minute, 0–59. */\n readonly minute?: number;\n /** Second, 0–59. */\n readonly second?: number;\n /**\n * Fractional-second digits exactly as populated (no leading dot), e.g.\n * `\"5\"` (0.5 s), `\"0500\"` (0.05 s). Preserved verbatim: never rounded.\n */\n readonly fractionalSeconds?: string;\n /** `true` iff an explicit `+/-ZZZZ` offset was present. */\n readonly hasTimezone: boolean;\n /** Signed minutes east of UTC; present iff `hasTimezone` is `true`. */\n readonly offsetMinutes?: number;\n /**\n * The fallback format that matched (`parseDtmCascade` only), e.g.\n * `\"MM/DD/YYYY\"` or `\"ISO-8601\"`. Absent for a strict HL7 DTM parse.\n */\n readonly matchedFormat?: string;\n}\n\n/**\n * Ordered list of built-in timestamp formats {@link parseDtmCascade} falls\n * back to when neither the strict HL7 DTM match nor any user-supplied format\n * succeeds. ISO-8601 is tried first (most constrained); `MM/DD/YYYY HH:mm:ss`\n * last (it overlaps the date-only form).\n *\n * @example\n * ```ts\n * import { BUILTIN_DATE_FALLBACKS } from \"@cosyte/hl7\";\n * console.log(BUILTIN_DATE_FALLBACKS);\n * // [\"ISO-8601\", \"YYYY-MM-DD\", \"MM/DD/YYYY\", \"MM/DD/YYYY HH:mm:ss\"]\n * ```\n */\nexport const BUILTIN_DATE_FALLBACKS: readonly string[] = [\n \"ISO-8601\",\n \"YYYY-MM-DD\",\n \"MM/DD/YYYY\",\n \"MM/DD/YYYY HH:mm:ss\",\n] as const;\n\n/**\n * Every date-format token the library's format-string matcher and\n * `defineProfile()` D-08 validator recognize. Re-exported so profile authors\n * can introspect the valid token set. `SSSS` (fractional seconds) is\n * recognised by the D-08 validator only.\n *\n * @example\n * ```ts\n * import { SUPPORTED_DATE_TOKENS } from \"@cosyte/hl7\";\n * console.log(SUPPORTED_DATE_TOKENS);\n * // [\"YYYY\", \"MM\", \"DD\", \"HH\", \"mm\", \"ss\", \"SSSS\"]\n * ```\n */\nexport const SUPPORTED_DATE_TOKENS: readonly string[] = [\n \"YYYY\",\n \"MM\",\n \"DD\",\n \"HH\",\n \"mm\",\n \"ss\",\n \"SSSS\",\n] as const;\n\n/**\n * The empty / unparseable result: `valid: false`, no parts, no timezone.\n * Frozen and shared to avoid per-call allocation on the common miss path.\n *\n * @internal\n */\nconst INVALID_PARTS_BASE = { valid: false as const, hasTimezone: false as const };\n\n/**\n * The frozen invalid/unparseable result for a raw string: `valid: false`, no\n * parts, no timezone. Frozen so every public `DtmParts` is immutable uniformly\n * (matching the composite path and `batch.ts`).\n *\n * @internal\n */\nfunction invalidDtm(raw: string): DtmParts {\n return Object.freeze({ raw, ...INVALID_PARTS_BASE });\n}\n\n/**\n * HL7 v2 DTM shape: `YYYY[MM[DD[HH[MM[SS[.SSSS]]]]]]` with an optional trailing\n * `+/-ZZZZ` offset. No separators between digit groups.\n *\n * @internal\n */\nconst DTM_PATTERN =\n /^(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(?:\\.(\\d{1,4}))?(?:([+-])(\\d{2})(\\d{2}))?$/u;\n\n/**\n * Parse an HL7 v2 TS/DTM string into typed {@link DtmParts}, **preserving the\n * stated precision and timezone fidelity**. Never zero-fills a truncation,\n * never coerces to a `Date`, and never assumes UTC for a missing offset.\n *\n * Returns `{ raw, valid: false, hasTimezone: false }` (no parts) for empty,\n * malformed, or calendar-out-of-range input: never throws. A fractional\n * component is only accepted at full second precision.\n *\n * @example\n * ```ts\n * import { parseDtm } from \"@cosyte/hl7\";\n *\n * parseDtm(\"1970\");\n * // { raw: \"1970\", valid: true, precision: \"year\", year: 1970, hasTimezone: false }\n *\n * parseDtm(\"20250102153045.5-0500\");\n * // precision \"fraction\", fractionalSeconds \"5\", hasTimezone true, offsetMinutes -300\n *\n * parseDtm(\"not-a-date\");\n * // { raw: \"not-a-date\", valid: false, hasTimezone: false }\n * ```\n */\nexport function parseDtm(raw: string): DtmParts {\n if (raw === \"\") return invalidDtm(raw);\n\n const match = DTM_PATTERN.exec(raw);\n if (match === null) return invalidDtm(raw);\n\n const [, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr, fracStr, sign, offHh, offMm] =\n match;\n if (yearStr === undefined) return invalidDtm(raw);\n\n // A fractional component is only meaningful at full second precision.\n if (fracStr !== undefined && secondStr === undefined) return invalidDtm(raw);\n\n const year = parseInt(yearStr, 10);\n const month = monthStr !== undefined ? parseInt(monthStr, 10) : undefined;\n const day = dayStr !== undefined ? parseInt(dayStr, 10) : undefined;\n const hour = hourStr !== undefined ? parseInt(hourStr, 10) : undefined;\n const minute = minuteStr !== undefined ? parseInt(minuteStr, 10) : undefined;\n const second = secondStr !== undefined ? parseInt(secondStr, 10) : undefined;\n\n // Calendar-range validation: out-of-range is invalid, never a wrong guess.\n if (\n (month !== undefined && (month < 1 || month > 12)) ||\n (day !== undefined && (day < 1 || day > 31)) ||\n (hour !== undefined && hour > 23) ||\n (minute !== undefined && minute > 59) ||\n (second !== undefined && second > 59)\n ) {\n return invalidDtm(raw);\n }\n\n let hasTimezone = false;\n let offsetMinutes: number | undefined;\n if (sign !== undefined && offHh !== undefined && offMm !== undefined) {\n const offHours = parseInt(offHh, 10);\n const offMins = parseInt(offMm, 10);\n // Offsets range roughly ±14:00; accept up to ±24:00, reject nonsense minutes.\n if (offHours > 24 || offMins > 59) return invalidDtm(raw);\n hasTimezone = true;\n offsetMinutes = (sign === \"-\" ? -1 : 1) * (offHours * 60 + offMins);\n }\n\n const precision: DtmPrecision =\n fracStr !== undefined\n ? \"fraction\"\n : second !== undefined\n ? \"second\"\n : minute !== undefined\n ? \"minute\"\n : hour !== undefined\n ? \"hour\"\n : day !== undefined\n ? \"day\"\n : month !== undefined\n ? \"month\"\n : \"year\";\n\n return Object.freeze({\n raw,\n valid: true,\n precision,\n year,\n ...(month !== undefined ? { month } : {}),\n ...(day !== undefined ? { day } : {}),\n ...(hour !== undefined ? { hour } : {}),\n ...(minute !== undefined ? { minute } : {}),\n ...(second !== undefined ? { second } : {}),\n ...(fracStr !== undefined ? { fractionalSeconds: fracStr } : {}),\n hasTimezone,\n ...(offsetMinutes !== undefined ? { offsetMinutes } : {}),\n });\n}\n\n/**\n * Reconstruct the HL7 DTM string from {@link DtmParts}. The inverse of\n * {@link parseDtm} for a strict HL7 parse: `formatDtm(parseDtm(s)) === s` for\n * any well-formed `s`, including the byte-preserving `-0000` (which HL7, unlike\n * RFC 3339, treats as UTC but whose sign we retain for exact round-trip).\n * Returns the raw string unchanged when `parts.valid` is `false`.\n *\n * Emits exactly the populated precision, no zero-fill, so a year-only value\n * re-serializes to four characters, never `YYYY0101`.\n *\n * @example\n * ```ts\n * import { parseDtm, formatDtm } from \"@cosyte/hl7\";\n * formatDtm(parseDtm(\"198807050000\")); // \"198807050000\"\n * formatDtm(parseDtm(\"1970\")); // \"1970\"\n * ```\n */\nexport function formatDtm(parts: DtmParts): string {\n if (!parts.valid || parts.year === undefined) return parts.raw;\n\n const pad = (n: number, width: number): string => n.toString().padStart(width, \"0\");\n let out = pad(parts.year, 4);\n if (parts.month !== undefined) out += pad(parts.month, 2);\n if (parts.day !== undefined) out += pad(parts.day, 2);\n if (parts.hour !== undefined) out += pad(parts.hour, 2);\n if (parts.minute !== undefined) out += pad(parts.minute, 2);\n if (parts.second !== undefined) out += pad(parts.second, 2);\n if (parts.fractionalSeconds !== undefined) out += `.${parts.fractionalSeconds}`;\n if (parts.hasTimezone && parts.offsetMinutes !== undefined) {\n const total = parts.offsetMinutes;\n // `Object.is(total, -0)` catches a `-0000` offset (parsed as -0) so it\n // re-serializes byte-exact as `-0000`, not `+0000`.\n const sign = total < 0 || Object.is(total, -0) ? \"-\" : \"+\";\n const abs = Math.abs(total);\n out += `${sign}${pad(Math.floor(abs / 60), 2)}${pad(abs % 60, 2)}`;\n }\n return out;\n}\n\n/**\n * Options controlling how {@link dtmToDate} resolves a missing timezone.\n *\n * @example\n * ```ts\n * import { parseDtm, dtmToDate } from \"@cosyte/hl7\";\n * // Treat an offset-less value as UTC (an explicit caller choice):\n * dtmToDate(parseDtm(\"20250102\"), { assumeOffsetMinutes: 0 });\n * // ...or as US Eastern standard time (UTC-05:00):\n * dtmToDate(parseDtm(\"20250102\"), { assumeOffsetMinutes: -300 });\n * ```\n */\nexport interface DtmToDateOptions {\n /**\n * Offset (signed minutes east of UTC) to assume when the value carries **no**\n * timezone. Without it, an offset-less value resolves to `undefined`,\n * {@link dtmToDate} never guesses a zone. Ignored when the value already has\n * an offset. Pass `0` to explicitly treat a naive value as UTC.\n */\n readonly assumeOffsetMinutes?: number;\n}\n\n/**\n * Materialize an absolute-instant JS `Date` from {@link DtmParts}: **only on\n * explicit caller request**. Truncated fields fill to their lowest legal value\n * (month → January, day → 1, time → 0) *for instant construction only*; the\n * value's stated `precision` still tells the truth.\n *\n * Timezone resolution is honest:\n * - has an offset → the exact instant, using that offset;\n * - no offset + `assumeOffsetMinutes` supplied → that offset is applied;\n * - no offset + nothing supplied → `undefined` (never a silent UTC guess).\n *\n * Returns `undefined` for an invalid value or an unresolvable zone; never\n * throws.\n *\n * @example\n * ```ts\n * import { parseDtm, dtmToDate } from \"@cosyte/hl7\";\n *\n * dtmToDate(parseDtm(\"20250102153045-0500\"))?.toISOString();\n * // \"2025-01-02T20:30:45.000Z\": exact, offset-derived\n *\n * dtmToDate(parseDtm(\"20250102\")); // undefined: refuses to guess the zone\n * dtmToDate(parseDtm(\"20250102\"), { assumeOffsetMinutes: 0 })?.toISOString();\n * // \"2025-01-02T00:00:00.000Z\": caller explicitly assumed UTC\n * ```\n */\nexport function dtmToDate(parts: DtmParts, options: DtmToDateOptions = {}): Date | undefined {\n if (!parts.valid || parts.year === undefined) return undefined;\n\n const offset = parts.hasTimezone ? parts.offsetMinutes : options.assumeOffsetMinutes;\n if (offset === undefined) return undefined;\n\n let ms = 0;\n if (parts.fractionalSeconds !== undefined) {\n ms = parseInt((parts.fractionalSeconds + \"000\").slice(0, 3), 10);\n }\n\n // Build via setUTCFullYear so a 1–99 AD year is NOT remapped to 1900–1999 by\n // `Date.UTC`'s legacy two-digit-year behavior (ECMA-262): a spec-valid\n // 4-digit DTM year like `0050` must stay year 50.\n const utc = new Date(0);\n utc.setUTCFullYear(parts.year, (parts.month ?? 1) - 1, parts.day ?? 1);\n utc.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, ms);\n // The value is expressed in `offset`; shift to UTC by subtracting it.\n const candidate = new Date(utc.getTime() - offset * 60_000);\n return isNaN(candidate.getTime()) ? undefined : candidate;\n}\n\n/**\n * Options passed to {@link parseDtmCascade}. `emit` and `position` are needed\n * only when the caller wants `TIMESTAMP_FALLBACK_FORMAT` warnings to surface.\n *\n * @internal\n */\nexport interface ParseDtmCascadeOptions {\n readonly userFormats?: readonly string[];\n readonly emit?: (warning: Hl7ParseWarning) => void;\n readonly position?: Hl7Position;\n}\n\n/**\n * Lenient datetime parse for non-composite callers (e.g. `msg.meta.timestamp`):\n *\n * 1. Strict HL7 DTM via {@link parseDtm}: no warning (spec-preferred).\n * 2. User-supplied formats, in order: first match wins, emits\n * `TIMESTAMP_FALLBACK_FORMAT`.\n * 3. Built-in {@link BUILTIN_DATE_FALLBACKS}, in order: emits on match.\n *\n * Always returns {@link DtmParts}; a fallback match sets `matchedFormat` and\n * `valid: true` with the parts it could recover. A total miss returns an\n * invalid result (no throw, no warning: nothing fell back to).\n *\n * @internal\n */\nexport function parseDtmCascade(raw: string, opts: ParseDtmCascadeOptions): DtmParts {\n if (raw === \"\") return invalidDtm(raw);\n\n const strict = parseDtm(raw);\n if (strict.valid) return strict;\n\n for (const format of opts.userFormats ?? []) {\n const matched = matchTokenParts(raw, format);\n if (matched !== undefined) {\n emitFallback(opts, format);\n return Object.freeze({ ...matched, raw, matchedFormat: format });\n }\n }\n\n for (const builtin of BUILTIN_DATE_FALLBACKS) {\n const matched = builtin === \"ISO-8601\" ? parseIsoParts(raw) : matchTokenParts(raw, builtin);\n if (matched !== undefined) {\n emitFallback(opts, builtin);\n return Object.freeze({ ...matched, raw, matchedFormat: builtin });\n }\n }\n\n return invalidDtm(raw);\n}\n\n/**\n * Emit a `TIMESTAMP_FALLBACK_FORMAT` warning when both an `emit` callback and a\n * `position` are supplied.\n *\n * @internal\n */\nfunction emitFallback(opts: ParseDtmCascadeOptions, matchedFormat: string): void {\n if (opts.emit !== undefined && opts.position !== undefined) {\n opts.emit(timestampFallbackFormat(opts.position, matchedFormat));\n }\n}\n\n/**\n * Token set recognised by the minimal format-string matcher. `MM` is month and\n * `mm` is minute (case-sensitive, moment.js-style).\n *\n * @internal\n */\nconst TOKENS = [\"YYYY\", \"MM\", \"DD\", \"HH\", \"mm\", \"ss\"] as const;\n\n/** @internal Digit-width of each token. */\nconst TOKEN_LENGTHS: Readonly<Record<(typeof TOKENS)[number], number>> = {\n YYYY: 4,\n MM: 2,\n DD: 2,\n HH: 2,\n mm: 2,\n ss: 2,\n};\n\n/**\n * Minimal format-string matcher over the tokens `YYYY MM DD HH mm ss`. Anything\n * else in `format` is a literal. Returns fidelity {@link DtmParts} (no offset,\n * these formats carry none) or `undefined` on mismatch. Parsing is strictly\n * linear so untrusted format strings cannot cause exponential backtracking.\n *\n * @internal\n */\nfunction matchTokenParts(input: string, format: string): DtmParts | undefined {\n type Token = (typeof TOKENS)[number];\n type Part =\n | { readonly kind: \"token\"; readonly token: Token }\n | { readonly kind: \"lit\"; readonly value: string };\n\n const parts: Part[] = [];\n let i = 0;\n while (i < format.length) {\n let matched: Token | undefined;\n for (const t of TOKENS) {\n if (format.slice(i, i + t.length) === t) {\n matched = t;\n break;\n }\n }\n if (matched !== undefined) {\n parts.push({ kind: \"token\", token: matched });\n i += matched.length;\n } else {\n parts.push({ kind: \"lit\", value: format.charAt(i) });\n i += 1;\n }\n }\n\n const got: Partial<Record<Token, number>> = {};\n let j = 0;\n for (const p of parts) {\n if (p.kind === \"lit\") {\n if (input.charAt(j) !== p.value) return undefined;\n j += 1;\n } else {\n const len = TOKEN_LENGTHS[p.token];\n const chunk = input.slice(j, j + len);\n if (chunk.length !== len || !/^\\d+$/u.test(chunk)) return undefined;\n got[p.token] = parseInt(chunk, 10);\n j += len;\n }\n }\n if (j !== input.length) return undefined; // trailing chars = mismatch\n\n return buildFallbackParts({\n year: got.YYYY,\n month: got.MM,\n day: got.DD,\n hour: got.HH,\n minute: got.mm,\n second: got.ss,\n });\n}\n\n/**\n * Parse an ISO-8601 string into fidelity {@link DtmParts} behind a strict shape\n * guard (requires at least `YYYY-MM-DD` so raw HL7 digit strings never match\n * here). Preserves an explicit `Z`/`+HH:MM` offset as timezone fidelity.\n *\n * @internal\n */\nfunction parseIsoParts(raw: string): DtmParts | undefined {\n const iso =\n /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?(Z|[+-]\\d{2}:?\\d{2})?)?$/u.exec(\n raw,\n );\n if (iso === null) return undefined;\n const [, y, mo, d, h, mi, s, frac, tz] = iso;\n\n let hasTimezone = false;\n let offsetMinutes: number | undefined;\n if (tz !== undefined) {\n hasTimezone = true;\n if (tz === \"Z\") {\n offsetMinutes = 0;\n } else {\n const sign = tz.startsWith(\"-\") ? -1 : 1;\n const digits = tz.slice(1).replace(\":\", \"\");\n offsetMinutes =\n sign * (parseInt(digits.slice(0, 2), 10) * 60 + parseInt(digits.slice(2), 10));\n }\n }\n\n return buildFallbackParts({\n year: y !== undefined ? parseInt(y, 10) : undefined,\n month: mo !== undefined ? parseInt(mo, 10) : undefined,\n day: d !== undefined ? parseInt(d, 10) : undefined,\n hour: h !== undefined ? parseInt(h, 10) : undefined,\n minute: mi !== undefined ? parseInt(mi, 10) : undefined,\n second: s !== undefined ? parseInt(s, 10) : undefined,\n fractionalSeconds: frac,\n hasTimezone,\n offsetMinutes,\n });\n}\n\n/**\n * Assemble validated {@link DtmParts} from a fallback match, computing the\n * precision from which fields are present and range-checking each. Returns\n * `undefined` when any field is out of range.\n *\n * @internal\n */\nfunction buildFallbackParts(f: {\n year: number | undefined;\n month?: number | undefined;\n day?: number | undefined;\n hour?: number | undefined;\n minute?: number | undefined;\n second?: number | undefined;\n fractionalSeconds?: string | undefined;\n hasTimezone?: boolean | undefined;\n offsetMinutes?: number | undefined;\n}): DtmParts | undefined {\n if (f.year === undefined) return undefined;\n if (\n (f.month !== undefined && (f.month < 1 || f.month > 12)) ||\n (f.day !== undefined && (f.day < 1 || f.day > 31)) ||\n (f.hour !== undefined && f.hour > 23) ||\n (f.minute !== undefined && f.minute > 59) ||\n (f.second !== undefined && f.second > 59)\n ) {\n return undefined;\n }\n\n const precision: DtmPrecision =\n f.fractionalSeconds !== undefined\n ? \"fraction\"\n : f.second !== undefined\n ? \"second\"\n : f.minute !== undefined\n ? \"minute\"\n : f.hour !== undefined\n ? \"hour\"\n : f.day !== undefined\n ? \"day\"\n : f.month !== undefined\n ? \"month\"\n : \"year\";\n\n return {\n raw: \"\", // caller overwrites with the real raw string\n valid: true,\n precision,\n year: f.year,\n ...(f.month !== undefined ? { month: f.month } : {}),\n ...(f.day !== undefined ? { day: f.day } : {}),\n ...(f.hour !== undefined ? { hour: f.hour } : {}),\n ...(f.minute !== undefined ? { minute: f.minute } : {}),\n ...(f.second !== undefined ? { second: f.second } : {}),\n ...(f.fractionalSeconds !== undefined ? { fractionalSeconds: f.fractionalSeconds } : {}),\n hasTimezone: f.hasTimezone ?? false,\n ...(f.offsetMinutes !== undefined ? { offsetMinutes: f.offsetMinutes } : {}),\n };\n}\n","/**\n * TS/DTM: HL7 v2 Time Stamp composite. Delegates parsing to the Phase 2\n * helper `src/parser/dates.ts::parseDtm` (D-10 \"zero duplicate date logic\").\n *\n * Phase N (datetime precision + timezone fidelity) reshaped this composite from\n * the old `{ raw, date }` (which zero-filled truncations and assumed UTC for a\n * missing offset: an architectural defect) to the fidelity-preserving\n * {@link DtmParts}: raw string + typed parts + stated precision + timezone\n * presence, with **no eager `Date`**. Callers that need an absolute instant\n * opt in explicitly via `dtmToDate(ts, opts)`: which refuses to guess a zone\n * for an offset-less value rather than silently defaulting to UTC.\n *\n * Zero runtime deps: delegates to `parseDtm` + `unescape`.\n */\n\nimport { parseDtm } from \"../../parser/dates.js\";\nimport type { DtmParts } from \"../../parser/dates.js\";\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\n/**\n * HL7 v2 Time Stamp (TS) / Date Time (DTM) composite: the raw HL7 string plus\n * its parsed parts, preserving the **stated precision** and **timezone\n * fidelity**. This is a {@link DtmParts}: `valid` is `false` (with no parts)\n * for unparseable input: NEVER throws (TYPES-04 no-throw guarantee).\n *\n * There is deliberately **no `date` field**: a day-only value coerced to a JS\n * `Date` at UTC midnight silently shifts the calendar day in negative-offset\n * zones. To obtain an absolute instant, call `dtmToDate(ts)` explicitly (and\n * supply `assumeOffsetMinutes` for an offset-less value).\n *\n * @example\n * ```ts\n * import type { TS } from \"@cosyte/hl7\";\n * import { dtmToDate } from \"@cosyte/hl7\";\n * const dob: TS = { raw: \"19880705\", valid: true, precision: \"day\",\n * year: 1988, month: 7, day: 5, hasTimezone: false };\n * console.log(dob.precision); // \"day\": not a full timestamp\n * console.log(dtmToDate(dob)); // undefined: refuses to guess the zone\n * ```\n */\nexport type TS = DtmParts;\n\n/**\n * Parse an HL7 v2 TS/DTM repetition into fidelity {@link TS} parts. Delegates\n * to `parseDtm`: the same structural parser that backs every timestamp in the\n * library. No user `dateFormats` at this layer; non-composite callers (e.g.\n * `msg.meta.timestamp`) that know `ParseOptions.dateFormats` use\n * `parseDtmCascade` directly.\n *\n * The result is frozen so the immutability guarantee holds for callers that\n * destructure or retain it.\n *\n * @example\n * ```ts\n * import { parseTs, DEFAULT_ENCODING_CHARACTERS, dtmToDate } from \"@cosyte/hl7\";\n * const rep = { components: [{ subcomponents: [\"20250102153045-0500\"] }] };\n * const ts = parseTs(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(ts.raw); // \"20250102153045-0500\"\n * console.log(ts.precision, ts.hasTimezone); // \"second\" true\n * console.log(dtmToDate(ts)?.toISOString()); // \"2025-01-02T20:30:45.000Z\"\n * ```\n */\nexport function parseTs(rep: RawRepetition, _enc: EncodingCharacters): TS {\n const comp = rep.components[0];\n // The tokenizer already unescaped every subcomponent on parse (parser-02), so\n // the stored value is decoded: use it directly, never a second unescape (that\n // would double-decode a value whose bytes look like an escape). `_enc` is kept\n // for composite-parser signature uniformity.\n const raw = comp?.subcomponents[0] ?? \"\";\n // `parseDtm` already returns a frozen `DtmParts`.\n return parseDtm(raw);\n}\n","/**\n * XAD: HL7 v2 Extended Address composite. 12-component structured address\n * shape parsed from a `RawRepetition` on demand by `Field.asXad()` (wired in\n * Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes),\n * NEVER set to `undefined`.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Extended Address (XAD): structured postal address per HL7 Chapter\n * 2. All 12 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. street: street address (house number + street name).\n * 2. otherDesignation: apartment number, suite, floor, etc.\n * 3. city\n * 4. stateOrProvince\n * 5. zipOrPostalCode\n * 6. country (ISO-3166 3-letter, e.g. \"USA\", \"CAN\")\n * 7. addressType (H=Home, B=Business, M=Mailing, O=Office, P=Permanent, ...)\n * 8. otherGeographicDesignation\n * 9. countyParishCode\n * 10. censusTract\n * 11. addressRepresentationCode\n * 12. addressValidityRange\n *\n * @example\n * ```ts\n * import type { XAD } from \"@cosyte/hl7\";\n * const addr: XAD = { street: \"123 Main St\", city: \"Boston\", stateOrProvince: \"MA\" };\n * ```\n */\nexport interface XAD {\n readonly street?: string;\n readonly otherDesignation?: string;\n readonly city?: string;\n readonly stateOrProvince?: string;\n readonly zipOrPostalCode?: string;\n readonly country?: string;\n readonly addressType?: string;\n readonly otherGeographicDesignation?: string;\n readonly countyParishCode?: string;\n readonly censusTract?: string;\n readonly addressRepresentationCode?: string;\n readonly addressValidityRange?: string;\n}\n\n/**\n * Parse an HL7 v2 XAD repetition into a structured `XAD` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseXad, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"123 Main St\"] },\n * { subcomponents: [\"Apt 4\"] },\n * { subcomponents: [\"Boston\"] },\n * { subcomponents: [\"MA\"] },\n * { subcomponents: [\"02101\"] },\n * ] };\n * const addr = parseXad(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(addr.city); // \"Boston\"\n * ```\n */\nexport function parseXad(rep: RawRepetition, enc: EncodingCharacters): XAD {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XAD> = {};\n\n const street = readComponent(rep, 0, enc);\n if (street !== undefined) out.street = street;\n\n const otherDesignation = readComponent(rep, 1, enc);\n if (otherDesignation !== undefined) out.otherDesignation = otherDesignation;\n\n const city = readComponent(rep, 2, enc);\n if (city !== undefined) out.city = city;\n\n const stateOrProvince = readComponent(rep, 3, enc);\n if (stateOrProvince !== undefined) out.stateOrProvince = stateOrProvince;\n\n const zipOrPostalCode = readComponent(rep, 4, enc);\n if (zipOrPostalCode !== undefined) out.zipOrPostalCode = zipOrPostalCode;\n\n const country = readComponent(rep, 5, enc);\n if (country !== undefined) out.country = country;\n\n const addressType = readComponent(rep, 6, enc);\n if (addressType !== undefined) out.addressType = addressType;\n\n const otherGeographicDesignation = readComponent(rep, 7, enc);\n if (otherGeographicDesignation !== undefined) {\n out.otherGeographicDesignation = otherGeographicDesignation;\n }\n\n const countyParishCode = readComponent(rep, 8, enc);\n if (countyParishCode !== undefined) out.countyParishCode = countyParishCode;\n\n const censusTract = readComponent(rep, 9, enc);\n if (censusTract !== undefined) out.censusTract = censusTract;\n\n const addressRepresentationCode = readComponent(rep, 10, enc);\n if (addressRepresentationCode !== undefined) {\n out.addressRepresentationCode = addressRepresentationCode;\n }\n\n const addressValidityRange = readComponent(rep, 11, enc);\n if (addressValidityRange !== undefined) out.addressValidityRange = addressValidityRange;\n\n return out;\n}\n","/**\n * XCN: HL7 v2 Extended Composite ID Number and Name for Persons. Common in\n * OBR-16 (ordering provider), PV1-7 (attending doctor), PV1-8 (referring\n * doctor), and other fields that identify a human clinician.\n *\n * Structurally XCN is XPN (person-name) components with an `idNumber` prefix\n * and an `assigningAuthority` nested-HD at component 9. v1 ships the 13\n * most-used components (HL7 v2.5 defines 23); additional components may be\n * restored in v2 if vendor-quirk fixtures require them.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n * Parser is silent (D-09 composite-parser silence).\n */\n\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\nimport { parseHd, type HD } from \"./hd.js\";\n\n/**\n * HL7 v2 Extended Composite ID Number and Name for Persons (XCN): per HL7\n * Chapter 2.A.88. All 13 v1 components are optional. Fields are OMITTED when\n * the underlying component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. idNumber: e.g. employee ID, NPI digits, DEA number (CX-1 analogue)\n * 2. familyName (XPN-1)\n * 3. givenName (XPN-2)\n * 4. secondName: second and further given names (XPN-3)\n * 5. suffix: Jr., III, etc. (XPN-4)\n * 6. prefix: Dr., Mrs., etc. (XPN-5)\n * 7. degree: MD, PhD, etc. (XPN-6)\n * 8. sourceTable\n * 9. assigningAuthority: nested HD (CX-4 analogue)\n * 10. nameTypeCode: L=Legal, M=Maiden, N=Nickname, ... (XPN-7)\n * 11. identifierCheckDigit\n * 12. checkDigitScheme: ISO 7064, M10, M11, NPI\n * 13. identifierTypeCode: \"NPI\", \"DN\" (DEA number), ... (CX-5 analogue)\n *\n * @example\n * ```ts\n * import type { XCN } from \"@cosyte/hl7\";\n * const orderingProvider: XCN = {\n * idNumber: \"1234567890\",\n * familyName: \"Smith\",\n * givenName: \"Jane\",\n * identifierTypeCode: \"NPI\",\n * };\n * ```\n */\nexport interface XCN {\n readonly idNumber?: string;\n readonly familyName?: string;\n readonly givenName?: string;\n readonly secondName?: string;\n readonly suffix?: string;\n readonly prefix?: string;\n readonly degree?: string;\n readonly sourceTable?: string;\n readonly assigningAuthority?: HD;\n readonly nameTypeCode?: string;\n readonly identifierCheckDigit?: string;\n readonly checkDigitScheme?: string;\n readonly identifierTypeCode?: string;\n}\n\n/**\n * Parse XCN component 9 (assigningAuthority) from its subcomponents into an\n * `HD`. The 3 HD subfields live as subcomponents of the XCN component; we\n * build a synthetic `RawRepetition` where each synthetic component wraps one\n * subcomponent of the XCN component as its own single subcomponent. This\n * lets `parseHd` consume the value via its existing `(rep, enc)` signature\n * without reimplementing the read.\n *\n * Returns `undefined` when the source component is missing or every\n * subcomponent is the empty string: prevents stub empty HD objects from\n * leaking into XCN output (mirrors the CX/PL convention).\n *\n * @internal\n */\nfunction parseAssigningAuthority(\n comp: RawComponent | undefined,\n enc: EncodingCharacters,\n): HD | undefined {\n if (comp === undefined) return undefined;\n if (comp.subcomponents.every((s) => s === \"\")) return undefined;\n const synthetic: RawRepetition = {\n components: comp.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const hd = parseHd(synthetic, enc);\n return Object.keys(hd).length === 0 ? undefined : hd;\n}\n\n/**\n * Parse an HL7 v2 XCN repetition into a structured `XCN` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Component 9\n * (`assigningAuthority`) is parsed as a nested `HD`; see component table in\n * the `XCN` interface JSDoc for the v1 trimming.\n *\n * @example\n * ```ts\n * import { parseXcn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"1234567890\"] },\n * { subcomponents: [\"Smith\"] },\n * { subcomponents: [\"Jane\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"HOSP\", \"1.2.3\", \"ISO\"] },\n * { subcomponents: [\"L\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"\"] },\n * { subcomponents: [\"NPI\"] },\n * ] };\n * const xcn = parseXcn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(xcn.idNumber); // \"1234567890\"\n * console.log(xcn.familyName); // \"Smith\"\n * console.log(xcn.assigningAuthority?.namespaceId); // \"HOSP\"\n * console.log(xcn.identifierTypeCode); // \"NPI\"\n * ```\n */\nexport function parseXcn(rep: RawRepetition, enc: EncodingCharacters): XCN {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XCN> = {};\n\n const idNumber = readComponent(rep, 0, enc);\n if (idNumber !== undefined) out.idNumber = idNumber;\n\n const familyName = readComponent(rep, 1, enc);\n if (familyName !== undefined) out.familyName = familyName;\n\n const givenName = readComponent(rep, 2, enc);\n if (givenName !== undefined) out.givenName = givenName;\n\n const secondName = readComponent(rep, 3, enc);\n if (secondName !== undefined) out.secondName = secondName;\n\n const suffix = readComponent(rep, 4, enc);\n if (suffix !== undefined) out.suffix = suffix;\n\n const prefix = readComponent(rep, 5, enc);\n if (prefix !== undefined) out.prefix = prefix;\n\n const degree = readComponent(rep, 6, enc);\n if (degree !== undefined) out.degree = degree;\n\n const sourceTable = readComponent(rep, 7, enc);\n if (sourceTable !== undefined) out.sourceTable = sourceTable;\n\n const assigningAuthority = parseAssigningAuthority(rep.components[8], enc);\n if (assigningAuthority !== undefined) out.assigningAuthority = assigningAuthority;\n\n const nameTypeCode = readComponent(rep, 9, enc);\n if (nameTypeCode !== undefined) out.nameTypeCode = nameTypeCode;\n\n const identifierCheckDigit = readComponent(rep, 10, enc);\n if (identifierCheckDigit !== undefined) out.identifierCheckDigit = identifierCheckDigit;\n\n const checkDigitScheme = readComponent(rep, 11, enc);\n if (checkDigitScheme !== undefined) out.checkDigitScheme = checkDigitScheme;\n\n const identifierTypeCode = readComponent(rep, 12, enc);\n if (identifierTypeCode !== undefined) out.identifierTypeCode = identifierTypeCode;\n\n return out;\n}\n","/**\n * XPN: HL7 v2 Extended Person Name composite. 14-component structured-name\n * shape parsed from a `RawRepetition` on demand by `Field.asXpn()` (wired in\n * Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes),\n * NEVER set to `undefined`.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Extended Person Name (XPN): structured name per HL7 Chapter 2. All\n * 14 components are optional. Fields are OMITTED when the underlying\n * component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. familyName\n * 2. givenName\n * 3. secondName (or \"second and further given names\")\n * 4. suffix (e.g. Jr., III)\n * 5. prefix (e.g. Dr., Mrs.)\n * 6. degree (e.g. MD, PhD)\n * 7. nameTypeCode (L=Legal, M=Maiden, N=Nickname, S=Coded Pseudo-Name, ...)\n * 8. nameRepresentationCode\n * 9. nameContext (flattened to string in v1: CWE nesting is out of scope)\n * 10. nameValidityRange\n * 11. nameAssemblyOrder (F=family first, G=given first)\n * 12. effectiveDate (raw HL7 TS string: caller may parse via parseDtm)\n * 13. expirationDate\n * 14. professionalSuffix\n *\n * @example\n * ```ts\n * import type { XPN } from \"@cosyte/hl7\";\n * const name: XPN = { familyName: \"Smith\", givenName: \"Jane\", prefix: \"Mrs.\" };\n * ```\n */\nexport interface XPN {\n readonly familyName?: string;\n readonly givenName?: string;\n readonly secondName?: string;\n readonly suffix?: string;\n readonly prefix?: string;\n readonly degree?: string;\n readonly nameTypeCode?: string;\n readonly nameRepresentationCode?: string;\n readonly nameContext?: string;\n readonly nameValidityRange?: string;\n readonly nameAssemblyOrder?: string;\n readonly effectiveDate?: string;\n readonly expirationDate?: string;\n readonly professionalSuffix?: string;\n}\n\n/**\n * Parse an HL7 v2 XPN repetition into a structured `XPN` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics).\n *\n * @example\n * ```ts\n * import { parseXpn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"Smith\"] },\n * { subcomponents: [\"Jane\"] },\n * ] };\n * const xpn = parseXpn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(xpn.familyName); // \"Smith\"\n * console.log(xpn.givenName); // \"Jane\"\n * ```\n */\nexport function parseXpn(rep: RawRepetition, enc: EncodingCharacters): XPN {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XPN> = {};\n\n const familyName = readComponent(rep, 0, enc);\n if (familyName !== undefined) out.familyName = familyName;\n\n const givenName = readComponent(rep, 1, enc);\n if (givenName !== undefined) out.givenName = givenName;\n\n const secondName = readComponent(rep, 2, enc);\n if (secondName !== undefined) out.secondName = secondName;\n\n const suffix = readComponent(rep, 3, enc);\n if (suffix !== undefined) out.suffix = suffix;\n\n const prefix = readComponent(rep, 4, enc);\n if (prefix !== undefined) out.prefix = prefix;\n\n const degree = readComponent(rep, 5, enc);\n if (degree !== undefined) out.degree = degree;\n\n const nameTypeCode = readComponent(rep, 6, enc);\n if (nameTypeCode !== undefined) out.nameTypeCode = nameTypeCode;\n\n const nameRepresentationCode = readComponent(rep, 7, enc);\n if (nameRepresentationCode !== undefined) out.nameRepresentationCode = nameRepresentationCode;\n\n const nameContext = readComponent(rep, 8, enc);\n if (nameContext !== undefined) out.nameContext = nameContext;\n\n const nameValidityRange = readComponent(rep, 9, enc);\n if (nameValidityRange !== undefined) out.nameValidityRange = nameValidityRange;\n\n const nameAssemblyOrder = readComponent(rep, 10, enc);\n if (nameAssemblyOrder !== undefined) out.nameAssemblyOrder = nameAssemblyOrder;\n\n const effectiveDate = readComponent(rep, 11, enc);\n if (effectiveDate !== undefined) out.effectiveDate = effectiveDate;\n\n const expirationDate = readComponent(rep, 12, enc);\n if (expirationDate !== undefined) out.expirationDate = expirationDate;\n\n const professionalSuffix = readComponent(rep, 13, enc);\n if (professionalSuffix !== undefined) out.professionalSuffix = professionalSuffix;\n\n return out;\n}\n","/**\n * XTN: HL7 v2 Extended Telecommunication Number composite. 12-component\n * structured telecom shape (v1 trimmed from the HL7 v2.5 full 14-component\n * XTN: slots 13/14 are rarely-used legacy fields; v2 may restore the full\n * shape) parsed from a `RawRepetition` on demand by `Field.asXtn()` (wired\n * in Plan 04). Fields are OMITTED when absent (exactOptionalPropertyTypes)\n *: NEVER set to `undefined`.\n *\n * Zero runtime deps: pure function over the raw positional tree + `unescape`.\n */\n\nimport type { EncodingCharacters, RawRepetition } from \"../../parser/types.js\";\n\nimport { readComponent } from \"./_shared.js\";\n\n/**\n * HL7 v2 Extended Telecommunication Number (XTN): structured telecom per\n * HL7 Chapter 2. All 12 v1 components are optional. Fields are OMITTED when\n * the underlying component is absent (exactOptionalPropertyTypes).\n *\n * Component positions (HL7 1-indexed; this interface is 0-indexed by key):\n * 1. telephoneNumber: formatted or unformatted phone number\n * 2. telecommunicationUseCode: PRN=Primary Residence, WPN=Work, NET=Internet,\n * ORN=Other Residence, BPN=Beeper, VHN=Vacation Home, ASN=Answering\n * Service, EMR=Emergency, ...\n * 3. telecommunicationEquipmentType: PH=Phone, FX=Fax, MD=Modem,\n * CP=Cellular Phone, BP=Beeper, Internet, X.400, TDD, TTY\n * 4. emailAddress\n * 5. countryCode (e.g. \"+1\")\n * 6. areaCityCode\n * 7. localNumber\n * 8. extension\n * 9. anyText: free-text note\n * 10. extensionPrefix (e.g. \"x\")\n * 11. speedDialCode\n * 12. unformattedTelephoneNumber\n *\n * @example\n * ```ts\n * import type { XTN } from \"@cosyte/hl7\";\n * const phone: XTN = {\n * telephoneNumber: \"(555) 555-1234\",\n * telecommunicationUseCode: \"WPN\",\n * telecommunicationEquipmentType: \"PH\",\n * };\n * ```\n */\nexport interface XTN {\n readonly telephoneNumber?: string;\n readonly telecommunicationUseCode?: string;\n readonly telecommunicationEquipmentType?: string;\n readonly emailAddress?: string;\n readonly countryCode?: string;\n readonly areaCityCode?: string;\n readonly localNumber?: string;\n readonly extension?: string;\n readonly anyText?: string;\n readonly extensionPrefix?: string;\n readonly speedDialCode?: string;\n readonly unformattedTelephoneNumber?: string;\n}\n\n/**\n * Parse an HL7 v2 XTN repetition into a structured `XTN` object. Components\n * are returned verbatim (already decoded once by the tokenizer: never re-unescaped,\n * HL7-VALUE-REDECODE). Absent / empty components are OMITTED\n * from the result (exactOptionalPropertyTypes semantics). Components past\n * position 12 are silently ignored in v1.\n *\n * @example\n * ```ts\n * import { parseXtn, DEFAULT_ENCODING_CHARACTERS } from \"@cosyte/hl7\";\n * const rep = { components: [\n * { subcomponents: [\"555-1234\"] },\n * { subcomponents: [\"PRN\"] },\n * { subcomponents: [\"PH\"] },\n * ] };\n * const xtn = parseXtn(rep, DEFAULT_ENCODING_CHARACTERS);\n * console.log(xtn.telephoneNumber); // \"555-1234\"\n * ```\n */\nexport function parseXtn(rep: RawRepetition, enc: EncodingCharacters): XTN {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<XTN> = {};\n\n const telephoneNumber = readComponent(rep, 0, enc);\n if (telephoneNumber !== undefined) out.telephoneNumber = telephoneNumber;\n\n const telecommunicationUseCode = readComponent(rep, 1, enc);\n if (telecommunicationUseCode !== undefined)\n out.telecommunicationUseCode = telecommunicationUseCode;\n\n const telecommunicationEquipmentType = readComponent(rep, 2, enc);\n if (telecommunicationEquipmentType !== undefined) {\n out.telecommunicationEquipmentType = telecommunicationEquipmentType;\n }\n\n const emailAddress = readComponent(rep, 3, enc);\n if (emailAddress !== undefined) out.emailAddress = emailAddress;\n\n const countryCode = readComponent(rep, 4, enc);\n if (countryCode !== undefined) out.countryCode = countryCode;\n\n const areaCityCode = readComponent(rep, 5, enc);\n if (areaCityCode !== undefined) out.areaCityCode = areaCityCode;\n\n const localNumber = readComponent(rep, 6, enc);\n if (localNumber !== undefined) out.localNumber = localNumber;\n\n const extension = readComponent(rep, 7, enc);\n if (extension !== undefined) out.extension = extension;\n\n const anyText = readComponent(rep, 8, enc);\n if (anyText !== undefined) out.anyText = anyText;\n\n const extensionPrefix = readComponent(rep, 9, enc);\n if (extensionPrefix !== undefined) out.extensionPrefix = extensionPrefix;\n\n const speedDialCode = readComponent(rep, 10, enc);\n if (speedDialCode !== undefined) out.speedDialCode = speedDialCode;\n\n const unformattedTelephoneNumber = readComponent(rep, 11, enc);\n if (unformattedTelephoneNumber !== undefined) {\n out.unformattedTelephoneNumber = unformattedTelephoneNumber;\n }\n\n return out;\n}\n","/**\n * `Field`: wrapper over a `RawField` exposing HL7 null/empty discrimination\n * (`isNull`), the raw repetitions tree, and a convenience `value` getter that\n * reads the first subcomponent of the first component of the first\n * repetition. Constructed internally by `Segment.field(n)`; user code never\n * calls `new Field(...)` directly.\n *\n * Typed composite coercions (`asXpn`, `asXad`, `asCx`, `asCwe`, `asCe`,\n * `asXtn`, `asPl`, `asTs`, `asNm`, `asHd`) delegate to the corresponding\n * composite parsers from `./types/*`. Coercions are lazy and NOT memoized\n * in v1 (D-09): each call re-parses the first repetition. Empty fields\n * return empty typed objects (`{}` for optional-field composites,\n * `{ raw: \"\", date: undefined }` / `{ raw: \"\", value: undefined }` for\n * the TS/NM scalar composites).\n */\n\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport { emitField } from \"../serialize/emit-field.js\";\nimport { renderText, type RenderedText, type RenderTextOptions } from \"../text/render.js\";\nimport type { EncodingCharacters, Hl7Position, RawField, RawRepetition } from \"../parser/types.js\";\nimport { parseCe, type CE } from \"./types/ce.js\";\nimport { parseCwe, type CWE } from \"./types/cwe.js\";\nimport { parseCx, type CX } from \"./types/cx.js\";\nimport { parseHd, type HD } from \"./types/hd.js\";\nimport { parseNm, type NM } from \"./types/nm.js\";\nimport { parsePl, type PL } from \"./types/pl.js\";\nimport { parseSn, type SN } from \"./types/sn.js\";\nimport { parseTs, type TS } from \"./types/ts.js\";\nimport { parseXad, type XAD } from \"./types/xad.js\";\nimport { parseXcn, type XCN } from \"./types/xcn.js\";\nimport { parseXpn, type XPN } from \"./types/xpn.js\";\nimport { parseXtn, type XTN } from \"./types/xtn.js\";\n\n/** Default position used by the shared empty-Field sentinel. @internal */\nconst DEFAULT_POSITION: Hl7Position = { segmentIndex: 0 };\n\n/**\n * Wrapper over a `RawField` exposing HL7 null/empty discrimination\n * (`isNull`), the repetitions tree, and a decoded `value` getter.\n * `seg.field(3) === seg.field(3)`: Field instances are referentially stable\n * per segment position (D-12).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * console.log(pid5?.value); // \"Smith\": decoded at parse\n * console.log(pid5?.isNull); // false: HL7 explicit null is \"\", absent is not\n * console.log(pid5?.repetitions.length); // 1\n * ```\n */\nexport class Field {\n /** HL7 null indicator: `true` iff the underlying field was the two-char literal `\"\"`. */\n public readonly isNull: boolean;\n\n /** Reference to the underlying `RawField.repetitions` (no defensive copy). */\n public readonly repetitions: readonly RawRepetition[];\n\n /** The 5 encoding characters for this message. Exposed for composite parsers (Plan 04). @internal */\n public readonly enc: EncodingCharacters;\n\n /** Position of this field in the parent message: used for position-aware error messages. @internal */\n public readonly position: Hl7Position;\n\n /** The full `RawField` this wrapper wraps. Exposed for composite parsers (Plan 02/03/04). @internal */\n public readonly raw: RawField;\n\n /**\n * Construct a new `Field`. Called internally by `Segment.field(n)`; user\n * code should obtain `Field` instances via `msg.segments(type)[i].field(n)`.\n * @internal\n */\n public constructor(raw: RawField, enc: EncodingCharacters, position: Hl7Position) {\n this.raw = raw;\n this.isNull = raw.isNull;\n this.repetitions = raw.repetitions;\n this.enc = enc;\n this.position = position;\n }\n\n /**\n * First-repetition, first-component, first-subcomponent value as a decoded\n * string: unescaped ONCE by the tokenizer on parse, returned verbatim here\n * (never re-unescaped, HL7-VALUE-REDECODE). Returns `\"\"` when the field is\n * empty or HL7 null. Equivalent to `msg.get('SEG.N')` for a top-level access.\n *\n * @example\n * ```ts\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * // wire \"Smith\\F\\Jr\" was decoded at parse → the field separator escape:\n * console.log(pid5?.value); // \"Smith|Jr\"\n * ```\n */\n public get value(): string {\n const rep = this.repetitions[0];\n if (rep === undefined) return \"\";\n const comp = rep.components[0];\n if (comp === undefined) return \"\";\n const sub = comp.subcomponents[0];\n if (sub === undefined) return \"\";\n // The tokenizer already unescaped every subcomponent on parse (parser-02),\n // so the stored value is decoded: return it directly. Re-unescaping here\n // would double-decode a value whose own bytes look like an escape (a wire\n // `\\E\\F\\E\\` decodes to `\\F\\`, which a second pass would wrongly turn into\n // `|`). Emit fidelity is handled separately by the raw overlay (HL7-ESC).\n return sub;\n }\n\n /**\n * The field's **canonical wire text**: the full field re-serialized with\n * the active delimiters and re-escaped content (repetitions, components,\n * and subcomponents included). Contrast with {@link value}, which\n * returns only the first subcomponent of the first component of the first\n * repetition (decoded once at parse: never re-unescaped).\n *\n * Use this when a field must be compared or echoed as a whole: e.g.\n * correlating an ACK's MSA-2 against the inbound MSH-10, where a\n * vendor-quirk control id containing an unescaped delimiter (`ID^X`) must\n * not be truncated to its first component.\n *\n * **Byte-verbatim for parsed content (HL7-ESC).** The parse pipeline stores\n * *decoded* content, but also records the original wire bytes of any escape\n * whose decode is not byte-faithful (`RawComponent.rawSubcomponents`), so\n * re-serialization preserves the sender's exact escape bytes: hex escapes\n * stay hex (`A\\X41\\B`, casing intact), and recognize-and-preserve sequences\n * (`\\H\\`, `\\N\\`, formatting/charset/vendor escapes) re-emit **verbatim**\n * rather than as escaped literal text. Delimiter/newline escapes and plain\n * content round-trip byte-exact via the re-escape path. The only remaining\n * canonicalization is structural: trailing insignificant empties are\n * stripped (D-02), and a field built by hand (not parsed) re-escapes its\n * decoded value since it has no overlay.\n *\n * **MSH-1/MSH-2 caveat.** Like {@link value}, calling this on MSH-1 or\n * MSH-2 (the delimiter-definition fields) re-escapes the encoding\n * characters themselves and produces garbage: those two fields are only\n * meaningful through `Hl7Message.encodingCharacters`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(\"MSH|^~\\\\&|A|B|C|D|20260101||ADT^A01|ID^X|P|2.5\\r\");\n * msg.segments(\"MSH\")[0]?.field(10).value; // \"ID\" (first component only)\n * msg.segments(\"MSH\")[0]?.field(10).text; // \"ID^X\" (verbatim wire text)\n * ```\n */\n public get text(): string {\n return emitField(this.raw, this.enc);\n }\n\n /**\n * Render this field's formatted text (HL7 v2 §2.7 highlight + formatting\n * escapes) into a normalized {@link RenderedText} display model: plain text\n * plus highlight-aware runs. A **read projection** over the field's\n * byte-verbatim wire {@link text}: it never mutates the raw value, and it\n * never fabricates (an unrenderable escape is preserved + flagged). Use this\n * to surface a clinical narrative (an NTE / OBX-5 note) to a human without\n * the raw `\\.br\\` / `\\H\\` sentinels.\n *\n * @param opts - see {@link RenderTextOptions} (e.g. a custom line-break string).\n * @returns the normalized display model.\n *\n * @example\n * ```ts\n * const note = msg.segments(\"OBX\")[0]?.field(5);\n * note?.render().text; // \"Specimen received.\\nGross exam normal.\"\n * ```\n */\n public render(opts?: RenderTextOptions): RenderedText {\n return renderText(this.text, this.enc, opts);\n }\n\n /**\n * Return a synthetic empty `Field` sentinel: used by `Segment.field(n)` to\n * honor MODEL-05's \"never throws on missing\" contract. The returned Field\n * has `isNull === false`, `repetitions === []`, and `value === \"\"`.\n * Referentially stable across calls (same instance returned each time).\n *\n * The `enc` argument is accepted for API symmetry but ignored: the\n * synthetic field carries no content, so unescape would be a no-op\n * regardless of the active encoding characters.\n *\n * @example\n * ```ts\n * const empty = Field.empty(msg.encodingCharacters);\n * console.log(empty.value); // \"\"\n * ```\n * @internal\n */\n public static empty(_enc: EncodingCharacters): Field {\n return EMPTY_FIELD;\n }\n\n /**\n * Coerce this field's first repetition to a typed `XPN` (Extended Person\n * Name). Absent components are OMITTED from the result\n * (`exactOptionalPropertyTypes`). Not memoized in v1: each call re-parses\n * (D-09).\n *\n * @example\n * ```ts\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * const name = pid5?.asXpn();\n * console.log(name?.familyName, name?.givenName);\n * ```\n */\n public asXpn(): XPN {\n return parseXpn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `XAD` (Extended Address).\n *\n * @example\n * ```ts\n * const addr = msg.segments(\"PID\")[0]?.field(11)?.asXad();\n * console.log(addr?.street, addr?.city, addr?.stateOrProvince);\n * ```\n */\n public asXad(): XAD {\n return parseXad(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `CX` (Extended Composite\n * ID). `assigningAuthority` is a nested `HD`.\n *\n * @example\n * ```ts\n * const mrn = msg.segments(\"PID\")[0]?.field(3)?.asCx();\n * console.log(mrn?.idNumber, mrn?.assigningAuthority?.namespaceId);\n * ```\n */\n public asCx(): CX {\n return parseCx(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `CWE` (Coded With\n * Exceptions).\n *\n * @example\n * ```ts\n * const code = msg.segments(\"OBX\")[0]?.field(3)?.asCwe();\n * console.log(code?.identifier, code?.text);\n * ```\n */\n public asCwe(): CWE {\n return parseCwe(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `CE` (Coded Element).\n *\n * @example\n * ```ts\n * const code = msg.segments(\"OBX\")[0]?.field(3)?.asCe();\n * console.log(code?.identifier, code?.text);\n * ```\n */\n public asCe(): CE {\n return parseCe(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `XTN` (Extended\n * Telecommunication Number).\n *\n * @example\n * ```ts\n * const phone = msg.segments(\"PID\")[0]?.field(13)?.asXtn();\n * console.log(phone?.telephoneNumber);\n * ```\n */\n public asXtn(): XTN {\n return parseXtn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `PL` (Person Location).\n * `facility` is a nested `HD`.\n *\n * @example\n * ```ts\n * const loc = msg.segments(\"PV1\")[0]?.field(3)?.asPl();\n * console.log(loc?.pointOfCare, loc?.room, loc?.facility?.namespaceId);\n * ```\n */\n public asPl(): PL {\n return parsePl(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `TS` (Time Stamp): the\n * fidelity `DtmParts` (raw + parts + precision + timezone). `valid` is\n * `false` on unparseable input (no throw). Build an absolute instant only on\n * explicit request via `dtmToDate(ts)`.\n *\n * @example\n * ```ts\n * const ts = msg.segments(\"MSH\")[0]?.field(7)?.asTs();\n * console.log(ts?.raw, ts?.precision, ts?.hasTimezone);\n * ```\n */\n public asTs(): TS {\n return parseTs(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `NM` (Numeric).\n * `{ raw, value }`: `value` is `undefined` on non-numeric input.\n *\n * @example\n * ```ts\n * const nm = msg.segments(\"OBX\")[0]?.field(5)?.asNm();\n * console.log(nm?.value);\n * ```\n */\n public asNm(): NM {\n return parseNm(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `SN` (Structured Numeric),\n * or `undefined` when the field carries no usable structured-numeric content.\n * Use for an OBX-5 whose OBX-2 value type is `SN` (a comparator like `>90`,\n * a range like `100-200`, or a ratio like `1:128`). `num1`/`num2` are\n * `number | undefined` (never `NaN`); the comparator is surfaced only when\n * SN.1 is a recognized operator.\n *\n * @example\n * ```ts\n * const sn = msg.segments(\"OBX\")[0]?.field(5)?.asSn();\n * console.log(sn?.comparator, sn?.num1); // \">\" 90\n * ```\n */\n public asSn(): SN | undefined {\n return parseSn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `HD` (Hierarchic\n * Designator).\n *\n * @example\n * ```ts\n * const sending = msg.segments(\"MSH\")[0]?.field(3)?.asHd();\n * console.log(sending?.namespaceId);\n * ```\n */\n public asHd(): HD {\n return parseHd(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n\n /**\n * Coerce this field's first repetition to a typed `XCN` (Extended Composite\n * ID Number and Name for Persons). `assigningAuthority` is a nested `HD`.\n * Common on OBR-16 (ordering provider), PV1-7 (attending doctor), PV1-8\n * (referring doctor). Empty field → `{}` (never throws).\n *\n * @example\n * ```ts\n * const orderedBy = msg.segments(\"OBR\")[0]?.field(16)?.asXcn();\n * console.log(orderedBy?.idNumber, orderedBy?.familyName, orderedBy?.identifierTypeCode);\n * ```\n */\n public asXcn(): XCN {\n return parseXcn(this.repetitions[0] ?? EMPTY_REP, this.enc);\n }\n}\n\nconst EMPTY_RAW_FIELD: RawField = Object.freeze({\n repetitions: Object.freeze([]),\n isNull: false,\n});\n\nconst EMPTY_FIELD = new Field(EMPTY_RAW_FIELD, DEFAULT_ENCODING_CHARACTERS, DEFAULT_POSITION);\n\n/**\n * Synthetic empty repetition: feeds composite parsers for empty fields so\n * they return `{}` / empty typed objects instead of throwing. Shared across\n * every `.asXxx()` coercion. Frozen so no parser can mutate the sentinel.\n * @internal\n */\nconst EMPTY_REP: RawRepetition = Object.freeze({\n components: Object.freeze([]),\n});\n","/**\n * `Segment`: wrapper class over a `RawSegment` that exposes `field(n)` with\n * referentially stable `Field` instances (D-12). Constructed internally by\n * `Hl7Message.segments(type)` / `Hl7Message.allSegments()`; user code never\n * calls `new Segment(...)` directly.\n *\n * The wrapper does NOT copy `raw.fields`: it holds a reference so mutations\n * through Plan 04's `setField` / `addSegment` / `removeSegment` stay visible.\n */\n\nimport { Field } from \"./field.js\";\nimport type { EncodingCharacters, RawField, RawSegment } from \"../parser/types.js\";\n\n/**\n * Wrapper over a `RawSegment` exposing typed per-position `Field` instances.\n * `seg.field(3) === seg.field(3)`: referential stability is guaranteed per\n * segment instance.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const pid = msg.segments(\"PID\")[0];\n * if (pid !== undefined) console.log(pid.field(5).value);\n * ```\n */\nexport class Segment {\n /** Segment name (3 chars, e.g. `\"PID\"`, `\"OBX\"`, `\"ZPI\"`). */\n public readonly type: string;\n\n /** Reference to the underlying `RawSegment.fields`: 1-indexed per HL7 convention. */\n public readonly fields: readonly RawField[];\n\n /** The 5 encoding characters for this message. Exposed for composite parsers. @internal */\n public readonly enc: EncodingCharacters;\n\n /** Absolute index of this segment in `Hl7Message.rawSegments[]`. Used for position tracking. @internal */\n public readonly absoluteIndex: number;\n\n /** The full `RawSegment` this wrapper wraps. Exposed for mutation methods (Plan 04). @internal */\n public readonly raw: RawSegment;\n\n /**\n * Lookup map from profile-declared field name → 1-indexed HL7 position.\n * Absent when no profile was applied to the parent message, or when the\n * applied profile does not declare `customSegments` for this segment's\n * type. Consumed by `get(name)` to resolve named-field access (PROF-07).\n * @internal\n */\n public readonly customFields: Readonly<Record<string, number>> | undefined;\n\n /** Lazy cache of Field wrappers: one per fields[] position. @internal */\n private _fieldWrappers: Field[] | undefined;\n\n /**\n * Construct a new `Segment`. Called internally by `Hl7Message`; user code\n * should obtain `Segment` instances via `msg.segments(type)` or\n * `msg.allSegments()`.\n *\n * The optional `customFields` parameter is the per-segment slice of the\n * applied profile's merged `customSegments` map (PROF-07 / D-16). When\n * supplied, `get(name)` resolves names against it; otherwise `get(name)`\n * always returns `undefined`.\n * @internal\n */\n public constructor(\n raw: RawSegment,\n enc: EncodingCharacters,\n absoluteIndex: number,\n customFields?: Readonly<Record<string, number>>,\n ) {\n this.raw = raw;\n this.type = raw.name;\n this.fields = raw.fields;\n this.enc = enc;\n this.absoluteIndex = absoluteIndex;\n this.customFields = customFields;\n }\n\n /**\n * Return the `Field` wrapper at HL7 position `n`. Indexing follows the HL7\n * 1-indexed convention: `seg.field(5)` on a PID segment maps to PID-5.\n * MSH segments use the same user-facing convention: `msh.field(1)` returns\n * the field-separator (MSH-1), `msh.field(2)` returns encoding chars\n * (MSH-2), `msh.field(3)` returns MSH-3, and so on: the internal\n * `fields[N-1]` offset for MSH segments is applied here (mirrors the\n * dot-path resolver in `dot-path.ts`, keeping `msg.segments('MSH')[0].field(3)`\n * and `msg.get('MSH.3')` in agreement).\n *\n * Returns a synthetic empty `Field` (`.isNull === false`, `.value === \"\"`)\n * when `n` is out of range: never throws (MODEL-05). Successive calls with\n * the same `n` return the same `Field` instance (D-12).\n *\n * @example\n * ```ts\n * const pid5 = msg.segments(\"PID\")[0]?.field(5);\n * console.log(pid5?.value); // \"Smith\"\n * const msh3 = msg.segments(\"MSH\")[0]?.field(3);\n * console.log(msh3?.value); // sending application (HL7 MSH-3)\n * ```\n */\n public field(n: number): Field {\n if (this._fieldWrappers === undefined) {\n // Build the full wrapper array. O(k) where k = fields.length; cached.\n this._fieldWrappers = this.fields.map(\n (rf, i) =>\n new Field(rf, this.enc, {\n segmentIndex: this.absoluteIndex,\n fieldIndex: i,\n }),\n );\n }\n // MSH offset: HL7 MSH-1 lives at fields[0] (separator), MSH-2 at fields[1]\n // (encoding chars), MSH-3 at fields[2], etc. Non-MSH segments use a\n // straight 1:1 mapping because fields[0] is the segment-name placeholder.\n const idx = this.type === \"MSH\" ? n - 1 : n;\n const f = this._fieldWrappers[idx];\n return f ?? Field.empty(this.enc);\n }\n\n /**\n * Return the `Field` at the profile-declared position for `name`, or\n * `undefined` when no custom mapping exists (PROF-07). Unlike `field(n)`,\n * missing names return `undefined`, NOT a synthetic empty Field, so\n * typos surface instead of silently resolving to an empty string (D-14).\n *\n * For segments without a profile-declared customSegments slice (most\n * non-Z segments, and any Z-segment whose host message had no profile\n * applied), this method always returns `undefined` (D-15 defense-in-depth\n *: D-05 already rejects standard-segment overlays at `defineProfile()`\n * time).\n *\n * When the declared position is out of range for the underlying\n * `RawSegment.fields`, `get(name)` returns `undefined` (NOT a\n * synthetic-empty Field) so callers can distinguish \"name not declared\"\n * from \"name declared but position missing in the raw message\" only at\n * the presence level (both collapse to `undefined` per D-14).\n *\n * @example\n * ```ts\n * const zpi = msg.allSegments().find((s) => s.type === \"ZPI\");\n * console.log(zpi?.get(\"encounterId\")?.value);\n * ```\n */\n public get(name: string): Field | undefined {\n const position = this.customFields?.[name];\n if (position === undefined) return undefined;\n // Delegate to field(n) for MSH-offset + wrapper-cache consistency.\n // field(n) returns Field.empty(enc) when out-of-range; we check whether\n // the field has content and return undefined for out-of-range so typos\n // surface (not a silent-empty read).\n const f = this.field(position);\n // Treat \"field has no repetitions AND not explicit-null\" as out-of-range.\n if (f.repetitions.length === 0 && !f.isNull) return undefined;\n return f;\n }\n}\n","/**\n * `allergies`: Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * AL1 segment in document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no AL1 present.\n * - D-06: NOT memoized: each call re-walks `msg.segments(\"AL1\")`.\n * - Phase N: `onsetDate` is the fidelity `TS` (precision + timezone preserved).\n * - D-22: never throws: empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"AL1\")`):\n * - `type` ← AL1-2 (IS: \"DA\"/\"FA\"/\"MA\"/\"EA\"/...)\n * - `code` ← AL1-3 (CWE)\n * - `severity` ← AL1-4 (IS: \"SV\"/\"MO\"/\"MI\")\n * - `reaction` ← AL1-5 (string / CWE first value)\n * - `onsetDate` ← AL1-6 (TS/DT → fidelity `TS`, Phase N)\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Allergy } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/**\n * Every AL1 as an `Allergy` entry in document order. D-05: returns `[]` when\n * no AL1 is present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const al of msg.allergies()) {\n * console.log(al.code?.identifier, al.severity, al.onsetDate?.raw);\n * }\n * ```\n *\n * @internal\n */\nexport function allergies(msg: Hl7Message): readonly Allergy[] {\n const out: Allergy[] = [];\n for (const al1 of msg.segments(\"AL1\")) {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<Allergy> = {};\n\n const type = stringOrUndefined(al1.field(2).value);\n if (type !== undefined) entry.type = type;\n\n const code = al1.field(3).asCwe();\n if (Object.keys(code).length > 0) entry.code = code;\n\n const severity = stringOrUndefined(al1.field(4).value);\n if (severity !== undefined) entry.severity = severity;\n\n const reaction = stringOrUndefined(al1.field(5).value);\n if (reaction !== undefined) entry.reaction = reaction;\n\n const onset = al1.field(6).asTs();\n if (onset.valid) entry.onsetDate = onset;\n\n out.push(Object.freeze(entry));\n }\n return Object.freeze(out);\n}\n","/**\n * `appointments`: Phase Q (scheduling breadth) implementation of the SIU\n * appointment extractor. Walks the message in document order and projects each\n * SCH (Scheduling Activity Information) segment into a typed {@link Appointment},\n * grouping the AIS/AIG/AIL/AIP resource segments that follow it positionally\n * under that SCH: the same open-a-group-on-the-anchor state machine\n * `immunizations()` uses for ORC→RXA→[RXR]. Covers the common SIU trigger\n * events (S12 new / S13 reschedule / S14 modify / S15 cancel / S26 no-show).\n *\n * Field map (HL7 v2 Ch. 10: scheduling):\n * - SCH-1 placer appointment ID (EI; first component surfaced verbatim)\n * - SCH-2 filler appointment ID (EI; first component surfaced verbatim)\n * - SCH-11 appointment timing quantity (TQ): TQ.4 start / TQ.5 end (DTM)\n * - SCH-25 filler status code (CWE: HL7 Table 0278): the appointment status\n * - AIS-3 universal service ID (CE) → resource kind \"service\"\n * - AIG-3 general resource ID (CE) → resource kind \"general\"\n * - AIL-3 location resource (PL / coded) → resource kind \"location\"\n * - AIP-3 personnel resource (XCN) → resource kind \"personnel\" (provider)\n *\n * Safety rules enforced here (Phase Q §Fail-safe):\n * - Never throws: a malformed SCH / AI* surfaces as omitted keys (HELPERS-07).\n * - The filler status code (SCH-25) is surfaced VERBATIM (provenance-only): a\n * mis-keyed status is echoed exactly, never normalized or validated.\n * - Missing fields → keys omitted; `resources` is ALWAYS a (possibly empty) array.\n * - Output is frozen at the boundary (D-01); NOT memoized (D-06).\n *\n * Known limitations: this covers the appointment-level identifiers, status,\n * SCH-11 timing, and the AI* resource identifiers only: it is NOT a\n * scheduling-workflow state machine, and it does not resolve per-resource start\n * offsets/durations. See KNOWN-LIMITATIONS.md.\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { RawComponent } from \"../parser/types.js\";\nimport { parseDtm } from \"../parser/dates.js\";\nimport { readSubcomponent } from \"../model/types/_shared.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\n\nimport type { Appointment, AppointmentResource } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so an optional CWE key stays absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/** First repetition's component at `index` (or `undefined`). @internal */\nfunction componentAt(field: Field, index: number): RawComponent | undefined {\n return field.repetitions[0]?.components[index];\n}\n\n/** Read `field`'s first-repetition component `compIdx`, subcomponent `subIdx`, unescaped. @internal */\nfunction fieldSub(field: Field, compIdx: number, subIdx: number): string | undefined {\n return readSubcomponent(componentAt(field, compIdx), subIdx, field.enc);\n}\n\n/**\n * The AI* segment types that carry an appointment resource, mapped to the\n * `kind` surfaced on {@link AppointmentResource}. AIP is the personnel\n * (provider) resource; AIL the location. @internal\n */\nconst RESOURCE_KIND: Readonly<Record<string, AppointmentResource[\"kind\"]>> = Object.freeze({\n AIS: \"service\",\n AIG: \"general\",\n AIL: \"location\",\n AIP: \"personnel\",\n});\n\n/**\n * Build one {@link AppointmentResource} from an AI* segment. The resource id\n * lives at position 3 for all four segment types; AIP-3 is an `XCN` (personnel)\n * and is additionally surfaced as `person`, while AIS/AIG/AIL-3 surface as a\n * coded `code` (first component verbatim). Returns `undefined` when the segment\n * carries no resource id at all. @internal\n */\nfunction buildResource(seg: Segment): AppointmentResource | undefined {\n const kind = RESOURCE_KIND[seg.type];\n if (kind === undefined) return undefined;\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<AppointmentResource> = { kind };\n\n const field3 = seg.field(3);\n if (kind === \"personnel\") {\n const person: XCN = field3.asXcn();\n if (Object.keys(person).length > 0) out.person = person;\n }\n // Every AI*-3 is surfaced as a coded element too (provenance-only, first\n // component verbatim) so a uniform `code.identifier` is always available.\n const code = cweOrUndefined(field3);\n if (code !== undefined) out.code = code;\n\n // A resource with no id at all is not worth surfacing.\n if (out.code === undefined && out.person === undefined) return undefined;\n return Object.freeze(out) as AppointmentResource;\n}\n\n/** Build a frozen {@link Appointment} from one SCH + its attached AI* resources. @internal */\nfunction finalizeAppointment(sch: Segment, resources: readonly AppointmentResource[]): Appointment {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Appointment> = { resources: Object.freeze(resources.slice()) };\n\n // SCH-1 / SCH-2 appointment ids (EI): first component surfaced verbatim.\n const placer = stringOrUndefined(sch.field(1).value);\n if (placer !== undefined) out.placerAppointmentId = placer;\n const filler = stringOrUndefined(sch.field(2).value);\n if (filler !== undefined) out.fillerAppointmentId = filler;\n\n // SCH-11 appointment timing quantity (TQ): TQ.4 start / TQ.5 end (DTM).\n const timing = sch.field(11);\n const startRaw = fieldSub(timing, 3, 0);\n if (startRaw !== undefined) out.startDateTime = parseDtm(startRaw);\n const endRaw = fieldSub(timing, 4, 0);\n if (endRaw !== undefined) out.endDateTime = parseDtm(endRaw);\n\n // SCH-25 filler status code (Table 0278): verbatim/provenance-only.\n const status = cweOrUndefined(sch.field(25));\n if (status !== undefined) out.fillerStatusCode = status;\n\n return Object.freeze(out) as Appointment;\n}\n\n/**\n * Every SCH of an SIU message as a typed {@link Appointment}, with the\n * AIS/AIG/AIL/AIP resource segments that follow it grouped positionally under\n * that SCH (service / general resource / location / personnel). Document order.\n * Returns `[]` when no SCH is present. NOT memoized: each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * The filler status code (SCH-25, Table 0278) is surfaced verbatim; per-resource\n * offsets/durations and the full scheduling workflow are out of scope (see the\n * package known-limitations).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const appt of msg.appointments()) {\n * console.log(appt.fillerAppointmentId, appt.fillerStatusCode?.identifier);\n * console.log(appt.startDateTime?.raw, appt.endDateTime?.raw);\n * for (const r of appt.resources) console.log(r.kind, r.code?.identifier, r.person?.familyName);\n * }\n * ```\n *\n * @internal\n */\nexport function appointments(msg: Hl7Message): readonly Appointment[] {\n const out: Appointment[] = [];\n\n let currentSch: Segment | undefined;\n let resources: AppointmentResource[] = [];\n\n const closeCurrent = (): void => {\n if (currentSch !== undefined) out.push(finalizeAppointment(currentSch, resources));\n };\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"SCH\") {\n closeCurrent();\n currentSch = seg;\n resources = [];\n continue;\n }\n if (currentSch === undefined) continue; // AI* before any SCH: dropped.\n if (RESOURCE_KIND[seg.type] !== undefined) {\n const resource = buildResource(seg);\n if (resource !== undefined) resources.push(resource);\n }\n }\n\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `charges`: Phase Q (financial breadth) implementation of the DFT charge\n * extractor. Walks the message in document order and projects each FT1\n * (Financial Transaction) segment into a typed {@link Charge}. Flat, one FT1\n * per {@link Charge} (parity with `diagnoses()` / `allergies()`): DFT^P03 posts\n * a list of financial transactions, each self-contained. Covers the common\n * DFT^P03 post-charges event.\n *\n * Field map (HL7 v2 Ch. 6: financial management):\n * - FT1-4 transaction date (TS)\n * - FT1-6 transaction type (IS: Table 0017: CG charge / CD credit /\n * PY payment / AJ adjustment; verbatim)\n * - FT1-7 transaction code (CE: the institution charge/procedure code)\n * - FT1-10 transaction quantity (NM)\n * - FT1-11 transaction amount, extended (CP): surfaced as canonical wire text\n * - FT1-12 transaction amount, unit (CP): surfaced as canonical wire text\n * - FT1-19 diagnosis code(s) (CE, repeating): billing diagnosis linkage\n *\n * Safety rules enforced here (Phase Q §Fail-safe):\n * - Never throws: a malformed FT1 surfaces as omitted keys (HELPERS-07).\n * - **No billing logic, no money-as-float.** The extended/unit amounts (CP)\n * are surfaced as their canonical wire text (`amountExtended`/`amountUnit`),\n * never parsed to a `number`: currency + price are preserved intact and no\n * rounding is ever introduced. `Field.text` is byte-exact for a plain numeric\n * amount (`150.00^USD`); it canonicalizes only escape sequences + trailing\n * empty components (D-02), which a CP amount does not carry. The transaction\n * type + code are provenance-only; nothing is validated, priced, or adjudicated.\n * - Missing fields → keys omitted; `diagnoses` is ALWAYS a (possibly empty)\n * array.\n * - Output is frozen at the boundary (D-01); NOT memoized (D-06).\n *\n * Known limitations: `charges()` surfaces billing-critical FT1 fields only. It\n * is NOT a claims/pricing engine: no charge validation, no adjudication, no\n * amount arithmetic. See KNOWN-LIMITATIONS.md.\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport { parseCwe, type CWE } from \"../model/types/cwe.js\";\n\nimport type { Charge } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so an optional CWE key stays absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Every repetition of a repeating coded field as a `CWE`, dropping empty\n * repetitions. Used for FT1-19 (diagnosis linkage, repeating CE). @internal\n */\nfunction repeatingCwe(field: Field): readonly CWE[] {\n const out: CWE[] = [];\n for (const rep of field.repetitions) {\n const cwe = parseCwe(rep, field.enc);\n if (Object.keys(cwe).length > 0) out.push(Object.freeze(cwe));\n }\n return out;\n}\n\n/** Build a frozen {@link Charge} from one FT1 segment. @internal */\nfunction finalizeCharge(ft1: Segment): Charge {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Charge> = { diagnoses: Object.freeze(repeatingCwe(ft1.field(19))) };\n\n // FT1-4 transaction date (fidelity TS, Phase N).\n const transactionDate = ft1.field(4).asTs();\n if (transactionDate.raw !== \"\") out.transactionDate = transactionDate;\n\n // FT1-6 transaction type (Table 0017): verbatim.\n const transactionType = stringOrUndefined(ft1.field(6).value);\n if (transactionType !== undefined) out.transactionType = transactionType;\n\n // FT1-7 transaction code: institution charge/procedure code (CWE).\n const transactionCode = cweOrUndefined(ft1.field(7));\n if (transactionCode !== undefined) out.transactionCode = transactionCode;\n\n // FT1-10 transaction quantity (NM): strict-parsed, never NaN.\n const quantity = ft1.field(10).asNm().value;\n if (quantity !== undefined) out.quantity = quantity;\n\n // FT1-11 / FT1-12 extended / unit amount (CP): canonical wire text, never a float.\n const amountExtended = stringOrUndefined(ft1.field(11).text);\n if (amountExtended !== undefined) out.amountExtended = amountExtended;\n const amountUnit = stringOrUndefined(ft1.field(12).text);\n if (amountUnit !== undefined) out.amountUnit = amountUnit;\n\n return Object.freeze(out) as Charge;\n}\n\n/**\n * Every FT1 of a DFT message as a typed {@link Charge}, one per FT1 in document\n * order. Returns `[]` when no FT1 is present. NOT memoized: each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * Billing-critical fields are surfaced (transaction type/code, extended/unit\n * amount, diagnosis linkage); there is **no billing logic and no money-as-float**\n *: amounts are the canonical CP wire text (byte-exact for a plain numeric\n * amount), never a `number`. See {@link Charge}.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const charge of msg.charges()) {\n * console.log(charge.transactionType, charge.transactionCode?.identifier);\n * console.log(charge.amountExtended); // e.g. \"150.00^USD\": wire text, never a number\n * for (const dx of charge.diagnoses) console.log(dx.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function charges(msg: Hl7Message): readonly Charge[] {\n const out: Charge[] = [];\n for (const seg of msg.allSegments()) {\n if (seg.type === \"FT1\") out.push(finalizeCharge(seg));\n }\n return Object.freeze(out);\n}\n","/**\n * `diagnoses`: Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * DG1 segment in document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no DG1 present.\n * - D-06: NOT memoized: each call re-walks `msg.segments(\"DG1\")`.\n * - Phase N: `dateTime` is the fidelity `TS` (precision + timezone preserved).\n * - D-22: never throws: empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"DG1\")`):\n * - `code` ← DG1-3 (CWE)\n * - `description` ← DG1-4 (ST)\n * - `dateTime` ← DG1-5 (TS/DT → fidelity `TS`, Phase N)\n * - `type` ← DG1-6 (IS: \"A\"=admit, \"W\"=working, \"F\"=final)\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Diagnosis } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/**\n * Every DG1 as a `Diagnosis` entry in document order. D-05: returns `[]` when\n * no DG1 is present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const dg of msg.diagnoses()) {\n * console.log(dg.code?.identifier, dg.description, dg.type);\n * }\n * ```\n *\n * @internal\n */\nexport function diagnoses(msg: Hl7Message): readonly Diagnosis[] {\n const out: Diagnosis[] = [];\n for (const dg1 of msg.segments(\"DG1\")) {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<Diagnosis> = {};\n\n const code = dg1.field(3).asCwe();\n if (Object.keys(code).length > 0) entry.code = code;\n\n const description = stringOrUndefined(dg1.field(4).value);\n if (description !== undefined) entry.description = description;\n\n const dt = dg1.field(5).asTs();\n if (dt.valid) entry.dateTime = dt;\n\n const type = stringOrUndefined(dg1.field(6).value);\n if (type !== undefined) entry.type = type;\n\n out.push(Object.freeze(entry));\n }\n return Object.freeze(out);\n}\n","/**\n * `groupNotes` / `notes`: Phase P implementation of NTE narrative grouping.\n * Groups **NTE** (Notes and Comments) segments to their parent **by position**:\n * an NTE inherits its meaning entirely from the segment that immediately\n * precedes it (HL7 v2 Ch. 2: the NTE carries no link field, so attachment is\n * purely positional). In an ORU the grammar is\n * `{ [ORC] OBR [{NTE}] [{ [OBX] [{NTE}] }] }`, so a note after OBR is\n * order-level and a note after OBX is *that* result-level (Ch. 7).\n *\n * Recognized parents and where their notes surface:\n * - `PID` → the patient view (`msg.patient.notes`).\n * - `ORC` / `OBR` → the order (`order.notes`).\n * - `OBX` → that specific observation (`observation.notes`).\n *\n * Design decisions enforced here:\n * - **Positional, never guessed.** The parent is the nearest *preceding\n * non-NTE* segment (consecutive NTEs chain to the same parent). Any\n * non-NTE segment that is NOT a recognized parent (e.g. `PV1`, `AL1`,\n * `MSH`) resets the target: a subsequent NTE is then surfaced\n * message-level, not attached to an unrelated earlier parent (fail safe;\n * the spec's \"profile-specific placement outside the common patterns is\n * surfaced message-level, not guessed\").\n * - **Never dropped: even when the parent's helper projection is dropped.**\n * A note whose recognized parent is *not* surfaced by any helper falls to\n * the message-level `unattached` bucket rather than vanishing. Two such\n * cases: (1) a **later PID** in a multi-patient ORU (`msg.patient` is the\n * first PID only), and (2) an **ORC region that never opens an order**: a\n * trailing/dangling ORC with no following OBR. To handle the ORC↔order\n * relationship, notes seen after an `ORC` (before its OBR) are **buffered**\n * and flushed onto the OBR that opens the order (in document order, ahead of\n * the OBR's own notes): exactly mirroring how `orders()` promotes a pending\n * ORC. Several ORCs before one OBR all flush to that order; nothing is lost.\n * - **Order preserved.** Note lines accumulate in document order per parent;\n * across parents the walk is `msg.allSegments()` order. Order-level notes\n * land on the OBR key in document order, so ORC-region notes precede\n * OBR-region notes without any hardcoded assumption about ORC-vs-OBR order.\n * - **Keyed by Segment reference.** `allSegments()` / `segments(type)` return\n * referentially-stable `Segment` instances from one master cache, so a\n * `Map<Segment, …>` lets `observations()` / `orders()` / `patient` look up\n * a parent's notes without re-implementing the positional walk.\n * - **NTE-3 (Comment, FT, repeating).** Each non-empty NTE-3 repetition is one\n * note line. The FULL repetition text is reassembled (all components /\n * subcomponents), HL7-unescaped: a non-conformant raw `^`/`&` in the FT\n * narrative tokenizes into components, so reading only the first would\n * truncate the note (silent clinical-text loss). NTE-1 (set id), NTE-2\n * (source of comment), and NTE-4 (comment type) are intentionally deferred,\n * FT formatting beyond the standard escape set is not specially rendered.\n * - NTE free-text is high-PHI-risk clinical narrative: it is payload; no\n * warning or log line echoes it.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\n\n/**\n * Sentinel target for notes seen in the ORC→OBR region: they belong to the\n * order the next OBR opens, so they are buffered and flushed onto that OBR\n * (mirroring `orders()` ORC promotion). @internal\n */\nconst ORDER_SINK = Symbol(\"order-sink\");\n\n/**\n * Positional grouping of every NTE segment's note lines. `byParent` maps a\n * recognized parent `Segment` (by reference) to its accumulated note lines;\n * `unattached` holds message-level notes with no recognized preceding parent.\n */\nexport interface NoteGrouping {\n /** Recognized parent segment → its note lines, in document order. */\n readonly byParent: ReadonlyMap<Segment, readonly string[]>;\n /** Message-level notes (no recognized preceding parent), in document order. */\n readonly unattached: readonly string[];\n}\n\n/**\n * Extract the note lines from one NTE segment: each non-empty NTE-3 (Comment,\n * FT) repetition as one line, decoded, in order. An NTE carrying no NTE-3\n * text yields `[]`.\n *\n * The FULL repetition text is reassembled: a lenient parser tokenizes a\n * non-conformant raw `^`/`&` in the FT narrative into components/subcomponents,\n * so reading only the first would silently truncate the note. Each leaf is\n * already decoded by the tokenizer (parser-02): it is used verbatim, NOT\n * re-unescaped (a second decode would double-decode a value whose bytes look\n * like an escape, HL7-VALUE-REDECODE): and components/subcomponents are\n * rejoined with the literal delimiters so both the conformant (`\\S\\`-escaped)\n * and quirky (raw-caret) forms read to the same text.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const nte = parseHL7(\"MSH|^~\\\\&|A|B|||1||ORU^R01|1|T|2.5\\rNTE|1||a~b\\r\").segments(\"NTE\")[0];\n * if (nte !== undefined) extractNoteLines(nte); // [\"a\", \"b\"]\n * ```\n *\n * @internal\n */\nexport function extractNoteLines(nte: Segment): string[] {\n const field = nte.field(3);\n const enc = field.enc;\n const lines: string[] = [];\n for (const rep of field.repetitions) {\n // Subcomponents are already decoded by the tokenizer: join them verbatim,\n // never a second `unescape` (HL7-VALUE-REDECODE).\n const text = rep.components\n .map((c) => c.subcomponents.join(enc.subcomponent))\n .join(enc.component);\n if (text !== \"\") lines.push(text);\n }\n return lines;\n}\n\n/**\n * Walk the message once and group NTE note lines to their positional parent.\n * The returned maps/arrays are frozen at the boundary. NOT memoized: each\n * caller (`observations()` / `orders()` / `buildPatient()` / `msg.notes()`)\n * re-walks, mirroring the non-memoized collection helpers.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const grouping = groupNotes(msg);\n * grouping.unattached; // message-level notes\n * grouping.byParent.get(msg.segments(\"OBX\")[0]!); // that OBX's notes\n * ```\n *\n * @internal\n */\nexport function groupNotes(msg: Hl7Message): NoteGrouping {\n const byParent = new Map<Segment, string[]>();\n const unattached: string[] = [];\n // Notes buffered in an ORC→OBR region; flushed onto the OBR that opens the\n // order, or to message level if no OBR follows (trailing/dangling ORC).\n let pendingOrderNotes: string[] = [];\n let sawPid = false;\n // Where the NEXT NTE's lines go: a recognized parent Segment (PID#1 / OBR /\n // OBX), the ORC sink, or `undefined` (message-level).\n let target: Segment | typeof ORDER_SINK | undefined;\n\n /** Append `lines` to a parent's accumulator (first write owns the array). */\n const attach = (parent: Segment, lines: string[]): void => {\n const existing = byParent.get(parent);\n if (existing === undefined) byParent.set(parent, lines);\n else existing.push(...lines);\n };\n\n for (const seg of msg.allSegments()) {\n const type = seg.type;\n\n if (type === \"NTE\") {\n const lines = extractNoteLines(seg);\n if (lines.length === 0) continue; // an empty NTE contributes nothing\n if (target === ORDER_SINK) pendingOrderNotes.push(...lines);\n else if (target === undefined) unattached.push(...lines);\n else attach(target, lines);\n continue;\n }\n\n if (type === \"OBR\") {\n // Open the order: seed its notes with the buffered ORC-region notes (in\n // document order, ahead of the OBR's own), then collect onto this OBR.\n if (pendingOrderNotes.length > 0) {\n attach(seg, pendingOrderNotes);\n pendingOrderNotes = []; // hand ownership to byParent; start a fresh buffer\n }\n target = seg;\n continue;\n }\n\n if (type === \"ORC\") {\n target = ORDER_SINK; // following notes belong to the order this ORC opens\n continue;\n }\n\n if (type === \"OBX\") {\n target = seg;\n continue;\n }\n\n if (type === \"PID\") {\n // Only the first PID is surfaced by `msg.patient`; a later PID's notes\n // have no dedicated surface, so route them to message level rather than\n // dropping them or mis-attaching them to the first patient.\n target = sawPid ? undefined : seg;\n sawPid = true;\n continue;\n }\n\n // Any other segment (MSH, PV1, AL1, …) re-scopes the immediate target to\n // message level (fail-safe: never guess). A buffered ORC region survives:\n // it still belongs to the order its OBR will open.\n target = undefined;\n }\n\n // A trailing ORC region that never opened an order → message level (never dropped).\n if (pendingOrderNotes.length > 0) unattached.push(...pendingOrderNotes);\n\n const frozenByParent = new Map<Segment, readonly string[]>();\n for (const [parent, lines] of byParent) frozenByParent.set(parent, Object.freeze(lines));\n\n return {\n byParent: frozenByParent,\n unattached: Object.freeze(unattached),\n };\n}\n\n/**\n * Message-level notes: surfaced verbatim in document order so nothing is ever\n * dropped. This bucket holds an NTE with **no recognized preceding parent**\n * (not immediately following a `PID` / `ORC` / `OBR` / `OBX`), plus the notes\n * whose recognized parent has **no surfaced projection**: a later `PID`'s notes\n * in a multi-patient ORU (`msg.patient` is the first PID only) and an ORC region\n * that never opens an order (a trailing/dangling `ORC` with no following OBR).\n * Notes that DO attach to a specific patient / order / result are exposed on\n * those helper outputs (`msg.patient?.notes`, `order.notes`, `observation.notes`)\n *: not here. D-05: returns `[]` when there are none. NOT memoized.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const note of msg.notes()) console.log(note); // message-level narrative\n * ```\n *\n * @internal\n */\nexport function notes(msg: Hl7Message): readonly string[] {\n return groupNotes(msg).unattached;\n}\n","/**\n * `observations` + `buildObservation`: Phase 4 Plan 03 (visit-and-observations)\n * implementation of HELPERS-04. Walks every OBX segment in document order and\n * projects each into a typed `Observation` discriminated by OBX-2\n * (`valueType`) per D-13. The per-segment builder `buildObservation` is\n * exported so Plan 04's `orders()` can reuse the same OBX → Observation\n * dispatch without duplicating the value-type switch (D-12 positional\n * grouping).\n *\n * Design decisions enforced here:\n * - D-05: `observations(msg)` always returns a readonly array: `[]` when\n * the message has no OBX segments.\n * - D-06: NOT memoized: each call re-walks `msg.segments(\"OBX\")`.\n * - D-11: document order (matches the segment iteration order).\n * - D-13: discriminated union on `valueType`:\n * - `\"NM\"` → `number | undefined` (via `Field.asNm()`)\n * - `\"SN\"` → `SN | undefined` (via `Field.asSn()`, structured numeric)\n * - `\"TS\" | \"DT\"` → `TS | undefined` (via `Field.asTs()`, fidelity per Phase N)\n * - `\"CWE\" | \"CE\"` → composite | undefined (via `Field.asCwe/asCe`)\n * - other (`ST`/`TX`/`FT`/`ID`/`IS`/unknown) → `string | undefined`\n * - D-15: common-field shape (setId, identifier, units, referenceRange,\n * abnormalFlags, status, observedDateTime).\n * - Phase N: datetime values are the fidelity `TS`, not a flat `Date`.\n * - D-22: never throws: empty or malformed input surfaces as `undefined`.\n * - D-01: each Observation and the outer array are frozen at the boundary.\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CE } from \"../model/types/ce.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport { groupNotes } from \"./notes.js\";\nimport type { Observation, ObservationBase } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so optional `units` keys stay absent when OBX-6 was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Build the common (valueType-agnostic) piece of an Observation from one OBX\n * Segment. Omits keys that are absent so the output stays\n * `exactOptionalPropertyTypes`-clean.\n *\n * @internal\n */\nfunction buildCommon(obx: Segment): ObservationBase {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n // `identifier` is always present (D-15): always parse OBX-3, even if empty.\n const base: Mutable<ObservationBase> = {\n identifier: obx.field(3).asCwe(),\n };\n\n const setId = stringOrUndefined(obx.field(1).value);\n if (setId !== undefined) base.setId = setId;\n\n const units = cweOrUndefined(obx.field(6));\n if (units !== undefined) {\n base.units = units;\n // OBX-6 CWE.3 == \"UCUM\" (HL7 Table 0396): the unit is declared UCUM.\n // Present-but-not-UCUM units surface `false` (never coerced); the flag is\n // omitted entirely when OBX-6 is absent.\n base.unitsAreUcum = units.nameOfCodingSystem === \"UCUM\";\n }\n\n const referenceRange = stringOrUndefined(obx.field(7).value);\n if (referenceRange !== undefined) base.referenceRange = referenceRange;\n\n const abnormalFlags = stringOrUndefined(obx.field(8).value);\n if (abnormalFlags !== undefined) base.abnormalFlags = abnormalFlags;\n\n const status = stringOrUndefined(obx.field(11).value);\n if (status !== undefined) base.status = status;\n\n const observedDateTime = obx.field(14).asTs();\n if (observedDateTime.valid) base.observedDateTime = observedDateTime;\n\n return base as ObservationBase;\n}\n\n/**\n * Dispatch the OBX-5 value to the correct parser based on OBX-2 `valueType`\n * per D-13. The returned object is frozen at the boundary (D-01).\n *\n * @internal\n */\nfunction dispatchValue(valueType: string, valueField: Field, common: ObservationBase): Observation {\n switch (valueType) {\n case \"NM\": {\n const nm = valueField.asNm();\n return Object.freeze({\n ...common,\n valueType: \"NM\" as const,\n value: nm.value,\n });\n }\n case \"SN\": {\n // Structured numeric: preserve the comparator/range/ratio as typed data\n // instead of letting `<10` collapse to the bare string \"<\" (D-13). The\n // inner SN object is frozen too so the whole Observation is deeply\n // immutable at the boundary (D-01).\n const sn = valueField.asSn();\n return Object.freeze({\n ...common,\n valueType: \"SN\" as const,\n value: sn === undefined ? undefined : Object.freeze(sn),\n });\n }\n case \"TS\":\n case \"DT\": {\n const ts = valueField.asTs();\n return Object.freeze({\n ...common,\n valueType,\n value: ts.valid ? ts : undefined,\n });\n }\n case \"CWE\": {\n const cwe = valueField.asCwe();\n const value: CWE | undefined = Object.keys(cwe).length === 0 ? undefined : cwe;\n return Object.freeze({\n ...common,\n valueType: \"CWE\" as const,\n value,\n });\n }\n case \"CE\": {\n const ce = valueField.asCe();\n const value: CE | undefined = Object.keys(ce).length === 0 ? undefined : ce;\n return Object.freeze({\n ...common,\n valueType: \"CE\" as const,\n value,\n });\n }\n default: {\n const raw = valueField.value;\n const value = raw === \"\" ? undefined : raw;\n return Object.freeze({\n ...common,\n valueType,\n value,\n });\n }\n }\n}\n\n/**\n * Build a single `Observation` from one OBX `Segment`. Value is dispatched\n * by OBX-2 per D-13; common fields follow D-15. Exported so Plan 04's\n * `orders()` can reuse this per-segment builder when grouping OBX under OBR\n * positionally (D-12): do NOT re-implement OBX → Observation construction\n * there.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const obx = msg.segments(\"OBX\")[0];\n * if (obx !== undefined) {\n * const obs = buildObservation(obx);\n * if (obs.valueType === \"NM\") console.log(obs.value);\n * }\n * ```\n */\nexport function buildObservation(obx: Segment, notes?: readonly string[]): Observation {\n const base = buildCommon(obx);\n // Phase P: attach positionally-grouped NTE note lines when present. The\n // `notes` array is already frozen by `groupNotes`; omit the key when empty so\n // the shape stays `exactOptionalPropertyTypes`-clean.\n const common: ObservationBase =\n notes !== undefined && notes.length > 0 ? { ...base, notes } : base;\n const valueType = obx.field(2).value;\n const valueField = obx.field(5);\n return dispatchValue(valueType, valueField, common);\n}\n\n/**\n * Every OBX segment as a typed `Observation` in document order (D-11). D-05:\n * returns `[]` when no OBX segments are present. D-06: NOT memoized: each\n * call re-walks `msg.segments(\"OBX\")`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const obs of msg.observations()) {\n * if (obs.valueType === \"NM\") console.log(obs.value); // number | undefined\n * else if (obs.valueType === \"TS\") console.log(obs.value?.raw, obs.value?.precision);\n * }\n * ```\n *\n * @internal\n */\nexport function observations(msg: Hl7Message): readonly Observation[] {\n const noteIndex = groupNotes(msg);\n const out: Observation[] = [];\n for (const obx of msg.segments(\"OBX\")) {\n out.push(buildObservation(obx, noteIndex.byParent.get(obx)));\n }\n return Object.freeze(out);\n}\n","/**\n * `documents`: Phase Q (document breadth) implementation of the MDM\n * document extractor. Walks the message in document order and projects each\n * TXA (Transcription Document Header) segment into a typed\n * {@link ClinicalDocument}, grouping the OBX narrative body that follows it\n * positionally under that TXA: the same open-a-group-on-the-anchor state\n * machine `immunizations()` uses for RXA→[OBX]. Covers the common MDM trigger\n * events (T02 original / T04 status change / T06 addendum).\n *\n * Field map (HL7 v2 Ch. 9: medical records / MDM):\n * - TXA-2 document type (IS: Table 0270; verbatim)\n * - TXA-4 activity date/time (TS)\n * - TXA-12 unique document number (EI; first component surfaced verbatim)\n * - TXA-13 parent document number (EI; addendum/replacement link)\n * - TXA-17 document COMPLETION status (ID: Table 0271)\n * - TXA-19 document AVAILABILITY status (ID: Table 0273)\n * - OBX the transcribed narrative body, grouped under the TXA\n *\n * Safety rules enforced here (Phase Q §Fail-safe: the load-bearing one):\n * - **TXA-17 completion status and TXA-19 availability status are surfaced as\n * DISTINCT fields and NEVER conflated.** A document can be *available*\n * (TXA-19 = `AV`) before it is *authenticated / legally authenticated*\n * (TXA-17 = `AU`/`LA`); a still-*preliminary* completion is a different\n * axis from availability. Reading a preliminary document as final is the\n * clinical harm this split exists to prevent. Both are verbatim,\n * provenance-only: never validated, never merged, never defaulted.\n * - Never throws: a malformed TXA surfaces as omitted keys (HELPERS-07).\n * - Missing fields → keys omitted; `observations` is ALWAYS a (possibly\n * empty) array.\n * - Output is frozen at the boundary (D-01); NOT memoized (D-06).\n *\n * Known limitations: `documents()` surfaces the document header + narrative body\n * only. It does NOT verify authentication signatures (TXA-22), resolve the\n * parent-document chain, or interpret confidentiality. See KNOWN-LIMITATIONS.md.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\n\nimport { groupNotes } from \"./notes.js\";\nimport { buildObservation } from \"./observations.js\";\nimport type { ClinicalDocument, Observation } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Build a frozen {@link ClinicalDocument} from one TXA + its grouped OBX body. @internal */\nfunction finalizeDocument(txa: Segment, observations: readonly Observation[]): ClinicalDocument {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<ClinicalDocument> = { observations: Object.freeze(observations.slice()) };\n\n // TXA-2 document type (Table 0270): verbatim.\n const documentType = stringOrUndefined(txa.field(2).value);\n if (documentType !== undefined) out.documentType = documentType;\n\n // TXA-4 activity date/time (fidelity TS, Phase N).\n const activity = txa.field(4).asTs();\n if (activity.raw !== \"\") out.activityDateTime = activity;\n\n // TXA-12 unique document number (EI): first component verbatim.\n const uniqueDoc = stringOrUndefined(txa.field(12).value);\n if (uniqueDoc !== undefined) out.uniqueDocumentNumber = uniqueDoc;\n\n // TXA-13 parent document number (EI): addendum/replacement link.\n const parentDoc = stringOrUndefined(txa.field(13).value);\n if (parentDoc !== undefined) out.parentDocumentNumber = parentDoc;\n\n // TXA-17 completion status (Table 0271): DISTINCT from availability (TXA-19).\n const completion = stringOrUndefined(txa.field(17).value);\n if (completion !== undefined) out.completionStatus = completion;\n\n // TXA-19 availability status (Table 0273): DISTINCT from completion (TXA-17).\n const availability = stringOrUndefined(txa.field(19).value);\n if (availability !== undefined) out.availabilityStatus = availability;\n\n return Object.freeze(out) as ClinicalDocument;\n}\n\n/**\n * Every TXA of an MDM message as a typed {@link ClinicalDocument}, with the OBX\n * narrative body grouped positionally under that TXA. Document order. Returns\n * `[]` when no TXA is present. NOT memoized: each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * TXA-17 completion status and TXA-19 availability status are surfaced as\n * **distinct** fields (`completionStatus` vs `availabilityStatus`) and are never\n * merged: a document can be available before it is authenticated, and reading a\n * preliminary document as final is the harm. See {@link ClinicalDocument}.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const doc of msg.documents()) {\n * console.log(doc.documentType, doc.completionStatus, doc.availabilityStatus);\n * for (const obx of doc.observations) console.log(obx.value); // narrative body\n * }\n * ```\n *\n * @internal\n */\nexport function documents(msg: Hl7Message): readonly ClinicalDocument[] {\n const noteIndex = groupNotes(msg); // Phase P: positional NTE grouping (by Segment ref)\n const out: ClinicalDocument[] = [];\n\n let currentTxa: Segment | undefined;\n let observations: Observation[] = [];\n\n const closeCurrent = (): void => {\n if (currentTxa !== undefined) out.push(finalizeDocument(currentTxa, observations));\n };\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"TXA\") {\n closeCurrent();\n currentTxa = seg;\n observations = [];\n continue;\n }\n if (currentTxa === undefined) continue; // OBX before any TXA: dropped (still on msg.observations()).\n if (seg.type === \"OBX\") {\n observations.push(buildObservation(seg, noteIndex.byParent.get(seg)));\n }\n }\n\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `identityEvents`: roadmap Phase K read-side helper that recognizes the ADT\n * patient-identity management trigger events and surfaces the MRG segment's\n * *prior* (non-surviving) identifiers alongside the PID/PV1 *surviving*\n * identifiers, each labelled by role.\n *\n * Spec traceability (HL7 v2 Ch. 3, Patient Administration):\n * - A18 \"The PID segment contains the surviving patient ID information. The\n * MRG segment contains the non-surviving information.\" The merge direction\n * is spec-explicit and constant: **MRG (prior) → PID (surviving)**: this\n * helper NEVER infers it from content and never reverses it.\n * - Merge family (§3.3.34–§3.3.42): A34/A35/A36 (v2.3-era merges), A39 merge\n * person, A40 merge patient identifier list, A41 merge account, A42 merge\n * visit; move family: A43 move patient info, A44 move account info; link\n * family: A24 link / A37 unlink (two PID groups, NO MRG); person add/update:\n * A28 / A31 (PID only, no MRG).\n * - MRG field map is **version-scoped** (v2.5.1 §3.4.10): MRG-1 prior patient\n * identifier list (CX, repeating), MRG-3 prior patient account number (CX),\n * MRG-4 prior patient ID (CX, backward-compat only: **withdrawn as of\n * v2.7** in favour of MRG-1), MRG-5 prior visit number (CX), MRG-7 prior\n * patient name (XPN). MRG-2 / MRG-6 (prior *alternate* patient/visit IDs,\n * also withdrawn v2.7) are deliberately not surfaced. On a v2.7+ message\n * (MSH-12) the withdrawn MRG-4 (and the symmetric withdrawn PID-2) are\n * NOT read as identity fields.\n *\n * Fail-safe: a merge/move event missing either side of the MRG→PID pair\n * surfaces what is present plus a `MERGE_MISSING_PRIOR_OR_SURVIVOR` warning on\n * the event: the MRG is **never dropped** (an orphaned MRG yields its own\n * event) and the direction is **never guessed**. The helper never throws.\n *\n * PHI note: identifiers and names are the *payload* of the typed view (by\n * design: the consumer needs them to apply the merge), but warning messages\n * carry only structural facts (event code + missing role), never a value.\n *\n * Applying the merge (re-pointing stored data to the survivor) is the\n * consumer's / integration engine's job: this helper only surfaces it.\n */\n\nimport type { Hl7Position } from \"../parser/types.js\";\nimport type { Hl7ParseWarning } from \"../parser/warnings.js\";\nimport { mergeMissingPriorOrSurvivor } from \"../parser/warnings.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CX } from \"../model/types/cx.js\";\nimport { parseCx } from \"../model/types/cx.js\";\nimport type { XPN } from \"../model/types/xpn.js\";\n\n/**\n * Classification of a recognized identity trigger event.\n *\n * - `merge`: A18 / A34 / A35 / A36 / A39 / A40 / A41 / A42 (MRG expected)\n * - `move`: A43 / A44 (MRG expected)\n * - `link` / `unlink`: A24 / A37 (two PID groups, no MRG)\n * - `add` / `update`: A28 / A31 (person add/update, no MRG)\n *\n * @example\n * ```ts\n * import type { IdentityEventKind } from \"@cosyte/hl7\";\n * const kind: IdentityEventKind = \"merge\";\n * ```\n */\nexport type IdentityEventKind = \"merge\" | \"move\" | \"link\" | \"unlink\" | \"add\" | \"update\";\n\n/**\n * Role of one party in an identity event. `surviving` / `subject` / `linked`\n * parties are ONLY ever sourced from PID (+ PV1); `prior` parties are ONLY\n * ever sourced from MRG: the role-labelling invariant Phase K exists for.\n *\n * @example\n * ```ts\n * import type { IdentityRole } from \"@cosyte/hl7\";\n * const role: IdentityRole = \"surviving\";\n * ```\n */\nexport type IdentityRole = \"surviving\" | \"prior\" | \"linked\" | \"subject\";\n\n/**\n * One party (one patient identity) in an identity event, labelled by role\n * with its source segment recorded as provenance. Absent fields are OMITTED\n * (exactOptionalPropertyTypes). All arrays and the object itself are frozen.\n *\n * Field sources by `sourceSegment`:\n * - `\"PID\"`: `identifiers` = PID-3 repetitions, `legacyPatientId` = PID-2\n * (pre-v2.7 only), `accountNumber` = PID-18, `visitNumber` = PV1-19 (from\n * the group's PV1, when present), `name` = PID-5 (first repetition).\n * - `\"MRG\"`: `identifiers` = MRG-1 repetitions, `legacyPatientId` = MRG-4\n * (pre-v2.7 only), `accountNumber` = MRG-3, `visitNumber` = MRG-5,\n * `name` = MRG-7 (first repetition).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const ev = parseHL7(raw).identityEvents()[0];\n * if (ev?.prior) {\n * console.log(ev.prior.role); // \"prior\"\n * console.log(ev.prior.sourceSegment); // \"MRG\"\n * for (const cx of ev.prior.identifiers) console.log(cx.idNumber);\n * }\n * ```\n */\nexport interface IdentityParty {\n /** Role of this party in the event: the safety-critical label. */\n readonly role: IdentityRole;\n /** Segment this party was sourced from: provenance for the role label. */\n readonly sourceSegment: \"PID\" | \"MRG\";\n /** Identifier list (PID-3 / MRG-1), every non-empty CX repetition. */\n readonly identifiers: readonly CX[];\n /**\n * Legacy single patient ID (PID-2 / MRG-4). Backward-compat only; withdrawn\n * as of HL7 v2.7: OMITTED (not read) when MSH-12 declares v2.7 or later.\n */\n readonly legacyPatientId?: CX;\n /** Patient account number (PID-18 / MRG-3). */\n readonly accountNumber?: CX;\n /** Visit number (PV1-19 for a PID party / MRG-5 for a prior party). */\n readonly visitNumber?: CX;\n /** Patient name (PID-5 / MRG-7, first repetition). */\n readonly name?: XPN;\n}\n\n/**\n * One recognized patient-identity event. For `merge` / `move` kinds the\n * `surviving` (PID/PV1-sourced) and `prior` (MRG-sourced) parties are also\n * exposed directly, with the spec-constant `direction: \"MRG_TO_PID\"`: the\n * prior identifiers are the ones being retired in favour of the surviving\n * ones, never the reverse (HL7 v2 Ch. 3, A18/A39/A40).\n *\n * `parties` is the complete role-labelled surface in document order: nothing\n * present in the message is dropped, including a nonconforming MRG in a\n * link/add message (surfaced as a `prior`-role party).\n *\n * `warnings` carries the event's own fail-safe warnings (currently\n * `MERGE_MISSING_PRIOR_OR_SURVIVOR`); they are scoped to the event and are\n * NOT appended to `Hl7Message.warnings` (a read-side helper never mutates\n * the message).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * for (const ev of parseHL7(raw).identityEvents()) {\n * if (ev.kind === \"merge\" && ev.prior && ev.surviving) {\n * // retire ev.prior.identifiers in favour of ev.surviving.identifiers\n * } else if (ev.warnings.length > 0) {\n * // incomplete pair: do NOT apply; route for review\n * }\n * }\n * ```\n */\nexport interface IdentityEvent {\n /** Trigger event code (MSH-9.2, falling back to EVN-1), e.g. `\"A40\"`. */\n readonly eventType: string;\n /** Classification of the trigger event. */\n readonly kind: IdentityEventKind;\n /** Every party in document order, role-labelled: the complete surface. */\n readonly parties: readonly IdentityParty[];\n /** The surviving party (merge/move): ONLY ever sourced from PID/PV1. */\n readonly surviving?: IdentityParty;\n /** The prior (non-surviving) party (merge/move): ONLY ever sourced from MRG. */\n readonly prior?: IdentityParty;\n /**\n * Spec-constant merge/move direction: the MRG (prior) identifiers merge\n * INTO the PID (surviving) identifiers. Present on `merge` / `move` events\n * only; never inferred from content.\n */\n readonly direction?: \"MRG_TO_PID\";\n /** Event-scoped fail-safe warnings (never PHI-bearing). */\n readonly warnings: readonly Hl7ParseWarning[];\n}\n\n/** Trigger-event → kind map for the recognized identity family. @internal */\nconst IDENTITY_TRIGGERS: ReadonlyMap<string, IdentityEventKind> = new Map<\n string,\n IdentityEventKind\n>([\n [\"A18\", \"merge\"], // merge patient information (backward-compat)\n [\"A34\", \"merge\"], // merge patient info - patient ID only\n [\"A35\", \"merge\"], // merge patient info - account number only\n [\"A36\", \"merge\"], // merge patient info - patient ID & account number\n [\"A39\", \"merge\"], // merge person - patient ID\n [\"A40\", \"merge\"], // merge patient - patient identifier list\n [\"A41\", \"merge\"], // merge account - patient account number\n [\"A42\", \"merge\"], // merge visit - visit number\n [\"A43\", \"move\"], // move patient information - patient identifier list\n [\"A44\", \"move\"], // move account information - patient account number\n [\"A24\", \"link\"], // link patient information\n [\"A37\", \"unlink\"], // unlink patient information\n [\"A28\", \"add\"], // add person information\n [\"A31\", \"update\"], // update person information\n]);\n\n/**\n * True when MSH-12 declares HL7 v2.7 or later: the era in which the\n * backward-compat single-ID fields (PID-2, MRG-2/4/6) are withdrawn. An\n * absent or unparseable version is treated as pre-v2.7 (the lenient default:\n * real-world ADT traffic is overwhelmingly v2.3–v2.5.1, where those fields\n * are still legal). @internal\n */\nfunction isV27OrLater(version: string | undefined): boolean {\n if (version === undefined) return false;\n const match = /^(\\d+)(?:\\.(\\d+))?/.exec(version.trim());\n if (match === null) return false;\n const major = Number(match[1]);\n const minor = match[2] === undefined ? 0 : Number(match[2]);\n return major > 2 || (major === 2 && minor >= 7);\n}\n\n/** Parse a single-CX field into a CX, or `undefined` when empty. @internal */\nfunction cxOrUndefined(seg: Segment, fieldIndex: number): CX | undefined {\n const cx = seg.field(fieldIndex).asCx();\n return Object.keys(cx).length > 0 ? cx : undefined;\n}\n\n/** Parse every non-empty CX repetition of a field. @internal */\nfunction cxList(seg: Segment, fieldIndex: number, msg: Hl7Message): readonly CX[] {\n const out: CX[] = [];\n for (const rep of seg.field(fieldIndex).repetitions) {\n const cx = parseCx(rep, msg.encodingCharacters);\n if (Object.keys(cx).length > 0) out.push(cx);\n }\n return Object.freeze(out);\n}\n\n/**\n * Build the PID/PV1-sourced party for a group. `role` distinguishes the\n * surviving (merge/move), linked (link/unlink), and subject (add/update)\n * uses of the same field map. @internal\n */\nfunction buildPidParty(\n pid: Segment,\n pv1: Segment | undefined,\n msg: Hl7Message,\n role: IdentityRole,\n legacyWithdrawn: boolean,\n): IdentityParty {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<IdentityParty> = {\n role,\n sourceSegment: \"PID\",\n identifiers: cxList(pid, 3, msg),\n };\n\n if (!legacyWithdrawn) {\n const legacy = cxOrUndefined(pid, 2);\n if (legacy !== undefined) out.legacyPatientId = legacy;\n }\n\n const account = cxOrUndefined(pid, 18);\n if (account !== undefined) out.accountNumber = account;\n\n if (pv1 !== undefined) {\n const visit = cxOrUndefined(pv1, 19);\n if (visit !== undefined) out.visitNumber = visit;\n }\n\n const name = pid.field(5).asXpn();\n if (Object.keys(name).length > 0) out.name = name;\n\n return Object.freeze(out) as IdentityParty;\n}\n\n/** Build the MRG-sourced `prior` party (version-scoped field map). @internal */\nfunction buildMrgParty(mrg: Segment, msg: Hl7Message, legacyWithdrawn: boolean): IdentityParty {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<IdentityParty> = {\n role: \"prior\",\n sourceSegment: \"MRG\",\n identifiers: cxList(mrg, 1, msg),\n };\n\n if (!legacyWithdrawn) {\n const legacy = cxOrUndefined(mrg, 4);\n if (legacy !== undefined) out.legacyPatientId = legacy;\n }\n\n const account = cxOrUndefined(mrg, 3);\n if (account !== undefined) out.accountNumber = account;\n\n const visit = cxOrUndefined(mrg, 5);\n if (visit !== undefined) out.visitNumber = visit;\n\n const name = mrg.field(7).asXpn();\n if (Object.keys(name).length > 0) out.name = name;\n\n return Object.freeze(out) as IdentityParty;\n}\n\n/** One PID-led (or orphan-MRG) segment group. @internal */\ninterface IdentityGroup {\n pid?: Segment;\n pv1?: Segment;\n mrg?: Segment;\n}\n\n/**\n * Split the message into PID-led groups (spec shape: `PID [PD1] MRG [PV1]`,\n * repeating). An MRG or PV1 attaches to the currently-open PID group; an MRG\n * with no open group (or arriving when the open group already holds one)\n * opens/continues an orphan group so it is NEVER dropped. @internal\n */\nfunction splitGroups(msg: Hl7Message): IdentityGroup[] {\n const groups: IdentityGroup[] = [];\n let current: IdentityGroup | undefined;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"PID\") {\n current = { pid: seg };\n groups.push(current);\n continue;\n }\n if (seg.type === \"MRG\") {\n if (current === undefined || current.mrg !== undefined) {\n current = { mrg: seg };\n groups.push(current);\n } else {\n current.mrg = seg;\n }\n continue;\n }\n if (seg.type === \"PV1\" && current !== undefined && current.pv1 === undefined) {\n current.pv1 = seg;\n }\n }\n return groups;\n}\n\n/** Does the CX carry a usable ID number (Ch. 2A: CX.1 is the identifier)? @internal */\nfunction hasUsableId(cx: CX | undefined): boolean {\n return cx !== undefined && cx.idNumber !== undefined && cx.idNumber !== \"\";\n}\n\n/**\n * Does a party carry at least one usable identity field? A CX with no ID\n * number (e.g. `^^^HOSP`, assigning authority only) is not a usable\n * identifier. Account and visit numbers count on BOTH sides: they are the\n * merge keys of A41/A42: but a name alone never does. @internal\n */\nfunction hasIdentityField(party: IdentityParty): boolean {\n return (\n party.identifiers.some(hasUsableId) ||\n hasUsableId(party.legacyPatientId) ||\n hasUsableId(party.accountNumber) ||\n hasUsableId(party.visitNumber)\n );\n}\n\n/** Position of a segment for warning context. @internal */\nfunction positionOf(seg: Segment | undefined): Hl7Position {\n return { segmentIndex: seg === undefined ? 0 : seg.absoluteIndex };\n}\n\n/** Finalize one merge/move event from one group. @internal */\nfunction buildMergeEvent(\n group: IdentityGroup,\n eventType: string,\n kind: \"merge\" | \"move\",\n msg: Hl7Message,\n legacyWithdrawn: boolean,\n): IdentityEvent {\n const parties: IdentityParty[] = [];\n const warnings: Hl7ParseWarning[] = [];\n let surviving: IdentityParty | undefined;\n let prior: IdentityParty | undefined;\n\n if (group.pid !== undefined) {\n surviving = buildPidParty(group.pid, group.pv1, msg, \"surviving\", legacyWithdrawn);\n parties.push(surviving);\n }\n if (group.mrg !== undefined) {\n prior = buildMrgParty(group.mrg, msg, legacyWithdrawn);\n parties.push(prior);\n }\n\n // Fail-safe (roadmap Phase K): surface what is present + a typed warning\n // when either role of the MRG→PID pair is missing OR carries no usable\n // identity field (e.g. a v2.7+ MRG whose only content was the gated\n // MRG-4: the consumer must not read an empty prior as \"nothing to\n // retire\"); never guess direction.\n if (prior === undefined || !hasIdentityField(prior)) {\n warnings.push(\n mergeMissingPriorOrSurvivor(positionOf(group.mrg ?? group.pid), eventType, \"prior\"),\n );\n }\n if (surviving === undefined || !hasIdentityField(surviving)) {\n warnings.push(\n mergeMissingPriorOrSurvivor(positionOf(group.pid ?? group.mrg), eventType, \"survivor\"),\n );\n }\n\n const out: IdentityEvent = {\n eventType,\n kind,\n parties: Object.freeze(parties),\n ...(surviving !== undefined ? { surviving } : {}),\n ...(prior !== undefined ? { prior } : {}),\n direction: \"MRG_TO_PID\",\n warnings: Object.freeze(warnings),\n };\n return Object.freeze(out);\n}\n\n/**\n * Recognize the message's identity trigger event and surface every party\n * labelled by role. Returns `[]` when the trigger (MSH-9.2, falling back to\n * EVN-1) is not in the identity family. Never throws; the result and every\n * nested view are deeply frozen. NOT memoized: each call re-walks the\n * message (mirrors `orders()`).\n *\n * Event shapes:\n * - `merge` / `move`: one event per PID-led group (repeating groups yield\n * one event each); `surviving` + `prior` + constant `direction`.\n * - `link` / `unlink`: ONE event; every PID group is a `linked` party.\n * - `add` / `update`: one event per PID group; the party role is `subject`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(rawA40);\n * const [ev] = msg.identityEvents();\n * ev?.kind; // \"merge\"\n * ev?.direction; // \"MRG_TO_PID\": spec-constant, never guessed\n * ev?.surviving?.sourceSegment; // \"PID\"\n * ev?.prior?.sourceSegment; // \"MRG\"\n * ```\n *\n * @internal\n */\nexport function identityEvents(msg: Hl7Message): readonly IdentityEvent[] {\n const trigger = msg.meta.triggerEvent ?? msg.get(\"EVN.1\");\n if (trigger === undefined || trigger === \"\") return Object.freeze([]);\n\n const eventType = trigger.toUpperCase();\n const kind = IDENTITY_TRIGGERS.get(eventType);\n if (kind === undefined) return Object.freeze([]);\n\n const legacyWithdrawn = isV27OrLater(msg.meta.version);\n const groups = splitGroups(msg);\n const events: IdentityEvent[] = [];\n\n if (kind === \"merge\" || kind === \"move\") {\n if (groups.length === 0) {\n // Trigger says merge/move but the message carries neither PID nor MRG:\n // one event recording both missing roles (position falls back to MSH).\n events.push(buildMergeEvent({}, eventType, kind, msg, legacyWithdrawn));\n } else {\n for (const group of groups) {\n events.push(buildMergeEvent(group, eventType, kind, msg, legacyWithdrawn));\n }\n }\n } else if (kind === \"link\" || kind === \"unlink\") {\n // A24/A37: the PID groups are peers being (un)linked: no survivor/prior\n // semantics. A nonconforming MRG is still surfaced (never dropped) as a\n // prior-role party in document order.\n const parties: IdentityParty[] = [];\n for (const group of groups) {\n if (group.pid !== undefined) {\n parties.push(buildPidParty(group.pid, group.pv1, msg, \"linked\", legacyWithdrawn));\n }\n if (group.mrg !== undefined) {\n parties.push(buildMrgParty(group.mrg, msg, legacyWithdrawn));\n }\n }\n const out: IdentityEvent = {\n eventType,\n kind,\n parties: Object.freeze(parties),\n warnings: Object.freeze([]),\n };\n events.push(Object.freeze(out));\n } else {\n // add / update (A28/A31): one subject party per PID group. A\n // nonconforming MRG is surfaced on the same event (never dropped).\n for (const group of groups) {\n const parties: IdentityParty[] = [];\n let subject: IdentityParty | undefined;\n if (group.pid !== undefined) {\n subject = buildPidParty(group.pid, group.pv1, msg, \"subject\", legacyWithdrawn);\n parties.push(subject);\n }\n if (group.mrg !== undefined) {\n parties.push(buildMrgParty(group.mrg, msg, legacyWithdrawn));\n }\n if (parties.length === 0) continue;\n const out: IdentityEvent = {\n eventType,\n kind,\n parties: Object.freeze(parties),\n warnings: Object.freeze([]),\n };\n events.push(Object.freeze(out));\n }\n }\n\n return Object.freeze(events);\n}\n","/**\n * `immunizations`: Phase E (P0 safety) implementation of the VXU^V04\n * immunization extractor. Walks the message in document order and projects each\n * RXA (Pharmacy/Treatment Administration) segment into a typed `Immunization`,\n * grouping the RXR (route/site) and OBX (e.g. VFC eligibility / funding) that\n * follow it positionally under that RXA: the same order-group state machine\n * `orders()` uses for ORC → OBR → OBX, specialized to the VXU group\n * `ORC`→`RXA`→`[RXR]`→`[{OBX}]` (one RXA per ORC; CDC v2.5.1 Immunization\n * Messaging IG).\n *\n * Field map (HL7 Ch. 4A: RXA; CDC v2.5.1 Immunization Messaging IG R1.5):\n * - RXA-3 date/time start of administration (TS)\n * - RXA-5 administered vaccine code (CWE: CVX, Table 0292) + any alternate\n * - RXA-6 administered dose amount (NM; `999` = IIS \"unknown\", surfaced as-is)\n * - RXA-7 administered dose units (CWE: UCUM)\n * - RXA-9 immunization information source (CWE: Table NIP001) → recordOrigin\n * - RXA-15 substance lot number (ST, first repetition)\n * - RXA-16 substance expiration date (TS, first repetition)\n * - RXA-17 substance manufacturer (CWE: MVX, Table 0227, first repetition)\n * - RXA-18 substance/treatment refusal reason (CWE, first repetition)\n * - RXA-20 completion status (ID: CP/RE/NA/PA)\n * - RXA-21 action code (ID: A/D/U), preserved verbatim\n * - RXR-1/2 route (Table 0162) / site (Table 0163), grouped (reuses MedicationRoute)\n * - ORC-1 order control of the preceding ORC, attached as orderControl\n *\n * Safety rules enforced here (Phase E):\n * - Never throws: malformed RXA surfaces as omitted keys (HELPERS-07).\n * - `actionCode` (RXA-21) is surfaced VERBATIM and never defaulted: a wrong\n * A/D/U corrupts an IIS add/delete/update dedup.\n * - `recordOrigin` is derived ONLY from the well-known NIP001 RXA-9.1 codes\n * (`00` administered; `01`-`08` historical) and OMITTED otherwise: the raw\n * RXA-9 claim is always preserved on `informationSource`. Never guessed.\n * - `doseAmount` is strict-`Number()` parsed via `Field.asNm()` → never `NaN`;\n * the `999` unknown-dose sentinel is surfaced as the number `999`, not coerced.\n * - Code-system provenance rides on the CWE fields\n * (`vaccineCode.nameOfCodingSystem`, `manufacturer.nameOfCodingSystem`,\n * `route.nameOfCodingSystem`); the helper reports the claim, never validates it.\n * - Output is frozen at the boundary (D-01).\n *\n * Grouping rules (parity with `orders()`):\n * - Each RXA opens a new `Immunization`. A preceding ORC contributes its ORC-1\n * as `orderControl`; an unmatched trailing ORC (after the last RXA) is dropped.\n * - RXR/OBX seen before any RXA are not attached to a phantom immunization\n * (pre-RXA OBX still surface via `msg.observations()`).\n * - `routes` and `observations` are ALWAYS present arrays (empty when none).\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\n\nimport { buildObservation } from \"./observations.js\";\nimport type {\n Immunization,\n ImmunizationRecordOrigin,\n MedicationRoute,\n Observation,\n} from \"./types.js\";\n\n/**\n * NIP001 RXA-9.1 codes that classify a dose as *historical* (sourced from\n * elsewhere, not administered by the reporting system). `00` is the sole\n * administered code; everything outside this set + `00` yields `undefined`\n * (fail-safe: never guessed). @internal\n */\nconst NIP001_HISTORICAL: ReadonlySet<string> = new Set([\n \"01\",\n \"02\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"07\",\n \"08\",\n]);\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer. @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Drop empty-composite leaks so optional CWE keys stay absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Classify RXA-9.1 against HL7 Table NIP001: `00` administered, `01`-`08`\n * historical, anything else (incl. absent) → `undefined` (fail-safe). @internal\n */\nfunction classifyOrigin(infoSource: CWE | undefined): ImmunizationRecordOrigin | undefined {\n const code = infoSource?.identifier;\n if (code === undefined) return undefined;\n if (code === \"00\") return \"administered\";\n if (NIP001_HISTORICAL.has(code)) return \"historical\";\n return undefined;\n}\n\n/** One RXR segment → a grouped `MedicationRoute` (Table 0162 route + Table 0163 site). @internal */\nfunction buildRoute(rxr: Segment): MedicationRoute {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationRoute> = {};\n\n const route = cweOrUndefined(rxr.field(1));\n if (route !== undefined) out.route = route;\n\n const site = cweOrUndefined(rxr.field(2));\n if (site !== undefined) out.site = site;\n\n return Object.freeze(out);\n}\n\n/** Build a frozen `Immunization` from one RXA + its attached ORC / routes / observations. @internal */\nfunction finalizeImmunization(\n rxa: Segment,\n attachedOrc: Segment | undefined,\n routes: readonly MedicationRoute[],\n observations: readonly Observation[],\n): Immunization {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Immunization> = {\n routes: Object.freeze(routes.slice()),\n observations: Object.freeze(observations.slice()),\n };\n\n // ORC-1 order control (when an ORC preceded this RXA).\n if (attachedOrc !== undefined) {\n const oc = stringOrUndefined(attachedOrc.field(1).value);\n if (oc !== undefined) out.orderControl = oc;\n }\n\n // RXA-3 administered date/time (fidelity TS, Phase N).\n const administered = rxa.field(3).asTs();\n if (administered.valid) out.administeredDateTime = administered;\n\n // RXA-5 vaccine code (CVX) with provenance + alternate coding.\n const vaccineCode = cweOrUndefined(rxa.field(5));\n if (vaccineCode !== undefined) out.vaccineCode = vaccineCode;\n\n // RXA-6 dose amount (strict-parsed; 999 unknown surfaced as-is).\n const doseAmount = rxa.field(6).asNm().value;\n if (doseAmount !== undefined) out.doseAmount = doseAmount;\n\n // RXA-7 dose units (UCUM) + the unitsAreUcum claim flag.\n const doseUnits = cweOrUndefined(rxa.field(7));\n if (doseUnits !== undefined) {\n out.doseUnits = doseUnits;\n out.doseUnitsAreUcum = doseUnits.nameOfCodingSystem === \"UCUM\";\n }\n\n // RXA-9 information source (NIP001) → preserve raw + derive recordOrigin.\n const informationSource = cweOrUndefined(rxa.field(9));\n if (informationSource !== undefined) out.informationSource = informationSource;\n const recordOrigin = classifyOrigin(informationSource);\n if (recordOrigin !== undefined) out.recordOrigin = recordOrigin;\n\n // RXA-15 lot number (first repetition).\n const lotNumber = stringOrUndefined(rxa.field(15).value);\n if (lotNumber !== undefined) out.lotNumber = lotNumber;\n\n // RXA-16 substance expiration date (first repetition; fidelity TS, Phase N).\n const expiration = rxa.field(16).asTs();\n if (expiration.valid) out.expirationDate = expiration;\n\n // RXA-17 manufacturer (MVX, first repetition).\n const manufacturer = cweOrUndefined(rxa.field(17));\n if (manufacturer !== undefined) out.manufacturer = manufacturer;\n\n // RXA-18 refusal reason (first repetition).\n const refusalReason = cweOrUndefined(rxa.field(18));\n if (refusalReason !== undefined) out.refusalReason = refusalReason;\n\n // RXA-20 completion status.\n const completionStatus = stringOrUndefined(rxa.field(20).value);\n if (completionStatus !== undefined) out.completionStatus = completionStatus;\n\n // RXA-21 action code: VERBATIM, never defaulted.\n const actionCode = stringOrUndefined(rxa.field(21).value);\n if (actionCode !== undefined) out.actionCode = actionCode;\n\n return Object.freeze(out) as Immunization;\n}\n\n/**\n * Every RXA of a VXU^V04 as a typed `Immunization`, with RXR (route/site) and\n * OBX children grouped positionally under the RXA and `orderControl` carried\n * from the preceding ORC of the VXU order group (Phase E, P0 safety). Document\n * order. Returns `[]` when no RXA is present. NOT memoized: each call re-walks\n * `msg.allSegments()`. Never throws (HELPERS-07).\n *\n * The vaccine code carries its own coding-system provenance\n * (`vaccineCode.nameOfCodingSystem`: `CVX`); a dual-coded RXA-5 surfaces its\n * alternate (CVX/NDC) on `vaccineCode.alternateIdentifier`/`…`. The action code\n * (RXA-21) is surfaced verbatim and `recordOrigin` (administered vs historical)\n * is derived only from the well-known NIP001 RXA-9.1 codes: see\n * {@link Immunization}.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const imm of msg.immunizations()) {\n * console.log(imm.vaccineCode?.identifier, imm.vaccineCode?.nameOfCodingSystem);\n * console.log(imm.doseAmount, imm.doseUnits?.identifier, imm.recordOrigin);\n * console.log(imm.actionCode, imm.completionStatus);\n * for (const r of imm.routes) console.log(r.route?.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function immunizations(msg: Hl7Message): readonly Immunization[] {\n const out: Immunization[] = [];\n\n let pendingOrc: Segment | undefined; // accumulates ORCs since the last RXA\n let currentRxa: Segment | undefined;\n let currentOrc: Segment | undefined; // ORC attached to the open RXA group\n let routes: MedicationRoute[] = [];\n let observations: Observation[] = [];\n\n const closeCurrent = (): void => {\n if (currentRxa !== undefined) {\n out.push(finalizeImmunization(currentRxa, currentOrc, routes, observations));\n }\n };\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"ORC\") {\n pendingOrc = seg;\n continue;\n }\n if (seg.type === \"RXA\") {\n // Close the previous group, then open a new one; promote pendingOrc.\n closeCurrent();\n currentRxa = seg;\n currentOrc = pendingOrc;\n pendingOrc = undefined;\n routes = [];\n observations = [];\n continue;\n }\n if (currentRxa === undefined) continue; // RXR/OBX before any RXA: dropped.\n if (seg.type === \"RXR\") {\n routes.push(buildRoute(seg));\n } else if (seg.type === \"OBX\") {\n observations.push(buildObservation(seg));\n }\n }\n\n // Finalize the trailing immunization group. A trailing ORC stays in\n // pendingOrc and is implicitly dropped (never promoted).\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `insurance`: Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * IN1 segment in document order, with positional IN2/IN3 presence flags\n * (`hasIn2` / `hasIn3`). Callers who need the full IN2/IN3 surface can drop\n * to `msg.segments(\"IN2\")[i]` / `msg.segments(\"IN3\")[i]`: the positional\n * index aligns with the IN1 index since we walk `msg.allSegments()` in\n * document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no IN1 present.\n * - D-06: NOT memoized: each call re-walks `msg.allSegments()`.\n * - Phase N: `effectiveDate` / `expirationDate` are the fidelity `TS`.\n * - D-22: never throws: empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"IN1\")`):\n * - `planId` ← IN1-2 (CWE)\n * - `companyId` ← IN1-3 (CX: first repetition)\n * - `companyName` ← IN1-4 (XON first component flattened to string)\n * - `groupNumber` ← IN1-8 (string)\n * - `effectiveDate` ← IN1-12 (TS/DT → fidelity `TS`, Phase N)\n * - `expirationDate` ← IN1-13 (TS/DT → fidelity `TS`, Phase N)\n * - `insuredName` ← IN1-16 (XPN)\n * - `policyNumber` ← IN1-36 (string)\n * - `hasIn2`/`hasIn3` ← positional IN2/IN3 presence booleans\n *\n * State-machine shape (single IN1 slot): open on IN1; attach any intervening\n * IN2/IN3 to flags; close and finalize when the next IN1 is seen or the walk\n * ends. IN2/IN3 appearing before any IN1 are ignored.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { Insurance } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/** Build a frozen `Insurance` from an IN1 segment + positional IN2/IN3 flags. @internal */\nfunction finalizeInsurance(in1: Segment, hasIn2: boolean, hasIn3: boolean): Insurance {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<Insurance> = { hasIn2, hasIn3 };\n\n const planId = in1.field(2).asCwe();\n if (Object.keys(planId).length > 0) entry.planId = planId;\n\n const companyId = in1.field(3).asCx();\n if (Object.keys(companyId).length > 0) entry.companyId = companyId;\n\n const companyName = stringOrUndefined(in1.field(4).value);\n if (companyName !== undefined) entry.companyName = companyName;\n\n const groupNumber = stringOrUndefined(in1.field(8).value);\n if (groupNumber !== undefined) entry.groupNumber = groupNumber;\n\n const effective = in1.field(12).asTs();\n if (effective.valid) entry.effectiveDate = effective;\n\n const expiration = in1.field(13).asTs();\n if (expiration.valid) entry.expirationDate = expiration;\n\n const insuredName = in1.field(16).asXpn();\n if (Object.keys(insuredName).length > 0) entry.insuredName = insuredName;\n\n const policyNumber = stringOrUndefined(in1.field(36).value);\n if (policyNumber !== undefined) entry.policyNumber = policyNumber;\n\n return Object.freeze(entry) as Insurance;\n}\n\n/**\n * Every IN1 as an `Insurance` entry in document order with positional\n * IN2/IN3 flags. `hasIn2` / `hasIn3` become `true` when an IN2 / IN3 appears\n * between this IN1 and the next IN1 (or end of message). D-05: returns `[]`\n * when no IN1 present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const ins of msg.insurance()) {\n * console.log(ins.companyName, ins.policyNumber, ins.hasIn2);\n * }\n * ```\n *\n * @internal\n */\nexport function insurance(msg: Hl7Message): readonly Insurance[] {\n const out: Insurance[] = [];\n let currentIn1: Segment | undefined;\n let currentHasIn2 = false;\n let currentHasIn3 = false;\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"IN1\") {\n // Close previous group.\n if (currentIn1 !== undefined) {\n out.push(finalizeInsurance(currentIn1, currentHasIn2, currentHasIn3));\n }\n currentIn1 = seg;\n currentHasIn2 = false;\n currentHasIn3 = false;\n continue;\n }\n if (seg.type === \"IN2\" && currentIn1 !== undefined) {\n currentHasIn2 = true;\n continue;\n }\n if (seg.type === \"IN3\" && currentIn1 !== undefined) {\n currentHasIn3 = true;\n continue;\n }\n }\n\n // Finalize the trailing IN1 group.\n if (currentIn1 !== undefined) {\n out.push(finalizeInsurance(currentIn1, currentHasIn2, currentHasIn3));\n }\n\n return Object.freeze(out);\n}\n","/**\n * `timing`: Phase M (order / medication timing) extraction. Projects the\n * TQ1 segment (HL7 v2.5+, Ch. 4 §4.5.4) and the **legacy embedded TQ** data\n * type in ORC-7 / RXE-1 (pre-v2.5, Ch. 2A §2.A.81: retained backward-compat\n * only, detail withdrawn as of v2.7) into the typed {@link OrderTiming}\n * surfaced on `Order.timings` / `Medication.timings`.\n *\n * Safety rules enforced here (Phase M §Fail-safe):\n * - The **repeat pattern** (TQ1-3 / legacy interval RI.1, HL7 Table 0335) is\n * surfaced **verbatim**: never normalized, never resolved to clock times,\n * never mapped to a different frequency. Reading `Q6H` as \"daily\" or losing\n * a `BID` silently changes the administered dose count (transcription-class\n * harm).\n * - A parametric `Q<integer><unit>` template's integer is **load-bearing** and\n * is never dropped: surfaced on `RepeatPattern.interval`.\n * - Total occurrences is read from **TQ1-14** (NM), *not* TQ1-11 (which is a\n * Text Instruction, TX).\n * - Never throws: a malformed timing surfaces as omitted keys (HELPERS-07).\n * - hl7 surfaces the timing *structure* only; it does NOT compute schedules,\n * resolve \"institution-specified times\", or interpret sig.\n *\n * Field maps:\n * TQ1 segment: TQ1-2 quantity (CQ), TQ1-3 repeat pattern (RPT.1, Table 0335),\n * TQ1-4 explicit time, TQ1-6 service duration, TQ1-7 start (DTM), TQ1-8 end\n * (DTM), TQ1-9 priority (CWE), TQ1-14 total occurrences (NM).\n * Legacy embedded TQ (one field): TQ.1 quantity (CQ), TQ.2 interval (RI.1\n * repeat pattern / RI.2 explicit time), TQ.3 duration, TQ.4 start (TS), TQ.5\n * end (TS), TQ.6 priority (ID), TQ.12 total occurrences (NM).\n */\n\nimport { parseDtm } from \"../parser/dates.js\";\nimport type { EncodingCharacters, RawComponent, RawRepetition } from \"../parser/types.js\";\nimport type { Field } from \"../model/field.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport { parseCwe, type CWE } from \"../model/types/cwe.js\";\nimport { readSubcomponent } from \"../model/types/_shared.js\";\nimport type { OrderTiming, RepeatPattern, TimingQuantity } from \"./types.js\";\n\n/**\n * Table-0335 fixed mnemonics scheduled at institution-specified times: a\n * conservative, provenance-only set (HL7 v2.5.1 Ch. 4 Table 0335). Membership\n * only sets `RepeatPattern.kind = \"named\"`; it never changes the verbatim\n * `code` or resolves a schedule. Compared case-insensitively. @internal\n */\nconst NAMED_PATTERNS: ReadonlySet<string> = new Set<string>([\n \"BID\",\n \"TID\",\n \"QID\",\n \"QOD\",\n \"QHS\",\n \"QAM\",\n \"QPM\",\n \"QSHIFT\",\n \"QD\",\n \"PRN\",\n \"AC\",\n \"PC\",\n \"HS\",\n \"C\",\n]);\n\n/** `Q<integer><unit>` parametric template (seconds/minutes/hours/days/weeks/lunar-months). @internal */\nconst PARAMETRIC = /^Q(\\d+)([SMHDWL])$/iu;\n/** `Q<integer>J<day-of-week>` parametric template (every N weeks on a weekday). @internal */\nconst PARAMETRIC_DOW = /^Q(\\d+)(J)(\\d)$/iu;\n\n/**\n * Classify a Table-0335 repeat-pattern `code` for **provenance only**: the\n * verbatim `code` is always authoritative and is never modified. A parametric\n * `Q<n><unit>` template surfaces its load-bearing integer + unit on `interval`;\n * a recognized mnemonic is `\"named\"`; anything else is `\"unknown\"` (surfaced\n * verbatim, never mapped). Never throws.\n *\n * @example\n * ```ts\n * classifyRepeatPattern(\"Q6H\"); // { code: \"Q6H\", kind: \"parametric\", interval: { count: 6, unit: \"H\" } }\n * classifyRepeatPattern(\"BID\"); // { code: \"BID\", kind: \"named\" }\n * classifyRepeatPattern(\"Q4-6H\"); // { code: \"Q4-6H\", kind: \"unknown\" }: verbatim, never mapped\n * ```\n * @internal\n */\nexport function classifyRepeatPattern(code: string): RepeatPattern {\n const parametric = PARAMETRIC.exec(code);\n if (parametric !== null) {\n const count = Number.parseInt(parametric[1] ?? \"\", 10);\n const unit = (parametric[2] ?? \"\").toUpperCase();\n if (!Number.isNaN(count)) {\n return { code, kind: \"parametric\", interval: { count, unit } };\n }\n }\n const dow = PARAMETRIC_DOW.exec(code);\n if (dow !== null) {\n const count = Number.parseInt(dow[1] ?? \"\", 10);\n if (!Number.isNaN(count)) {\n return { code, kind: \"parametric\", interval: { count, unit: \"J\" } };\n }\n }\n if (NAMED_PATTERNS.has(code.toUpperCase())) {\n return { code, kind: \"named\" };\n }\n return { code, kind: \"unknown\" };\n}\n\n/** Strict-`Number` parse of a raw HL7 numeric: `undefined` (never `NaN`) on empty/garbage. @internal */\nfunction strictNumber(raw: string | undefined): number | undefined {\n if (raw === undefined || raw === \"\") return undefined;\n const n = Number(raw);\n return Number.isNaN(n) ? undefined : n;\n}\n\n/**\n * Build a `CWE` from the subcomponents of one raw component: used to surface\n * the units (a CE) nested inside a CQ (e.g. TQ1-2's `quantity^units&&`). Each\n * subcomponent maps to one CWE component. Returns `undefined` when the\n * component is absent or carries no content. @internal\n */\nfunction cweFromSubcomponents(\n component: RawComponent | undefined,\n enc: EncodingCharacters,\n): CWE | undefined {\n if (component === undefined || component.subcomponents.length === 0) return undefined;\n const rep: RawRepetition = {\n components: component.subcomponents.map((sub) => ({ subcomponents: [sub] })),\n };\n const cwe = parseCwe(rep, enc);\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/** Build a `TimingQuantity` from a CQ-shaped field (TQ1-2 / legacy TQ.1). @internal */\nfunction buildQuantity(\n quantityRaw: string | undefined,\n unitsComponent: RawComponent | undefined,\n enc: EncodingCharacters,\n): TimingQuantity | undefined {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<TimingQuantity> = {};\n\n const value = strictNumber(quantityRaw);\n if (value !== undefined) out.value = value;\n\n const units = cweFromSubcomponents(unitsComponent, enc);\n if (units !== undefined) out.units = units;\n\n return Object.keys(out).length === 0 ? undefined : Object.freeze(out);\n}\n\n/** First repetition's component at `index` (or `undefined`). @internal */\nfunction componentAt(field: Field, index: number): RawComponent | undefined {\n return field.repetitions[0]?.components[index];\n}\n\n/** Read `field`'s first-repetition component `compIdx`, subcomponent `subIdx`, unescaped. @internal */\nfunction fieldSub(field: Field, compIdx: number, subIdx: number): string | undefined {\n return readSubcomponent(componentAt(field, compIdx), subIdx, field.enc);\n}\n\n/**\n * Build one {@link OrderTiming} from a TQ1 segment (v2.5+). Reads TQ1-2, -3, -4,\n * -6, -7, -8, -9, -14. Never throws.\n *\n * @example\n * ```ts\n * const tq1 = msg.segments(\"TQ1\")[0];\n * if (tq1 !== undefined) console.log(buildTq1Timing(tq1).repeatPattern?.code);\n * ```\n * @internal\n */\nexport function buildTq1Timing(tq1: Segment): OrderTiming {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<OrderTiming> = { source: \"TQ1\" };\n\n // TQ1-2 quantity (CQ): CQ.1 = component 0 subcomponent 0, CQ.2 units = component 1.\n const q2 = tq1.field(2);\n const quantity = buildQuantity(fieldSub(q2, 0, 0), componentAt(q2, 1), tq1.enc);\n if (quantity !== undefined) out.quantity = quantity;\n\n // TQ1-3 repeat pattern (RPT.1): verbatim, classified for provenance only.\n const rpt = fieldSub(tq1.field(3), 0, 0);\n if (rpt !== undefined) out.repeatPattern = Object.freeze(classifyRepeatPattern(rpt));\n\n // TQ1-4 explicit time: verbatim (first repetition/value).\n const explicit = fieldSub(tq1.field(4), 0, 0);\n if (explicit !== undefined) out.explicitTime = explicit;\n\n // TQ1-6 service duration: verbatim.\n const duration = fieldSub(tq1.field(6), 0, 0);\n if (duration !== undefined) out.serviceDuration = duration;\n\n // TQ1-7 / TQ1-8 start / end (DTM): Phase N fidelity TS.\n const start = tq1.field(7).asTs();\n if (start.raw !== \"\") out.startDateTime = start;\n const end = tq1.field(8).asTs();\n if (end.raw !== \"\") out.endDateTime = end;\n\n // TQ1-9 priority (CWE).\n const priority = tq1.field(9).asCwe();\n if (Object.keys(priority).length > 0) out.priority = priority;\n\n // TQ1-14 total occurrences (NM): NOT TQ1-11.\n const total = strictNumber(fieldSub(tq1.field(14), 0, 0));\n if (total !== undefined) out.totalOccurrences = total;\n\n return Object.freeze(out) as OrderTiming;\n}\n\n/**\n * Build one {@link OrderTiming} from a legacy embedded TQ data type carried in a\n * single field (ORC-7 for orders, RXE-1 for encoded medications; pre-v2.5).\n * Reads TQ.1 (quantity), TQ.2 (interval → repeat pattern / explicit time),\n * TQ.3 (duration), TQ.4/TQ.5 (start / end TS), TQ.6 (priority), TQ.12 (total\n * occurrences). Returns `undefined` when the field carries no timing content so\n * the caller does not surface an empty legacy timing. Never throws.\n *\n * @example\n * ```ts\n * const orc = msg.segments(\"ORC\")[0];\n * if (orc !== undefined) console.log(buildLegacyTiming(orc.field(7))?.repeatPattern?.code);\n * ```\n * @internal\n */\nexport function buildLegacyTiming(field: Field): OrderTiming | undefined {\n const rep = field.repetitions[0];\n if (rep === undefined) return undefined;\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<OrderTiming> = { source: \"legacy\" };\n\n // TQ.1 Quantity (CQ): CQ.1 = component 0 subcomponent 0, CQ.2 units = subcomponent 1.\n const quantity = buildQuantity(fieldSub(field, 0, 0), undefined, field.enc);\n if (quantity !== undefined) {\n // Legacy CQ.2 units collapse to a single subcomponent: surface as { identifier }.\n const unitsId = fieldSub(field, 0, 1);\n out.quantity =\n unitsId !== undefined\n ? Object.freeze({ ...quantity, units: { identifier: unitsId } })\n : quantity;\n }\n\n // TQ.2 Interval (RI): RI.1 = repeat pattern, RI.2 = explicit time.\n const rpt = fieldSub(field, 1, 0);\n if (rpt !== undefined) out.repeatPattern = Object.freeze(classifyRepeatPattern(rpt));\n const explicit = fieldSub(field, 1, 1);\n if (explicit !== undefined) out.explicitTime = explicit;\n\n // TQ.3 Duration.\n const duration = fieldSub(field, 2, 0);\n if (duration !== undefined) out.serviceDuration = duration;\n\n // TQ.4 / TQ.5 Start / End (TS): Phase N fidelity parse of the embedded value.\n const startRaw = fieldSub(field, 3, 0);\n if (startRaw !== undefined) out.startDateTime = parseDtm(startRaw);\n const endRaw = fieldSub(field, 4, 0);\n if (endRaw !== undefined) out.endDateTime = parseDtm(endRaw);\n\n // TQ.6 Priority (ID): surfaced as a CWE { identifier } for shape parity with TQ1-9.\n const priorityId = fieldSub(field, 5, 0);\n if (priorityId !== undefined) out.priority = Object.freeze({ identifier: priorityId });\n\n // TQ.12 Total occurrences (NM).\n const total = strictNumber(fieldSub(field, 11, 0));\n if (total !== undefined) out.totalOccurrences = total;\n\n // A source-only object (nothing else populated) is not a real timing.\n if (Object.keys(out).length === 1) return undefined;\n\n return Object.freeze(out) as OrderTiming;\n}\n","/**\n * `medications`: Phase D (P0 safety) implementation of the pharmacy/treatment\n * extractor. Walks the message in document order and projects each RXO / RXE /\n * RXD / RXA segment into a typed `Medication`, grouping the RXR (route) and\n * RXC (component) segments that follow it positionally under that parent,\n * the same state-machine pattern `orders()` uses for OBR → OBX (D-12).\n *\n * Field map (HL7 Ch. 4A: Pharmacy/Treatment):\n * - RXO (order): give RXO-1, amount RXO-2/3, units RXO-4, form RXO-5\n * - RXE (encoded): give RXE-2, amount RXE-3/4, units RXE-5,\n * strength RXE-25 + units RXE-26\n * - RXD (dispense): give RXD-2, amount RXD-4 (single), units RXD-5\n * - RXA (administration): give RXA-5, amount RXA-6 (single), units RXA-7\n * - RXR (route, grouped): route RXR-1 (Table 0162), site RXR-2 (Table 0163)\n * - RXC (component, grouped): type RXC-1, code RXC-2, amount RXC-3, units RXC-4\n *\n * Safety rules enforced here (Phase D §4):\n * - Never throws: malformed RX* surface as omitted keys (matches the helper\n * layer contract; HELPERS-07).\n * - `amount` (how much) and `strength` (concentration) are surfaced as\n * SEPARATE fields and are NEVER reconciled: including against any strength\n * a coded drug (e.g. an NDC) implies. A disagreement is preserved.\n * - Numeric fields are strict-`Number()` parsed via `Field.asNm()` → never\n * `NaN`; absent/blank → key omitted.\n * - Code-system provenance rides on the give-code CWE\n * (`giveCode.nameOfCodingSystem`); the helper reports the claim, never\n * validates it.\n * - Output is frozen at the boundary (Order/Observation parity, D-01).\n *\n * Grouping rules:\n * - Each RXO/RXE/RXD/RXA opens a new `Medication`. RXR/RXC seen before any\n * RX* parent are dropped (parity with `orders()` dropping a leading OBX /\n * trailing ORC): they are not attached to a phantom medication.\n * - `routes` and `components` are ALWAYS present arrays (empty when none).\n */\n\nimport type { Field } from \"../model/field.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport { buildLegacyTiming, buildTq1Timing } from \"./timing.js\";\nimport type {\n Medication,\n MedicationAmount,\n MedicationComponent,\n MedicationContext,\n MedicationRoute,\n MedicationStrength,\n OrderTiming,\n} from \"./types.js\";\n\n/** The four RX* parent segment types that each open a `Medication`. @internal */\nconst PARENT_CONTEXT: Readonly<Record<string, MedicationContext>> = {\n RXO: \"order\",\n RXE: \"encoded\",\n RXD: \"dispense\",\n RXA: \"administration\",\n};\n\n/** Drop empty-composite leaks so optional CWE keys stay absent when the field was blank. @internal */\nfunction cweOrUndefined(field: Field): CWE | undefined {\n const cwe = field.asCwe();\n return Object.keys(cwe).length === 0 ? undefined : cwe;\n}\n\n/**\n * Build the give/dispense/administered amount from a (min, max, units) field\n * triple. Returns `undefined` when none of the three carries content so the\n * optional `amount` key stays absent. `max` is `undefined` for single-amount\n * (dispense/administration) callers. @internal\n */\nfunction buildAmount(\n minField: Field,\n maxField: Field | undefined,\n unitsField: Field,\n): MedicationAmount | undefined {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationAmount> = {};\n\n const minimum = minField.asNm().value;\n if (minimum !== undefined) out.minimum = minimum;\n\n if (maxField !== undefined) {\n const maximum = maxField.asNm().value;\n if (maximum !== undefined) out.maximum = maximum;\n }\n\n const units = cweOrUndefined(unitsField);\n if (units !== undefined) out.units = units;\n\n return Object.keys(out).length === 0 ? undefined : Object.freeze(out);\n}\n\n/** RXE-25/26 give strength: surfaced verbatim, never reconciled with the give code. @internal */\nfunction buildStrength(rxe: Segment): MedicationStrength | undefined {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationStrength> = {};\n\n const value = rxe.field(25).asNm().value;\n if (value !== undefined) out.value = value;\n\n const units = cweOrUndefined(rxe.field(26));\n if (units !== undefined) out.units = units;\n\n return Object.keys(out).length === 0 ? undefined : Object.freeze(out);\n}\n\n/** Build the give-code + amount + (strength/form) for one RX* parent by context. @internal */\nfunction buildFromParent(parent: Segment, context: MedicationContext): Medication {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Medication> = { context, routes: [], components: [] };\n\n let giveCode: CWE | undefined;\n let amount: MedicationAmount | undefined;\n\n switch (context) {\n case \"order\": {\n giveCode = cweOrUndefined(parent.field(1));\n amount = buildAmount(parent.field(2), parent.field(3), parent.field(4));\n const form = cweOrUndefined(parent.field(5));\n if (form !== undefined) out.dosageForm = form;\n break;\n }\n case \"encoded\": {\n giveCode = cweOrUndefined(parent.field(2));\n amount = buildAmount(parent.field(3), parent.field(4), parent.field(5));\n const strength = buildStrength(parent);\n if (strength !== undefined) out.strength = strength;\n break;\n }\n case \"dispense\": {\n giveCode = cweOrUndefined(parent.field(2));\n // RXD-4 is a SINGLE actual-dispense amount: no max field.\n amount = buildAmount(parent.field(4), undefined, parent.field(5));\n break;\n }\n case \"administration\": {\n giveCode = cweOrUndefined(parent.field(5));\n // RXA-6 is a SINGLE administered amount: no max field.\n amount = buildAmount(parent.field(6), undefined, parent.field(7));\n break;\n }\n }\n\n if (giveCode !== undefined) out.giveCode = giveCode;\n if (amount !== undefined) out.amount = amount;\n\n return out as Medication;\n}\n\n/** One RXR segment → a grouped `MedicationRoute` (Table 0162 route + Table 0163 site). @internal */\nfunction buildRoute(rxr: Segment): MedicationRoute {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationRoute> = {};\n\n const route = cweOrUndefined(rxr.field(1));\n if (route !== undefined) out.route = route;\n\n const site = cweOrUndefined(rxr.field(2));\n if (site !== undefined) out.site = site;\n\n return Object.freeze(out);\n}\n\n/** One RXC segment → a grouped `MedicationComponent` (structural: not pharmacologically resolved). @internal */\nfunction buildComponent(rxc: Segment): MedicationComponent {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<MedicationComponent> = {};\n\n const type = rxc.field(1).value;\n if (type !== \"\") out.type = type;\n\n const code = cweOrUndefined(rxc.field(2));\n if (code !== undefined) out.code = code;\n\n const amount = rxc.field(3).asNm().value;\n if (amount !== undefined) out.amount = amount;\n\n const units = cweOrUndefined(rxc.field(4));\n if (units !== undefined) out.units = units;\n\n return Object.freeze(out);\n}\n\n/**\n * Build the frozen `timings` list for a medication group (Phase M). Every TQ1\n * segment grouped under the RX* parent yields one `OrderTiming`\n * (`source: \"TQ1\"`). When the group carries no TQ1, the **legacy embedded TQ**\n * is read from RXE-1 (an encoded RXE order) or, failing that, from the preceding\n * ORC's ORC-7 (any pharmacy order: e.g. a pre-v2.5 RXO whose timing lives in\n * ORC-7 with no OBR to surface it via `orders()`). Reading the legacy source\n * only when no TQ1 is present means the same timing is never double-counted; the\n * ORC-7 fallback means a legacy-only timing is never dropped. `orc` is the ORC\n * that opened this group (already consumed for only the first RX* of the group,\n * so an `ORC RXO RXE` group never double-surfaces the ORC-7 timing).\n * @internal\n */\nfunction buildMedTimings(\n tq1Segs: readonly Segment[],\n parent: Segment,\n context: MedicationContext,\n orc: Segment | undefined,\n): readonly OrderTiming[] {\n if (tq1Segs.length > 0) {\n return Object.freeze(tq1Segs.map((seg) => buildTq1Timing(seg)));\n }\n if (context === \"encoded\") {\n const legacy = buildLegacyTiming(parent.field(1)); // RXE-1 Quantity/Timing\n if (legacy !== undefined) return Object.freeze([legacy]);\n }\n if (orc !== undefined) {\n const legacy = buildLegacyTiming(orc.field(7)); // ORC-7 Quantity/Timing\n if (legacy !== undefined) return Object.freeze([legacy]);\n }\n return Object.freeze([]);\n}\n\n/** Freeze a Medication and its grouped child arrays at the boundary (D-01). @internal */\nfunction finalize(\n med: Medication,\n parent: Segment,\n orc: Segment | undefined,\n routes: readonly MedicationRoute[],\n components: readonly MedicationComponent[],\n tq1Segs: readonly Segment[],\n): Medication {\n const out = med as { -readonly [K in keyof Medication]: Medication[K] };\n out.routes = Object.freeze(routes.slice());\n out.components = Object.freeze(components.slice());\n out.timings = buildMedTimings(tq1Segs, parent, med.context, orc);\n return Object.freeze(out);\n}\n\n/**\n * Every RXO/RXE/RXD/RXA as a typed `Medication`, with RXR (route) and RXC\n * (component) segments grouped positionally under the preceding RX* parent\n * (Phase D, P0 safety). Document order. Returns `[]` when no RX* parent is\n * present. NOT memoized: each call re-walks `msg.allSegments()`. Never throws\n * (HELPERS-07).\n *\n * The give code carries its own coding-system provenance\n * (`giveCode.nameOfCodingSystem`). The give *amount* and the give *strength*\n * are surfaced as separate fields and are never reconciled: a strength a\n * coded drug implies is never used to validate or overwrite the explicit\n * RXE-25/26 strength (Phase D §4).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const med of msg.medications()) {\n * console.log(med.context, med.giveCode?.identifier, med.giveCode?.nameOfCodingSystem);\n * console.log(med.amount?.minimum, med.amount?.units?.identifier);\n * for (const r of med.routes) console.log(r.route?.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function medications(msg: Hl7Message): readonly Medication[] {\n const out: Medication[] = [];\n\n let current: Medication | undefined;\n let currentParent: Segment | undefined;\n let currentOrc: Segment | undefined; // ORC that opened the current group (ORC-7 legacy source)\n let pendingOrc: Segment | undefined; // ORC seen before the next RX* parent opens\n let routes: MedicationRoute[] = [];\n let components: MedicationComponent[] = [];\n let pendingTq1: Segment[] = []; // TQ1 seen before the next RX* parent opens (Phase M)\n let currentTq1: Segment[] = []; // TQ1 grouped under the open RX* parent (Phase M)\n let awaitingParent = false; // an ORC has begun a group still awaiting its RX* parent (Phase M)\n\n const closeCurrent = (): void => {\n if (current !== undefined && currentParent !== undefined) {\n out.push(finalize(current, currentParent, currentOrc, routes, components, currentTq1));\n }\n };\n\n for (const seg of msg.allSegments()) {\n const context = PARENT_CONTEXT[seg.type];\n if (context !== undefined) {\n // Close the previous medication group, then open a new one: promoting\n // any TQ1 seen since the last parent (the order group places TQ1 ahead\n // of the RXE it modifies). The preceding ORC (its ORC-7 legacy timing) is\n // consumed by only this first RX*: `pendingOrc` is cleared so a sibling\n // RX* in the same ORC group never double-surfaces the ORC-7 timing.\n closeCurrent();\n current = buildFromParent(seg, context);\n currentParent = seg;\n currentOrc = pendingOrc;\n pendingOrc = undefined;\n routes = [];\n components = [];\n currentTq1 = pendingTq1;\n pendingTq1 = [];\n awaitingParent = false;\n continue;\n }\n if (seg.type === \"ORC\") {\n // A new ORC starts a new order group: any following TQ1 (before that\n // group's RX* parent) belongs to the NEXT medication, and its ORC-7\n // carries the legacy timing for that group.\n pendingOrc = seg;\n awaitingParent = true;\n continue;\n }\n if (seg.type === \"TQ1\") {\n // A TQ1 attaches to the open medication only when no newer ORC has begun a\n // group; otherwise it modifies the next RX* parent.\n if (current !== undefined && !awaitingParent) currentTq1.push(seg);\n else pendingTq1.push(seg);\n continue;\n }\n if (current === undefined) continue; // RXR/RXC before any RX* parent: dropped.\n if (seg.type === \"RXR\") {\n routes.push(buildRoute(seg));\n } else if (seg.type === \"RXC\") {\n components.push(buildComponent(seg));\n }\n }\n\n // Finalize the trailing medication group.\n closeCurrent();\n\n return Object.freeze(out);\n}\n","/**\n * `buildMeta`: compose MSH-derived message metadata into the frozen `Meta`\n * view exposed by `Hl7Message.meta` (HELPERS-01). Implementation composes on\n * the Phase 3 public surface (`msg.get`, `msg.segments(\"MSH\")[0].field(N)`),\n * never walks `rawSegments` directly (CONTEXT.md §domain \"Compose, don't\n * reach through\").\n *\n * D-01 freeze at boundary. D-02 memoization is handled by the caller\n * (`Hl7Message.meta` getter). D-03 Meta is always defined: MSH absence\n * throws `NO_MSH_SEGMENT` at parse time, so the MSH guard here is purely for\n * TS narrowing. Phase N: `timestamp` is the fidelity `TS` (precision +\n * timezone preserved), never an eager UTC-assuming `Date`. D-21 silent. D-22\n * never throws. D-23 string fields are decoded (unescaped once at parse) by routing through\n * `msg.get()` / `field.value`.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport { parseDtmCascade } from \"../parser/dates.js\";\n\nimport type { Meta } from \"./types.js\";\n\n/**\n * Build the immutable `Meta` view from a parsed message's MSH segment. The\n * result is deeply frozen (D-01) and consumed through the memoized\n * `Hl7Message.meta` getter (D-02). Absent fields are OMITTED from the\n * resulting object (exactOptionalPropertyTypes semantics): never set to\n * `undefined`.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.meta.type); // \"ADT^A01^ADT_A01\"\n * console.log(msg.meta.controlId); // \"MSG001\"\n * console.log(msg.meta.timestamp?.raw); // fidelity TS (Phase N)\n * ```\n *\n * @internal\n */\nexport function buildMeta(msg: Hl7Message): Meta {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Meta> = {};\n\n // D-03: MSH is always present on a parsed Hl7Message. The optional-chain\n // here is purely for TS narrowing under noUncheckedIndexedAccess.\n const msh = msg.segments(\"MSH\")[0];\n\n // ─── MSH-9 message type (full string + per-component shortcuts) ────────\n // msg.get(\"MSH.9\") returns the first subcomponent of the first component,\n // i.e. MSH-9.1. To emit the FULL typed string (e.g. \"ADT^A01^ADT_A01\") we\n // reconstruct it from each component's first subcomponent, joined on '^'\n // and trimmed of trailing empties so \"ADT^A01\" doesn't render as\n // \"ADT^A01^\".\n if (msh !== undefined) {\n const typeField = msh.field(9);\n const firstRep = typeField.repetitions[0];\n if (firstRep !== undefined) {\n const parts: string[] = [];\n for (let i = 0; i < firstRep.components.length; i++) {\n const sub = msg.get(`MSH.9.${String(i + 1)}`);\n parts.push(sub ?? \"\");\n }\n while (parts.length > 0 && parts[parts.length - 1] === \"\") parts.pop();\n const fullType = parts.join(\"^\");\n if (fullType !== \"\") out.type = fullType;\n }\n }\n const messageCode = msg.get(\"MSH.9.1\");\n if (messageCode !== undefined && messageCode !== \"\") out.messageCode = messageCode;\n const triggerEvent = msg.get(\"MSH.9.2\");\n if (triggerEvent !== undefined && triggerEvent !== \"\") out.triggerEvent = triggerEvent;\n const messageStructure = msg.get(\"MSH.9.3\");\n if (messageStructure !== undefined && messageStructure !== \"\") {\n out.messageStructure = messageStructure;\n }\n\n // ─── MSH-10 message control ID ────────────────────────────────────────\n const controlId = msg.get(\"MSH.10\");\n if (controlId !== undefined && controlId !== \"\") out.controlId = controlId;\n\n // ─── MSH-7 timestamp (Phase N fidelity TS + D-21 merged dateFormats) ───\n // Call parseDtmCascade DIRECTLY (not via .asTs() which hard-codes the strict\n // HL7 shape) so Phase 6 D-21 `options.dateFormats ++ profile.dateFormats` is\n // honoured for MSH-7. .asTs() stays strict for composite callers (Phase 3\n // D-10 \"zero duplicate date logic\"); meta.ts is the non-composite caller that\n // benefits from the lenient cascade. Phase N: `timestamp` is the fidelity\n // TS (precision + timezone preserved), never an eager UTC-assuming Date.\n if (msh !== undefined) {\n const tsField = msh.field(7);\n const tsRaw = tsField.value;\n if (tsRaw !== \"\") {\n const parsed = parseDtmCascade(tsRaw, { userFormats: msg.dateFormats });\n // `parseDtmCascade` already returns a frozen `DtmParts`.\n if (parsed.valid) out.timestamp = parsed;\n }\n }\n\n // ─── MSH-12 version ───────────────────────────────────────────────────\n const version = msg.get(\"MSH.12\");\n if (version !== undefined && version !== \"\") out.version = version;\n\n // ─── MSH-3/-4/-5/-6 apps + facilities (first component = namespace id) ─\n const sendingApp = msg.get(\"MSH.3.1\");\n if (sendingApp !== undefined && sendingApp !== \"\") out.sendingApp = sendingApp;\n const sendingFacility = msg.get(\"MSH.4.1\");\n if (sendingFacility !== undefined && sendingFacility !== \"\") {\n out.sendingFacility = sendingFacility;\n }\n const receivingApp = msg.get(\"MSH.5.1\");\n if (receivingApp !== undefined && receivingApp !== \"\") out.receivingApp = receivingApp;\n const receivingFacility = msg.get(\"MSH.6.1\");\n if (receivingFacility !== undefined && receivingFacility !== \"\") {\n out.receivingFacility = receivingFacility;\n }\n\n // ─── MSH-11 processing ID (first component) ───────────────────────────\n const processingId = msg.get(\"MSH.11.1\");\n if (processingId !== undefined && processingId !== \"\") out.processingId = processingId;\n\n // D-01: freeze at boundary: callers see an immutable view.\n return Object.freeze(out);\n}\n","/**\n * `nextOfKin`: Phase 4 Plan 04 implementation of HELPERS-06. One entry per\n * NK1 segment in document order.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each entry and to the outer array.\n * - D-05: returns `[]` when no NK1 present.\n * - D-06: NOT memoized: each call re-walks `msg.segments(\"NK1\")`.\n * - D-22: never throws: empty / malformed fields surface as omitted keys.\n *\n * Lean v1 field set (callers wanting more can drop to `msg.segments(\"NK1\")`):\n * - `name` ← NK1-2 (XPN)\n * - `relationship` ← NK1-3 (CWE)\n * - `address` ← NK1-4 (XAD)\n * - `phone` ← NK1-5 first repetition (XTN)\n * - `contactRole` ← NK1-7 (CWE)\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { NextOfKin } from \"./types.js\";\n\n/**\n * Every NK1 as a `NextOfKin` entry in document order. D-05: returns `[]` when\n * no NK1 is present. D-06: NOT memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const nk of msg.nextOfKin()) {\n * console.log(nk.name?.familyName, nk.relationship?.identifier);\n * }\n * ```\n *\n * @internal\n */\nexport function nextOfKin(msg: Hl7Message): readonly NextOfKin[] {\n const out: NextOfKin[] = [];\n for (const nk1 of msg.segments(\"NK1\")) {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const entry: Mutable<NextOfKin> = {};\n\n const name = nk1.field(2).asXpn();\n if (Object.keys(name).length > 0) entry.name = name;\n\n const relationship = nk1.field(3).asCwe();\n if (Object.keys(relationship).length > 0) entry.relationship = relationship;\n\n const address = nk1.field(4).asXad();\n if (Object.keys(address).length > 0) entry.address = address;\n\n const phone = nk1.field(5).asXtn();\n if (Object.keys(phone).length > 0) entry.phone = phone;\n\n const contactRole = nk1.field(7).asCwe();\n if (Object.keys(contactRole).length > 0) entry.contactRole = contactRole;\n\n out.push(Object.freeze(entry));\n }\n return Object.freeze(out);\n}\n","/**\n * `orders`: Phase 4 Plan 04 implementation of HELPERS-05. Walks the message\n * in document order and groups OBX segments positionally under their\n * preceding OBR (D-12). An ORC segment that precedes an OBR contributes its\n * ORC-1 as the order's `orderControl` (D-16); unmatched trailing ORCs are\n * dropped.\n *\n * Design decisions enforced here:\n * - D-01: `Object.freeze` applied to each Order and to the outer array.\n * - D-05: returns `[]` when no OBR is present.\n * - D-06: NOT memoized: each call re-walks `msg.allSegments()`.\n * - D-12: OBX attached positionally to the preceding OBR; pre-OBR OBX are\n * NOT grouped here (but still surface via `msg.observations()`).\n * - D-16: Order field contract (placerOrderNumber, fillerOrderNumber,\n * universalServiceId, orderStatus, orderControl, orderedBy, observations).\n * - D-18: `orderStatus` uses OBR-25 (resultStatus) for v1; Phase 7 may revisit.\n * - D-22: never throws: malformed OBR/OBX surface as omitted keys.\n * - D-24 (a): `orderedBy` is an XCN composite (not a flat string).\n * - Reuses `buildObservation` from `./observations.ts` (Plan 03): never\n * re-implement OBX → Observation construction here.\n *\n * State-machine shape: two ORC slots.\n * - `pendingOrc` accumulates ORCs seen since the last OBR.\n * - `currentOrc` is the ORC attached to the currently-open OBR group.\n * When an OBR is seen, close the previous group with `currentOrc`, then\n * promote `pendingOrc` → `currentOrc` for the new group and reset\n * `pendingOrc`. A trailing ORC after the last OBR stays in `pendingOrc` and\n * is implicitly dropped (never promoted).\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\n\nimport { groupNotes, type NoteGrouping } from \"./notes.js\";\nimport { buildObservation } from \"./observations.js\";\nimport { buildLegacyTiming, buildTq1Timing } from \"./timing.js\";\nimport type { Observation, Order, OrderTiming } from \"./types.js\";\n\n/** Normalize HL7 empty-string to `undefined` for the helper layer (D-22). @internal */\nfunction stringOrUndefined(v: string): string | undefined {\n return v === \"\" ? undefined : v;\n}\n\n/**\n * Build the frozen `timings` list for an order group (Phase M). Every TQ1\n * segment grouped under the OBR yields one `OrderTiming` (`source: \"TQ1\"`).\n * The legacy embedded TQ in the attached ORC's ORC-7 is read **only when the\n * group carries no TQ1**: so the same timing is never double-counted and a\n * legacy-only (pre-v2.5) timing is never dropped. @internal\n */\nfunction buildTimings(\n tq1Segs: readonly Segment[],\n attachedOrc: Segment | undefined,\n): readonly OrderTiming[] {\n if (tq1Segs.length > 0) {\n return Object.freeze(tq1Segs.map((seg) => buildTq1Timing(seg)));\n }\n if (attachedOrc !== undefined) {\n const legacy = buildLegacyTiming(attachedOrc.field(7)); // ORC-7 Quantity/Timing\n if (legacy !== undefined) return Object.freeze([legacy]);\n }\n return Object.freeze([]);\n}\n\n/** Build a frozen `Order` from the accumulated OBR / attached ORC / observations. @internal */\nfunction finalizeOrder(\n obr: Segment,\n attachedOrc: Segment | undefined,\n observations: readonly Observation[],\n tq1Segs: readonly Segment[],\n noteIndex: NoteGrouping,\n): Order {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Order> = {\n observations,\n timings: buildTimings(tq1Segs, attachedOrc),\n };\n\n // Phase P: every order-level note (ORC-region + OBR-region) is keyed on the\n // OBR in document order by `groupNotes`: the ORC region is flushed onto the\n // OBR when the order opens, so this is a single already-ordered lookup. The\n // array is already frozen by `groupNotes`.\n const orderNotes = noteIndex.byParent.get(obr);\n if (orderNotes !== undefined && orderNotes.length > 0) out.notes = orderNotes;\n\n const placer = stringOrUndefined(obr.field(2).value);\n if (placer !== undefined) out.placerOrderNumber = placer;\n\n const filler = stringOrUndefined(obr.field(3).value);\n if (filler !== undefined) out.fillerOrderNumber = filler;\n\n const usvc: CWE = obr.field(4).asCwe();\n if (Object.keys(usvc).length > 0) out.universalServiceId = usvc;\n\n // D-16: orderStatus from OBR-25 (resultStatus) for v1; Phase 7 may revisit.\n const status = stringOrUndefined(obr.field(25).value);\n if (status !== undefined) out.orderStatus = status;\n\n // D-16: orderControl from the attached ORC-1 (when an ORC preceded this OBR).\n if (attachedOrc !== undefined) {\n const oc = stringOrUndefined(attachedOrc.field(1).value);\n if (oc !== undefined) out.orderControl = oc;\n }\n\n // D-24 (a): orderedBy is an XCN composite read from OBR-16.\n const orderedBy: XCN = obr.field(16).asXcn();\n if (Object.keys(orderedBy).length > 0) out.orderedBy = orderedBy;\n\n return Object.freeze(out) as Order;\n}\n\n/**\n * Every OBR as an Order with its OBX children grouped positionally (D-12).\n * OBX segments that precede any OBR are NOT attached to an order (they still\n * surface in `msg.observations()` which walks all OBX regardless). An ORC\n * segment preceding an OBR contributes its `orderControl` (ORC-1) to that\n * order; unmatched ORCs (trailing after the last OBR) are dropped.\n *\n * D-05: returns `[]` when no OBR is present. D-06: NOT memoized.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const order of msg.orders()) {\n * console.log(order.placerOrderNumber, order.observations.length);\n * for (const obs of order.observations) console.log(obs.value);\n * }\n * ```\n *\n * @internal\n */\nexport function orders(msg: Hl7Message): readonly Order[] {\n const noteIndex = groupNotes(msg); // Phase P: positional NTE grouping (by Segment ref)\n const out: Order[] = [];\n let pendingOrc: Segment | undefined; // accumulates ORCs since last OBR\n let pendingTq1: Segment[] = []; // TQ1 seen before the next OBR opens (Phase M)\n let awaitingObr = false; // an ORC has opened a new group still awaiting its OBR (Phase M)\n let currentObr: Segment | undefined;\n let currentOrc: Segment | undefined; // ORC attached to the open OBR group\n let currentObservations: Observation[] = [];\n let currentTq1: Segment[] = []; // TQ1 grouped under the open OBR (Phase M)\n\n for (const seg of msg.allSegments()) {\n if (seg.type === \"ORC\") {\n pendingOrc = seg;\n // A new ORC starts a new order group: any following TQ1 (before that\n // group's OBR) belongs to the NEXT order, never the still-open prior one.\n awaitingObr = true;\n continue;\n }\n if (seg.type === \"TQ1\") {\n // A TQ1 attaches to the open OBR only when no newer ORC has begun a group;\n // otherwise it modifies the next OBR (a TQ1 can sit either side of the OBR,\n // and an intervening ORC re-scopes it to the following order).\n if (currentObr !== undefined && !awaitingObr) currentTq1.push(seg);\n else pendingTq1.push(seg);\n continue;\n }\n if (seg.type === \"OBR\") {\n // Close previous group using THAT group's attached ORC + TQ1.\n if (currentObr !== undefined) {\n out.push(\n finalizeOrder(\n currentObr,\n currentOrc,\n Object.freeze(currentObservations.slice()),\n currentTq1,\n noteIndex,\n ),\n );\n }\n // Open new group; promote pendingOrc / pendingTq1; reset pending.\n currentObr = seg;\n currentOrc = pendingOrc;\n currentTq1 = pendingTq1;\n pendingOrc = undefined;\n pendingTq1 = [];\n awaitingObr = false;\n currentObservations = [];\n continue;\n }\n if (seg.type === \"OBX\" && currentObr !== undefined) {\n currentObservations.push(buildObservation(seg, noteIndex.byParent.get(seg)));\n }\n }\n\n // Finalize the trailing order. A trailing ORC / TQ1 after the last OBR stays\n // pending and is implicitly dropped (never promoted): parity with ORC.\n if (currentObr !== undefined) {\n out.push(\n finalizeOrder(\n currentObr,\n currentOrc,\n Object.freeze(currentObservations.slice()),\n currentTq1,\n noteIndex,\n ),\n );\n }\n\n return Object.freeze(out);\n}\n","/**\n * `pickMrn`: pick the Medical Record Number string from a PID-3 identifier\n * list. Isolated from `patient.ts` so Phase 6 profile hooks can substitute\n * a profile-aware variant without patching the helper that calls it.\n *\n * Silent (D-21: helpers emit no warnings). Never throws (D-22).\n */\n\nimport type { CX } from \"../model/types/cx.js\";\n\n/**\n * Pick the Medical Record Number string from a list of PID-3 CX identifiers.\n *\n * D-07: prefer the first CX whose `identifierTypeCode === \"MR\"` (HL7 v2.5+\n * canonical MRN marker). D-10: the match is case-SENSITIVE: lowercase\n * `\"mr\"` does NOT match; spec mandates uppercase.\n *\n * D-08: when no MR-typed identifier is found, fall back to the first CX's\n * `idNumber`. Returns `undefined` when the first CX has no `idNumber` (even\n * if later CXs do: the fallback is strictly \"first CX\", not \"first CX with\n * idNumber\", because we need a deterministic answer).\n *\n * D-21: no warning emitted. Callers who need strict MR resolution can walk\n * `patient.identifiers` themselves.\n *\n * @example\n * ```ts\n * import { pickMrn } from \"@cosyte/hl7\";\n * pickMrn([\n * { idNumber: \"X1\" },\n * { idNumber: \"MRN001\", identifierTypeCode: \"MR\" },\n * ]);\n * // → \"MRN001\"\n *\n * pickMrn([{ idNumber: \"X1\" }]);\n * // → \"X1\" (fallback: no MR entry)\n *\n * pickMrn([]);\n * // → undefined\n * ```\n */\nexport function pickMrn(identifiers: readonly CX[]): string | undefined {\n for (const cx of identifiers) {\n if (cx.identifierTypeCode === \"MR\" && cx.idNumber !== undefined) {\n return cx.idNumber;\n }\n }\n const first = identifiers[0];\n return first?.idNumber;\n}\n","/**\n * `buildPatient`: compose PID-derived patient demographics into the frozen\n * `Patient` view exposed by `Hl7Message.patient` (HELPERS-02). Composition\n * happens through the Phase 3 public surface (`msg.segments(\"PID\")[0].field(N)`\n * + composite coercions + `parseCx` / `parseXtn` for multi-rep walks),\n * never through `rawSegments` directly.\n *\n * Decisions honored here:\n * - D-01: `Object.freeze` the top-level object at the boundary.\n * - D-04: return `undefined` when no PID segment exists.\n * - D-07 / D-08 / D-10: MRN pick via `pickMrn` (isolated for Phase 6).\n * - D-09: `identifiers` is a frozen `readonly CX[]`: always present.\n * - D-17: `fullName` is Western order \"Given Middle Family, Suffix\", omitted\n * parts cleanly joined, absent when no usable parts.\n * - Phase N: `dateOfBirth` is the fidelity `TS` (day-only DOB keeps `precision:\n * \"day\"`, never a UTC-midnight instant that shifts the day).\n * - D-19: flat `familyName` / `givenName` / `middleName` convenience fields\n * mirror XPN, with `middleName` mapped from `XPN.secondName`.\n * - D-20: `phoneNumbers` concatenates PID-13 then PID-14 repetitions.\n * - D-22: never throws: absent / malformed fields surface as omitted keys.\n * - D-23: string reads are decoded via `Field.value` / composite parsers (once at parse).\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { CX } from \"../model/types/cx.js\";\nimport { parseCx } from \"../model/types/cx.js\";\nimport type { XPN } from \"../model/types/xpn.js\";\nimport type { XTN } from \"../model/types/xtn.js\";\nimport { parseXtn } from \"../model/types/xtn.js\";\n\nimport { groupNotes } from \"./notes.js\";\nimport { pickMrn } from \"./pick-mrn.js\";\nimport type { Patient } from \"./types.js\";\n\n/**\n * Compose the `fullName` string in Western order \"Given Middle Family,\n * Suffix\" from XPN parts (D-17). Missing parts are omitted cleanly: no\n * double spaces, no leading/trailing comma. Returns `undefined` when no\n * usable parts remain so the helper can omit the key entirely.\n *\n * @internal\n */\nfunction composeFullName(name: XPN): string | undefined {\n const parts: string[] = [];\n if (name.givenName !== undefined && name.givenName !== \"\") parts.push(name.givenName);\n if (name.secondName !== undefined && name.secondName !== \"\") parts.push(name.secondName);\n if (name.familyName !== undefined && name.familyName !== \"\") parts.push(name.familyName);\n const base = parts.join(\" \");\n const suffix = name.suffix;\n const hasSuffix = suffix !== undefined && suffix !== \"\";\n let full: string;\n if (hasSuffix) {\n full = base === \"\" ? suffix : `${base}, ${suffix}`;\n } else {\n full = base;\n }\n return full === \"\" ? undefined : full;\n}\n\n/**\n * Build the immutable `Patient` view from a parsed message's PID segment, or\n * return `undefined` when no PID exists (D-04). The returned object is\n * deeply frozen (D-01) and consumed through the memoized `Hl7Message.patient`\n * getter (D-02). Absent fields are OMITTED (exactOptionalPropertyTypes); the\n * `name`, `identifiers`, and `phoneNumbers` fields are ALWAYS present (D-09,\n * D-19, D-20).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.patient?.mrn); // first CX-5=\"MR\" idNumber\n * console.log(msg.patient?.fullName); // \"Jane Q Smith, Jr\"\n * console.log(msg.patient?.dateOfBirth?.raw); // fidelity TS (Phase N): e.g. \"19800115\"\n * for (const phone of msg.patient?.phoneNumbers ?? []) {\n * console.log(phone.telephoneNumber);\n * }\n * ```\n *\n * @internal\n */\nexport function buildPatient(msg: Hl7Message): Patient | undefined {\n const pid = msg.segments(\"PID\")[0];\n if (pid === undefined) return undefined; // D-04\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Patient> = {};\n\n // ─── PID-3 identifiers (D-09) + MRN pick (D-07 / D-08 / D-10) ─────────\n const identifiers: CX[] = [];\n for (const rep of pid.field(3).repetitions) {\n const cx = parseCx(rep, msg.encodingCharacters);\n if (Object.keys(cx).length > 0) identifiers.push(cx);\n }\n const frozenIds = Object.freeze(identifiers);\n out.identifiers = frozenIds;\n\n const mrn = pickMrn(frozenIds);\n if (mrn !== undefined) out.mrn = mrn;\n\n // ─── PID-5 name (XPN) + flat D-19 shortcuts + D-17 fullName ───────────\n const name = pid.field(5).asXpn();\n out.name = name; // always present, may be `{}` on absent PID-5\n\n if (name.familyName !== undefined) out.familyName = name.familyName;\n if (name.givenName !== undefined) out.givenName = name.givenName;\n if (name.secondName !== undefined) out.middleName = name.secondName; // D-19 rename\n\n const fullName = composeFullName(name);\n if (fullName !== undefined) out.fullName = fullName;\n\n // ─── PID-7 date of birth (Phase N fidelity TS) ────────────────────────\n const dob = pid.field(7).asTs();\n if (dob.valid) out.dateOfBirth = dob;\n\n // ─── PID-8 administrative sex (flat string) ───────────────────────────\n const sex = pid.field(8).value;\n if (sex !== \"\") out.sex = sex;\n\n // ─── PID-11 address (XAD): omit when empty ───────────────────────────\n const address = pid.field(11).asXad();\n if (Object.keys(address).length > 0) out.address = address;\n\n // ─── PID-13 home + PID-14 business phones, concatenated (D-20) ────────\n const phones: XTN[] = [];\n for (const rep of pid.field(13).repetitions) {\n const xtn = parseXtn(rep, msg.encodingCharacters);\n if (Object.keys(xtn).length > 0) phones.push(xtn);\n }\n for (const rep of pid.field(14).repetitions) {\n const xtn = parseXtn(rep, msg.encodingCharacters);\n if (Object.keys(xtn).length > 0) phones.push(xtn);\n }\n out.phoneNumbers = Object.freeze(phones);\n\n // ─── PID-10 race (CWE) ───────────────────────────────────────────────\n const race = pid.field(10).asCwe();\n if (Object.keys(race).length > 0) out.race = race;\n\n // ─── PID-22 ethnicity (CWE) ──────────────────────────────────────────\n const ethnicity = pid.field(22).asCwe();\n if (Object.keys(ethnicity).length > 0) out.ethnicity = ethnicity;\n\n // ─── PID-15 primary language (CE) ────────────────────────────────────\n const language = pid.field(15).asCe();\n if (Object.keys(language).length > 0) out.language = language;\n\n // ─── Phase P: NTE notes positionally attached to this PID ─────────────\n // Notes immediately following the (first) PID segment attach to the patient.\n // A second PID's group notes ride on that PID segment but are not surfaced\n // here (the patient view is the first PID: a documented single-patient model).\n // The array is already frozen by `groupNotes`; a later PID's notes are routed\n // to `msg.notes()` there, never mis-attached to this first-PID patient view.\n const patientNotes = groupNotes(msg).byParent.get(pid);\n if (patientNotes !== undefined && patientNotes.length > 0) out.notes = patientNotes;\n\n // D-01 freeze at boundary.\n return Object.freeze(out) as Patient;\n}\n","/**\n * `buildStructure`: compose the read-side `MessageStructure` summary exposed\n * by `Hl7Message.structure` (roadmap Phase G). It mirrors, on the public\n * message surface, the same conservative expected-group analysis the parser\n * runs at parse time to emit `MISSING_EXPECTED_GROUP` warnings: so a consumer\n * can ask \"did this message carry its expected core groups?\" without scanning\n * `msg.warnings`.\n *\n * Composes on the Phase 3 public surface (`msg.get`, `msg.allSegments()`),\n * never walks `rawSegments` directly. D-01 freeze at boundary (the underlying\n * `analyzeMessageStructure` already freezes deeply). D-02 memoization is the\n * caller's job (`Hl7Message.structure` getter). D-22 never throws.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport { analyzeMessageStructure, type MessageStructure } from \"../parser/message-structure.js\";\n\n/**\n * Build the immutable `MessageStructure` summary for a parsed message. Reads\n * the message type from MSH-9.1 / MSH-9.2 and the present segment names from\n * `msg.allSegments()`, then defers to the pure `analyzeMessageStructure`. The\n * result is deeply frozen and consumed through the memoized\n * `Hl7Message.structure` getter.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.structure.recognized); // true for known types\n * console.log(msg.structure.missingGroups); // e.g. [\"result\"]\n * ```\n *\n * @internal\n */\nexport function buildStructure(msg: Hl7Message): MessageStructure {\n const messageCode = msg.get(\"MSH.9.1\") ?? \"\";\n const triggerEvent = msg.get(\"MSH.9.2\") ?? \"\";\n const presentSegmentNames = new Set<string>();\n for (const seg of msg.allSegments()) presentSegmentNames.add(seg.type);\n return analyzeMessageStructure(messageCode, triggerEvent, presentSegmentNames);\n}\n","/**\n * `buildVisit`: Phase 4 Plan 03 (visit-and-observations) implementation of\n * HELPERS-03. Reads the first PV1 segment (if any) and projects the 7 locked\n * v1 fields as a deeply frozen `Visit` object, composing on Phase 3's public\n * read surface (`msg.segments(\"PV1\")[0].field(n).asXxx()`).\n *\n * Design decisions enforced here:\n * - D-04 nullable: returns `undefined` when no PV1 segment is present.\n * - Phase N: admit/discharge timestamps are the fidelity `TS` (precision +\n * timezone preserved), not an eager `Date`.\n * - D-24 option (a): attendingDoctor/referringDoctor use the Plan 01\n * `Field.asXcn()` coercion (composite, not flat string).\n * - D-01 freeze at boundary: the returned Visit is frozen.\n * - D-22 never-throws: every field reaches a safe default when absent or\n * malformed (empty strings and empty composites are omitted via\n * `exactOptionalPropertyTypes`).\n * - D-02 memoization is handled by the `Hl7Message.visit` getter: this\n * function is invoked lazily on first access and its result is cached.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { PL } from \"../model/types/pl.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\nimport type { Visit } from \"./types.js\";\n\n/** Return `undefined` when an empty-composite parse (`{}`) leaks through. @internal */\nfunction nonEmptyPl(pl: PL): PL | undefined {\n return Object.keys(pl).length === 0 ? undefined : pl;\n}\n\n/** Return `undefined` when an empty-composite XCN parse (`{}`) leaks through. @internal */\nfunction nonEmptyXcn(xcn: XCN): XCN | undefined {\n return Object.keys(xcn).length === 0 ? undefined : xcn;\n}\n\n/**\n * Build the immutable `Visit` view for a parsed message, or `undefined`\n * when no PV1 segment exists (HELPERS-03 nullable). Memoized by\n * `Hl7Message.visit` (D-02); mutations drop the cache wholesale via\n * `invalidateCaches()`.\n *\n * Doctors (attendingDoctor/referringDoctor) are XCN composites per D-24\n * option (a). admitDateTime/dischargeDateTime are the fidelity `TS` (Phase N).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.visit?.patientClass); // \"I\"\n * console.log(msg.visit?.location?.pointOfCare); // \"ICU\"\n * console.log(msg.visit?.admitDateTime?.raw); // fidelity TS (Phase N)\n * console.log(msg.visit?.attendingDoctor?.familyName); // XCN via D-24(a)\n * ```\n *\n * @internal\n */\nexport function buildVisit(msg: Hl7Message): Visit | undefined {\n const pv1 = msg.segments(\"PV1\")[0];\n if (pv1 === undefined) return undefined; // HELPERS-03 nullable\n\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<Visit> = {};\n\n // PV1-2: patientClass (flat string)\n const patientClass = pv1.field(2).value;\n if (patientClass !== \"\") out.patientClass = patientClass;\n\n // PV1-3: location (PL)\n const location = nonEmptyPl(pv1.field(3).asPl());\n if (location !== undefined) out.location = location;\n\n // PV1-7: attendingDoctor (XCN: D-24 option (a))\n const attending = nonEmptyXcn(pv1.field(7).asXcn());\n if (attending !== undefined) out.attendingDoctor = attending;\n\n // PV1-8: referringDoctor (XCN)\n const referring = nonEmptyXcn(pv1.field(8).asXcn());\n if (referring !== undefined) out.referringDoctor = referring;\n\n // PV1-19: visitNumber. Spec-wise PV1-19 is a CX: the lean v1 shape surfaces\n // the first component (idNumber) via `.value`. Callers needing the full CX\n // can reach msg.segments(\"PV1\")[0].field(19).asCx().\n const visitNumber = pv1.field(19).value;\n if (visitNumber !== \"\") out.visitNumber = visitNumber;\n\n // PV1-44: admitDateTime (fidelity TS, Phase N)\n const admit = pv1.field(44).asTs();\n if (admit.valid) out.admitDateTime = admit;\n\n // PV1-45: dischargeDateTime (fidelity TS, Phase N)\n const discharge = pv1.field(45).asTs();\n if (discharge.valid) out.dischargeDateTime = discharge;\n\n return Object.freeze(out);\n}\n","/**\n * `emitPrettyPrint`: human-readable multi-line rendering of an `Hl7Message`\n * for logs and debugging (SER-04).\n *\n * Implementation lives in Phase 5 Plan 04 (pretty-print). Stub throws.\n *\n * Decisions (for Plan 04 implementer):\n * - D-22: no options: single opinionated format.\n * - D-23: segment-per-line with labeled fields `[N]=value`. Field values\n * shown verbatim with active delimiters; empty trailing positions suppressed.\n * - D-24: resolution depth stops at field level: composite values render as\n * their raw HL7 string (e.g. `Smith^John^Q`).\n * - D-25: first line is a metadata header\n * `HL7 <type> controlId=<id> timestamp=<raw-hl7> (<N> segments)`.\n * - D-26: pure: never warns or throws.\n *\n * @internal\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { RawSegment } from \"../parser/types.js\";\nimport { emitField } from \"./emit-field.js\";\n\n/**\n * Emit a human-readable multi-line rendering of a parsed `Hl7Message` for\n * logs and debugging (SER-04). Single opinionated format per D-22; no\n * options. Header per D-25; segment lines per D-23; depth stops at field\n * level per D-24; pure per D-26.\n *\n * **Raw-escape rendering (W2):** field values render as their raw HL7\n * string representation, produced via `emitField`. Embedded delimiters in\n * user data appear as HL7 escape sequences: e.g. a patient family name\n * that was decoded from `\\F\\` on input (literal `|` in `Field.value`)\n * renders in pretty-print as `Smith\\F\\Jones`, NOT as `Smith|Jones`. This\n * preserves round-trip fidelity: copy-pasting the output into `parseHL7`\n * yields a structurally equivalent message. For un-escaped human display,\n * use typed accessors (e.g. `msg.patient?.familyName`), which return\n * already-decoded strings.\n *\n * @internal\n */\nexport function emitPrettyPrint(msg: Hl7Message): string {\n const lines: string[] = [];\n lines.push(buildHeaderLine(msg));\n for (const seg of msg.rawSegments) {\n lines.push(buildSegmentLine(seg, msg));\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * D-25 header:\n * `HL7 <type> controlId=<id> timestamp=<raw-hl7> (<N> segments)`\n * Missing meta fields render as `-`. Segment count is always a number.\n * Separator between header fields is TWO spaces.\n * @internal\n */\nfunction buildHeaderLine(msg: Hl7Message): string {\n const meta = msg.meta;\n const type = meta.type ?? \"-\";\n const controlId = meta.controlId ?? \"-\";\n // Phase N: render the raw HL7 timestamp verbatim (precision + zone preserved)\n // rather than coercing to a UTC ISO instant, which would misstate a day-only\n // or offset-less value.\n const timestamp = meta.timestamp?.raw ?? \"-\";\n const segCount = msg.rawSegments.length;\n return (\n \"HL7 \" +\n type +\n \" controlId=\" +\n controlId +\n \" timestamp=\" +\n timestamp +\n \" (\" +\n String(segCount) +\n \" segments)\"\n );\n}\n\n/**\n * D-23 segment line:\n * `<seg.name> [N]=<emittedFieldValue> [M]=<emittedFieldValue> ...`\n * - Non-MSH: start at fields[1] with HL7 index 1.\n * - MSH: start at fields[2] with HL7 index 3 (MSH-1/MSH-2 are the\n * delimiters themselves and are not labelled: their content is\n * implicit in the header).\n * - Field rendered via `emitField` (D-24 depth stop + W2 raw-escape).\n * - Empty-emitted values are SUPPRESSED (no `[N]=` entry) so sparse\n * segments stay terse. `isNull === true` emits `\"\"` (2 chars) and IS\n * shown.\n * - A segment with only absent fields emits just the segment name\n * (no trailing spaces).\n * @internal\n */\nfunction buildSegmentLine(seg: RawSegment, msg: Hl7Message): string {\n const enc = msg.encodingCharacters;\n // First data field index and first displayed HL7 field number:\n // - MSH: fields[2] -> [3]\n // - non-MSH: fields[1] -> [1]\n const isMsh = seg.name === \"MSH\";\n const firstFieldIndex = isMsh ? 2 : 1;\n const firstDisplayNumber = isMsh ? 3 : 1;\n\n const labeledParts: string[] = [];\n for (let i = firstFieldIndex; i < seg.fields.length; i++) {\n const f = seg.fields[i];\n if (f === undefined) continue;\n const emitted = emitField(f, enc);\n if (emitted === \"\") continue; // suppress absent-field labels\n const displayNumber = firstDisplayNumber + (i - firstFieldIndex);\n labeledParts.push(\"[\" + String(displayNumber) + \"]=\" + emitted);\n }\n\n if (labeledParts.length === 0) return seg.name;\n return seg.name + \" \" + labeledParts.join(\" \");\n}\n","/**\n * `emitJson` + `SerializedMessage`: snapshot-stable JSON projection of an\n * `Hl7Message`. Mirrors `rawSegments` one-for-one; preserves `isNull`;\n * always includes `warnings: []`; omits `profile` when absent.\n *\n * The `SerializedMessage` interface is exported in Plan 01 (this file) so\n * consumers + `src/index.ts` can reference the type immediately. The\n * `emitJson` function body is filled in Phase 5 Plan 03 (to-json).\n *\n * Decisions:\n * - D-17: shape is a raw-tree mirror (encodingCharacters + segments +\n * warnings + optional profile).\n * - D-18: `Hl7Message.toJSON` delegates here so `JSON.stringify(msg)` Just Works.\n * - D-19: warnings array is ALWAYS present (`warnings: []` when empty).\n * - D-20: `profile` field appears only when `msg.profile` is truthy: then\n * contains only `name` + `lineage`.\n * - D-21: `SerializedMessage` is exported from `src/index.ts` (not nested\n * under HL7 namespace).\n *\n * Note on runtime freeze scope: `emitJson` returns an object that is\n * boundary-frozen (top level only: `Object.isFrozen(msg.toJSON()) === true`).\n * Inner arrays are readonly at the TypeScript type level but MUTABLE at\n * runtime: consumers should treat the returned structure as immutable\n * and not mutate nested arrays. Deep-freeze is explicitly rejected per\n * D-30 (emit is hot-path; runtime deep-freeze would add cost with no\n * observable benefit given the type-level readonly contract).\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { EncodingCharacters } from \"../parser/types.js\";\nimport type { Hl7ParseWarning } from \"../parser/warnings.js\";\n\n/**\n * Snapshot-stable JSON projection of an `Hl7Message` (SER-03). Every field\n * is readonly; segment order is preserved; `isNull` flags are preserved.\n *\n * Runtime immutability: the top-level object is `Object.freeze`d\n * (boundary-frozen). Inner arrays are readonly at the TypeScript type\n * level but mutable at runtime: treat as immutable, do not mutate.\n *\n * @example\n * ```ts\n * import { parseHL7, type SerializedMessage } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const snap: SerializedMessage = msg.toJSON();\n * console.log(snap.segments[0]?.name); // \"MSH\"\n * console.log(snap.warnings.length); // 0 when clean\n * console.log(JSON.stringify(msg) === JSON.stringify(snap)); // true\n * console.log(Object.isFrozen(snap)); // true (D-30 boundary freeze)\n * ```\n */\nexport interface SerializedMessage {\n readonly encodingCharacters: EncodingCharacters;\n readonly segments: ReadonlyArray<{\n readonly name: string;\n readonly fields: ReadonlyArray<{\n readonly repetitions: ReadonlyArray<{\n readonly components: ReadonlyArray<{ readonly subcomponents: readonly string[] }>;\n }>;\n readonly isNull: boolean;\n }>;\n }>;\n readonly warnings: readonly Hl7ParseWarning[];\n readonly profile?: { readonly name: string; readonly lineage: readonly string[] };\n}\n\n/**\n * Build the `SerializedMessage` snapshot from a parsed message (SER-03).\n * Raw-tree mirror per D-17; warnings array always present (D-19); profile\n * included only when `msg.profile` is truthy (D-20). Pure: never warns,\n * never throws. Not cached (D-30: each call re-walks `rawSegments`).\n *\n * Boundary-frozen: the top-level returned object passes through\n * `Object.freeze` before return, so `Object.isFrozen(result) === true`.\n * Inner arrays are readonly at the TS type level but NOT runtime-frozen\n * (D-30 cost doctrine: emit is hot-path; deep-freeze would add traversal\n * cost with no observable benefit beyond the type contract).\n *\n * Shared Phase-2 invariant (established by Plan 02): the raw tree stores\n * DECODED subcomponent strings (tokenize now unescapes on parse). emitJson\n * mirrors those decoded strings verbatim: NO re-escape transformation is\n * applied here; the JSON projection reflects the decoded source of truth.\n *\n * @internal\n */\nexport function emitJson(msg: Hl7Message): SerializedMessage {\n // Raw-tree mirror (D-17). Build fresh plain objects so the output is\n // decoupled from the parser's internal arrays. `subcomponents.slice()`\n // clones the inner string array; primitives are cloned for free.\n const segments = msg.rawSegments.map((seg) => ({\n name: seg.name,\n fields: seg.fields.map((field) => ({\n // D-17 + Claude's-Discretion: `repetitions` is ALWAYS `[]` when the\n // field has zero repetitions: shape-stable, no conditional omission.\n repetitions: field.repetitions.map((rep) => ({\n components: rep.components.map((comp) => ({\n subcomponents: comp.subcomponents.slice(),\n })),\n })),\n isNull: field.isNull,\n })),\n }));\n\n // exactOptionalPropertyTypes-safe conditional-assign pattern. An absent\n // `profile` key is valid for the optional field; an explicit\n // `profile: undefined` is NOT. Mirrors `src/helpers/meta.ts::buildMeta`.\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<SerializedMessage> = {\n encodingCharacters: {\n field: msg.encodingCharacters.field,\n component: msg.encodingCharacters.component,\n repetition: msg.encodingCharacters.repetition,\n escape: msg.encodingCharacters.escape,\n subcomponent: msg.encodingCharacters.subcomponent,\n },\n segments,\n // D-19: ALWAYS present, even when empty. `msg.warnings` is already frozen\n // at Hl7Message construction (Phase 2): pass-through is safe.\n warnings: msg.warnings,\n };\n\n if (msg.profile !== undefined) {\n // D-20 structural contract: EXACTLY `{name, lineage}`. The upstream\n // parser constructor (src/parser/index.ts) already strips any extra\n // `Profile`-descriptor fields (onWarning, customSegments, dateFormats,\n // description) before assigning to `Hl7Message.profile`. `lineage` is\n // REQUIRED (not optional) when profile is defined: straight\n // assignment; no nullish-coalesce fallback (would be dead code given\n // the type guarantee).\n out.profile = {\n name: msg.profile.name,\n lineage: msg.profile.lineage,\n };\n }\n\n // W5: boundary-freeze at the top level only. Inner arrays remain mutable\n // at runtime by design (D-30: deep-freeze rejected as hot-path cost with\n // no observable benefit over the TS readonly type contract).\n return Object.freeze(out) as SerializedMessage;\n}\n","/**\n * `emitMessage`: top-level HL7 string emitter. Composes `emitSegment` from\n * `./emit-field.ts`, special-cases MSH-1 / MSH-2 per D-06, and joins segments\n * with strict CR (`\\r`) per D-05.\n *\n * Implementation lives in Phase 5 Plan 02 (to-string-and-round-trip). This\n * stub exists so Plan 01 can wire the `Hl7Message.toString` instance method\n * before Plan 02 runs; invoking it throws.\n *\n * Decisions (for Plan 02 implementer):\n * - D-01: walk `msg.rawSegments` verbatim.\n * - D-04: every field string passes through `emitField` (which calls\n * `reescape` internally).\n * - D-05: segments joined by `\\r`; trailing `\\r` after the last segment.\n * - D-06: MSH-1 / MSH-2 inlined (see CONTEXT §specifics emission trace).\n * - D-07: pure: never warns, never throws.\n * - D-08: no MLLP wrapping.\n *\n * @internal\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport { emitField, emitSegment } from \"./emit-field.js\";\nimport type { EncodingCharacters, RawSegment } from \"../parser/types.js\";\n\n/**\n * Emit a parsed `Hl7Message` as spec-clean HL7 (SER-01 + SER-05). Walks\n * `msg.rawSegments` verbatim (D-01). Inlines MSH-1 and MSH-2 from\n * `msg.encodingCharacters` per D-06. Joins segments with strict CR (`\\r`)\n * and appends a trailing CR per D-05. Does NOT wrap in MLLP framing (D-08).\n *\n * Trailing-empty semantics: D-02's trailing-empty strip is field-SCOPED\n * (inside `emitField`: trailing empty repetitions/components/subcomponents\n * are stripped). At the SEGMENT level (inside `emitSegment`) trailing empty\n * fields are PRESERVED to maintain HL7 positional addressing. `emitMessage`\n * does not alter either behavior.\n *\n * Pure for all well-formed inputs: never warns on structurally valid\n * messages (D-07). Throws a typed `Error` ONLY for the structurally\n * invalid case of `msg.rawSegments.length === 0` (W1 fix): emitting a\n * bare `\"\\r\"` for a zero-segment message would violate the \"serializer\n * is conservative (always emits spec-clean HL7)\" guardrail, since\n * `parseHL7(\"\\r\")` fails with `NO_MSH_SEGMENT`. The throw mirrors the\n * D-06 MSH guard in `emitSegment`: catch programmer misuse loudly at\n * the call site rather than silently corrupting wire output. The parser\n * cannot produce an empty `rawSegments`, so this path is only reachable\n * via direct `new Hl7Message({ segments: [] })` construction or post-\n * `removeSegment` edge cases.\n *\n * @internal\n */\nexport function emitMessage(msg: Hl7Message): string {\n if (msg.rawSegments.length === 0) {\n throw new Error(\n \"emitMessage: refusing to emit a message with zero segments. \" +\n \"Every HL7 message must contain at least an MSH segment per HL7 v2 spec.\",\n );\n }\n const enc = msg.encodingCharacters;\n const segmentStrings: string[] = [];\n for (const seg of msg.rawSegments) {\n if (seg.name === \"MSH\") {\n segmentStrings.push(emitMshSegment(seg, enc));\n } else {\n segmentStrings.push(emitSegment(seg, enc));\n }\n }\n return segmentStrings.join(\"\\r\") + \"\\r\";\n}\n\n/**\n * Emit the MSH segment with the D-06 special case: MSH-1 is `enc.field`\n * (one char, inlined immediately after \"MSH\"), MSH-2 is\n * `enc.component + enc.repetition + enc.escape + enc.subcomponent`\n * (4 chars, fixed order), and MSH-3..N use the normal `emitField` path\n * joined by `enc.field`.\n *\n * This is the exact inverse of Phase 2 `readDelimiters`:\n * - `readDelimiters` reads `firstSegment.charAt(3)` as the field separator\n * and `firstSegment.slice(4, 8)` as MSH-2;\n * - `emitMshSegment` writes `\"MSH\" + enc.field + <MSH-2 chars> + enc.field + <rest>`.\n *\n * Trailing empty fields in MSH-3..N are PRESERVED (W3): no trimming of\n * the `tailParts` array before joining.\n *\n * **IMPORTANT: `seg.fields[0]` and `seg.fields[1]` content is IGNORED**\n * (WR-02): MSH-1 and MSH-2 are emitted from `msg.encodingCharacters` per\n * D-06, which is the single source of truth. This is a deliberate\n * deviation from the general D-01 \"walk `msg.rawSegments` verbatim\"\n * doctrine, because running MSH-2 through `emitField` would re-escape\n * the encoding chars and produce garbage. For parser-produced messages\n * `fields[0]` / `fields[1]` always match `encodingCharacters`. For\n * synthetic messages constructed via `new Hl7Message({...})` directly,\n * the burden is on the caller to keep `encodingCharacters` aligned with\n * the raw tree's MSH-1/MSH-2 placeholders: if they diverge, this\n * emitter silently favors `encodingCharacters`.\n *\n * @internal\n */\nfunction emitMshSegment(seg: RawSegment, enc: EncodingCharacters): string {\n // MSH-2 literal chars (D-06 fixed order). When the parsed encoding carried\n // a v2.7+ truncation char (5-char MSH-2), emit it in the 5th position so\n // the wire form round-trips byte-exact.\n const msh2 =\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\");\n // MSH-3..N: fields[2..N] via emitField, joined by enc.field.\n // W3: trailing empty fields preserved: do NOT pop trailing \"\" off tailParts.\n const tailParts: string[] = [];\n for (let i = 2; i < seg.fields.length; i++) {\n const f = seg.fields[i];\n tailParts.push(f === undefined ? \"\" : emitField(f, enc));\n }\n const tail = tailParts.join(enc.field);\n // D-06 exact emission trace:\n // \"MSH\" + enc.field + enc.component + enc.repetition + enc.escape +\n // enc.subcomponent + enc.field + <tail>\n // = \"MSH\" + enc.field + msh2 + enc.field + tail\n return \"MSH\" + enc.field + msh2 + enc.field + tail;\n}\n","/**\n * Typed-composite **encoders** for the `@cosyte/hl7` emit path (roadmap Phase\n * T): the conservative-emit mirror of the `src/model/types/*` read parsers.\n *\n * Each encoder takes one typed composite (an {@link XPN} name, a {@link CX}\n * identifier, a {@link TS} timestamp, …) and produces a `RawField` whose\n * positional structure matches exactly what the corresponding `parseXxx`\n * reads back. The load-bearing guarantees:\n *\n * - **No delimiter injection.** Component values are stored **decoded** (the\n * same surface `parseXxx` returns), and the serializer (`emit-field.ts`)\n * runs every subcomponent through `reescape` (the HL7-R encode-safe codec)\n * on the way out. A `familyName` of `\"Smith^Jr\"` is therefore emitted as\n * `Smith\\S\\Jr` (one component) and re-parses to the exact string `\"Smith^Jr\"`,\n * never forging a component boundary. The caller never hand-assembles\n * `^`/`&`/`~`.\n * - **`emit ∘ parse` identity on the modelled fields.** Interior empty\n * components are preserved (so component positions stay aligned) and only\n * trailing empties are trimmed (matching the serializer's D-02 strip and the\n * parser's omit-on-absent), so `parseXxx(encodeXxx(v)) ` reproduces `v` on\n * every modelled field.\n * - **Never fabricate.** An omitted optional field encodes to an empty /\n * absent component: never a defaulted value. An all-empty composite encodes\n * to an absent field (`repetitions: []`).\n *\n * Zero runtime deps: pure functions over the raw positional tree.\n */\n\nimport type { RawComponent, RawField, RawRepetition } from \"../parser/types.js\";\n\nimport type { CE } from \"../model/types/ce.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport type { CX } from \"../model/types/cx.js\";\nimport type { HD } from \"../model/types/hd.js\";\nimport type { NM } from \"../model/types/nm.js\";\nimport type { PL } from \"../model/types/pl.js\";\nimport type { TS } from \"../model/types/ts.js\";\nimport type { XAD } from \"../model/types/xad.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\nimport type { XPN } from \"../model/types/xpn.js\";\nimport type { XTN } from \"../model/types/xtn.js\";\n\n/**\n * The 11 typed composite kinds this module can encode. Mirrors the read-side\n * composite set (`XPN`, `XAD`, `CX`, `CWE`, `CE`, `XTN`, `PL`, `TS`, `NM`,\n * `HD`, `XCN`).\n */\nexport type CompositeKind =\n | \"XPN\"\n | \"XAD\"\n | \"CX\"\n | \"CWE\"\n | \"CE\"\n | \"XTN\"\n | \"PL\"\n | \"TS\"\n | \"NM\"\n | \"HD\"\n | \"XCN\";\n\n/**\n * Maps each {@link CompositeKind} to the typed value {@link encodeComposite}\n * (and `setComposite`) accept for it. `TS` also accepts a pre-formatted HL7\n * timestamp string; `NM` also accepts a `number` or a raw numeric string,\n * both are emitted verbatim (the serializer never re-formats a claimed value).\n */\nexport interface CompositeValueByKind {\n readonly XPN: XPN;\n readonly XAD: XAD;\n readonly CX: CX;\n readonly CWE: CWE;\n readonly CE: CE;\n readonly XTN: XTN;\n readonly PL: PL;\n readonly TS: TS | string;\n readonly NM: NM | number | string;\n readonly HD: HD;\n readonly XCN: XCN;\n}\n\n/** A single-subcomponent component carrying `value` (or empty when absent). @internal */\nfunction sc(value: string | undefined): RawComponent {\n return { subcomponents: [value ?? \"\"] };\n}\n\n/**\n * A component whose subcomponents form a nested HD (namespaceId & universalId &\n * universalIdType): the shape `parseHd` reads from a synthesised repetition\n * inside CX-4 / PL-4 / XCN-9. Trailing-empty subcomponents are trimmed so the\n * emitted `&`-run matches what the parser produced. Absent HD → empty component.\n * @internal\n */\nfunction hdComponent(hd: HD | undefined): RawComponent {\n if (hd === undefined) return { subcomponents: [] };\n const subs = [hd.namespaceId ?? \"\", hd.universalId ?? \"\", hd.universalIdType ?? \"\"];\n while (subs.length > 0 && subs[subs.length - 1] === \"\") subs.pop();\n return { subcomponents: subs };\n}\n\n/** True iff a component carries no content (no subcomponents, or all empty). @internal */\nfunction isEmptyComponent(c: RawComponent): boolean {\n return c.subcomponents.every((s) => s === \"\");\n}\n\n/**\n * Assemble a `RawField` from an ordered component list: interior empties are\n * preserved (positions stay aligned for a faithful re-parse), trailing empties\n * are trimmed, and an all-empty list yields an absent field (`repetitions: []`).\n * @internal\n */\nfunction toField(components: readonly RawComponent[]): RawField {\n const trimmed = components.slice();\n while (trimmed.length > 0) {\n const last = trimmed[trimmed.length - 1];\n if (last !== undefined && isEmptyComponent(last)) trimmed.pop();\n else break;\n }\n if (trimmed.length === 0) return { repetitions: [], isNull: false };\n return { repetitions: [{ components: trimmed }], isNull: false };\n}\n\n/**\n * Encode an XPN (14 components) to a spec-clean field.\n *\n * @example\n * ```ts\n * import { encodeXpn } from \"@cosyte/hl7\";\n * encodeXpn({ familyName: \"Doe\", givenName: \"Jane\", prefix: \"Dr\" });\n * ```\n */\nexport function encodeXpn(v: XPN): RawField {\n return toField([\n sc(v.familyName),\n sc(v.givenName),\n sc(v.secondName),\n sc(v.suffix),\n sc(v.prefix),\n sc(v.degree),\n sc(v.nameTypeCode),\n sc(v.nameRepresentationCode),\n sc(v.nameContext),\n sc(v.nameValidityRange),\n sc(v.nameAssemblyOrder),\n sc(v.effectiveDate),\n sc(v.expirationDate),\n sc(v.professionalSuffix),\n ]);\n}\n\n/**\n * Encode an XAD (12 components) to a spec-clean field.\n *\n * @example\n * ```ts\n * import { encodeXad } from \"@cosyte/hl7\";\n * encodeXad({ street: \"123 Main St\", city: \"Boston\", stateOrProvince: \"MA\" });\n * ```\n */\nexport function encodeXad(v: XAD): RawField {\n return toField([\n sc(v.street),\n sc(v.otherDesignation),\n sc(v.city),\n sc(v.stateOrProvince),\n sc(v.zipOrPostalCode),\n sc(v.country),\n sc(v.addressType),\n sc(v.otherGeographicDesignation),\n sc(v.countyParishCode),\n sc(v.censusTract),\n sc(v.addressRepresentationCode),\n sc(v.addressValidityRange),\n ]);\n}\n\n/**\n * Encode a CX (identifier): component 4 is a nested HD (assigningAuthority).\n *\n * @example\n * ```ts\n * import { encodeCx } from \"@cosyte/hl7\";\n * encodeCx({ idNumber: \"MRN001\", assigningAuthority: { namespaceId: \"HOSP\" }, identifierTypeCode: \"MR\" });\n * ```\n */\nexport function encodeCx(v: CX): RawField {\n return toField([\n sc(v.idNumber),\n sc(v.checkDigit),\n sc(v.checkDigitScheme),\n hdComponent(v.assigningAuthority),\n sc(v.identifierTypeCode),\n sc(v.assigningFacility),\n sc(v.effectiveDate),\n sc(v.expirationDate),\n sc(v.assigningJurisdiction),\n sc(v.assigningAgencyOrDepartment),\n ]);\n}\n\n/**\n * Encode a CWE (coded element, 9 modelled + preserved `extraComponents`).\n *\n * @example\n * ```ts\n * import { encodeCwe } from \"@cosyte/hl7\";\n * encodeCwe({ identifier: \"GLU\", text: \"Glucose\", nameOfCodingSystem: \"LN\" });\n * ```\n */\nexport function encodeCwe(v: CWE): RawField {\n const components: RawComponent[] = [\n sc(v.identifier),\n sc(v.text),\n sc(v.nameOfCodingSystem),\n sc(v.alternateIdentifier),\n sc(v.alternateText),\n sc(v.nameOfAlternateCodingSystem),\n sc(v.codingSystemVersionId),\n sc(v.alternateCodingSystemVersionId),\n sc(v.originalText),\n ];\n for (const extra of v.extraComponents ?? []) components.push(sc(extra));\n return toField(components);\n}\n\n/**\n * Encode a CE (coded element, 6 modelled + preserved `extraComponents`).\n *\n * @example\n * ```ts\n * import { encodeCe } from \"@cosyte/hl7\";\n * encodeCe({ identifier: \"GLU\", text: \"Glucose\", nameOfCodingSystem: \"L\" });\n * ```\n */\nexport function encodeCe(v: CE): RawField {\n const components: RawComponent[] = [\n sc(v.identifier),\n sc(v.text),\n sc(v.nameOfCodingSystem),\n sc(v.alternateIdentifier),\n sc(v.alternateText),\n sc(v.nameOfAlternateCodingSystem),\n ];\n for (const extra of v.extraComponents ?? []) components.push(sc(extra));\n return toField(components);\n}\n\n/**\n * Encode an XTN (telecom, 12 components) to a spec-clean field.\n *\n * @example\n * ```ts\n * import { encodeXtn } from \"@cosyte/hl7\";\n * encodeXtn({ telephoneNumber: \"555-1234\", telecommunicationUseCode: \"PRN\" });\n * ```\n */\nexport function encodeXtn(v: XTN): RawField {\n return toField([\n sc(v.telephoneNumber),\n sc(v.telecommunicationUseCode),\n sc(v.telecommunicationEquipmentType),\n sc(v.emailAddress),\n sc(v.countryCode),\n sc(v.areaCityCode),\n sc(v.localNumber),\n sc(v.extension),\n sc(v.anyText),\n sc(v.extensionPrefix),\n sc(v.speedDialCode),\n sc(v.unformattedTelephoneNumber),\n ]);\n}\n\n/**\n * Encode a PL (person location): component 4 is a nested HD (facility).\n *\n * @example\n * ```ts\n * import { encodePl } from \"@cosyte/hl7\";\n * encodePl({ pointOfCare: \"ICU\", room: \"101\", bed: \"A\" });\n * ```\n */\nexport function encodePl(v: PL): RawField {\n return toField([\n sc(v.pointOfCare),\n sc(v.room),\n sc(v.bed),\n hdComponent(v.facility),\n sc(v.locationStatus),\n sc(v.personLocationType),\n sc(v.building),\n sc(v.floor),\n sc(v.locationDescription),\n sc(v.comprehensiveLocationId),\n sc(v.assigningAuthorityForLocation),\n ]);\n}\n\n/**\n * Encode an HD (hierarchic designator, 3 components) to a spec-clean field.\n *\n * @example\n * ```ts\n * import { encodeHd } from \"@cosyte/hl7\";\n * encodeHd({ namespaceId: \"EPIC\", universalId: \"1.2.840\", universalIdType: \"ISO\" });\n * ```\n */\nexport function encodeHd(v: HD): RawField {\n return toField([sc(v.namespaceId), sc(v.universalId), sc(v.universalIdType)]);\n}\n\n/**\n * Encode a TS/DTM timestamp. Accepts either the typed {@link TS} (its `raw`\n * string is emitted verbatim: the serializer never re-derives a timestamp\n * from parts) or a pre-formatted HL7 timestamp string.\n *\n * @example\n * ```ts\n * import { encodeTs } from \"@cosyte/hl7\";\n * encodeTs(\"20260721101500\");\n * ```\n */\nexport function encodeTs(v: TS | string): RawField {\n const raw = typeof v === \"string\" ? v : v.raw;\n return toField([sc(raw)]);\n}\n\n/**\n * Encode an NM numeric. Accepts the typed {@link NM} (its `raw` string emitted\n * verbatim, preserving the sender's precision/formatting), a `number`, or a raw\n * string. A `number` is stringified with `String(n)`; the value is never\n * reconciled or rounded.\n *\n * @example\n * ```ts\n * import { encodeNm } from \"@cosyte/hl7\";\n * encodeNm(\"120.50\"); // precision preserved verbatim\n * ```\n */\nexport function encodeNm(v: NM | number | string): RawField {\n let raw: string;\n if (typeof v === \"number\") raw = String(v);\n else if (typeof v === \"string\") raw = v;\n else raw = v.raw;\n return toField([sc(raw)]);\n}\n\n/**\n * Encode an XCN: component 9 is a nested HD (assigningAuthority).\n *\n * @example\n * ```ts\n * import { encodeXcn } from \"@cosyte/hl7\";\n * encodeXcn({ idNumber: \"1234567890\", familyName: \"Welby\", identifierTypeCode: \"NPI\" });\n * ```\n */\nexport function encodeXcn(v: XCN): RawField {\n return toField([\n sc(v.idNumber),\n sc(v.familyName),\n sc(v.givenName),\n sc(v.secondName),\n sc(v.suffix),\n sc(v.prefix),\n sc(v.degree),\n sc(v.sourceTable),\n hdComponent(v.assigningAuthority),\n sc(v.nameTypeCode),\n sc(v.identifierCheckDigit),\n sc(v.checkDigitScheme),\n sc(v.identifierTypeCode),\n ]);\n}\n\n/**\n * Encode any typed composite into a spec-clean `RawField` by its\n * {@link CompositeKind}. The single dispatcher `setComposite` and the typed\n * builders (`buildAdt`/`buildOru`) route through.\n *\n * Encoding takes **no** encoding-characters argument on purpose: the field it\n * produces carries the **decoded** component values, and the actual\n * delimiter-escaping happens later in the serializer against the message's own\n * encoding characters: so a composite is delimiter-independent to encode.\n *\n * @example\n * ```ts\n * import { encodeComposite } from \"@cosyte/hl7\";\n * // A hostile family name cannot break framing on emit:\n * const f = encodeComposite(\"XPN\", { familyName: \"Smith^Jr\", givenName: \"Ann\" });\n * ```\n */\nexport function encodeComposite<K extends CompositeKind>(\n kind: K,\n value: CompositeValueByKind[K],\n): RawField {\n switch (kind) {\n case \"XPN\":\n return encodeXpn(value as XPN);\n case \"XAD\":\n return encodeXad(value as XAD);\n case \"CX\":\n return encodeCx(value as CX);\n case \"CWE\":\n return encodeCwe(value as CWE);\n case \"CE\":\n return encodeCe(value as CE);\n case \"XTN\":\n return encodeXtn(value as XTN);\n case \"PL\":\n return encodePl(value as PL);\n case \"TS\":\n return encodeTs(value as TS | string);\n case \"NM\":\n return encodeNm(value as NM | number | string);\n case \"HD\":\n return encodeHd(value as HD);\n case \"XCN\":\n return encodeXcn(value as XCN);\n default: {\n // Exhaustiveness guard: a new CompositeKind must add a branch above.\n const never: never = kind;\n throw new TypeError(`encodeComposite: unknown composite kind ${JSON.stringify(never)}.`);\n }\n }\n}\n\n/**\n * Encode an array of typed composites into a single repeating `RawField`: one\n * HL7 repetition (`~`-joined on emit) per array element. Used for repeating\n * fields such as PID-3 (patient identifier list) and PID-11 (addresses). An\n * empty array yields an absent field.\n *\n * @example\n * ```ts\n * import { encodeCompositeReps } from \"@cosyte/hl7\";\n * const ids = encodeCompositeReps(\"CX\", [\n * { idNumber: \"MRN001\", identifierTypeCode: \"MR\" },\n * { idNumber: \"9990\", identifierTypeCode: \"SS\" },\n * ]);\n * ```\n */\nexport function encodeCompositeReps<K extends CompositeKind>(\n kind: K,\n values: readonly CompositeValueByKind[K][],\n): RawField {\n const repetitions: RawRepetition[] = [];\n for (const value of values) {\n const encoded = encodeComposite(kind, value);\n // Each single-composite encode yields at most one repetition; an all-empty\n // composite yields none: skip it so an empty entry never forges a bare `~`.\n for (const rep of encoded.repetitions) repetitions.push(rep);\n }\n return { repetitions, isNull: false };\n}\n","/**\n * `Hl7Message`: the immutable parsed-message model produced by `parseHL7`.\n * Phase 2 shipped the read-only shell; Phase 3 extends the same class with\n * the read-path traversal methods (`get`, `getAll`, `segments`,\n * `allSegments`) on top of lazy, referentially stable Segment/Field caches\n * (D-11/D-12). The constructor surface is unchanged (Phase 2 D-05 lock),\n * `init.segments` is still the parser-side key, but the public raw-tree\n * field is now exposed as `rawSegments` to free up the name `segments` for\n * the typed `segments(type)` method.\n */\n\nimport { parsePath, resolvePath } from \"./dot-path.js\";\nimport { Segment } from \"./segment.js\";\nimport type {\n CustomSegmentDefinition,\n EncodingCharacters,\n RawComponent,\n RawField,\n RawRepetition,\n RawSegment,\n} from \"../parser/types.js\";\nimport type { Hl7ParseWarning } from \"../parser/warnings.js\";\nimport { allergies as walkAllergies } from \"../helpers/allergies.js\";\nimport { appointments as walkAppointments } from \"../helpers/appointments.js\";\nimport { charges as walkCharges } from \"../helpers/charges.js\";\nimport { diagnoses as walkDiagnoses } from \"../helpers/diagnoses.js\";\nimport { documents as walkDocuments } from \"../helpers/documents.js\";\nimport type { IdentityEvent } from \"../helpers/identity.js\";\nimport { identityEvents as walkIdentityEvents } from \"../helpers/identity.js\";\nimport { immunizations as walkImmunizations } from \"../helpers/immunizations.js\";\nimport { insurance as walkInsurance } from \"../helpers/insurance.js\";\nimport { medications as walkMedications } from \"../helpers/medications.js\";\nimport { buildMeta } from \"../helpers/meta.js\";\nimport { nextOfKin as walkNextOfKin } from \"../helpers/next-of-kin.js\";\nimport { notes as walkNotes } from \"../helpers/notes.js\";\nimport { observations as walkObservations } from \"../helpers/observations.js\";\nimport { orders as walkOrders } from \"../helpers/orders.js\";\nimport { buildPatient } from \"../helpers/patient.js\";\nimport { buildStructure } from \"../helpers/structure.js\";\nimport type {\n Allergy,\n Appointment,\n Charge,\n ClinicalDocument,\n Diagnosis,\n Immunization,\n Insurance,\n Medication,\n Meta,\n NextOfKin,\n Observation,\n Order,\n Patient,\n Visit,\n} from \"../helpers/types.js\";\nimport type { MessageStructure } from \"../parser/message-structure.js\";\nimport { buildVisit } from \"../helpers/visit.js\";\nimport { emitPrettyPrint } from \"../serialize/pretty-print.js\";\nimport { emitJson, type SerializedMessage } from \"../serialize/to-json.js\";\nimport { emitMessage } from \"../serialize/to-string.js\";\nimport {\n encodeComposite,\n type CompositeKind,\n type CompositeValueByKind,\n} from \"../builder/encode-composite.js\";\n\n/**\n * HL7 segment-name shape: 3 characters, first an uppercase ASCII letter,\n * remaining two uppercase ASCII letters or digits: `[A-Z][A-Z0-9]{2}`.\n * This matches standard HL7 v2 segment names (MSH, PID, PV1, PV2, OBX,\n * OBR, NK1, AL1, DG1, IN1, IN2, IN3, …) AND Z-segment custom shapes\n * (ZPI, ZX1, …). Enforced symmetrically on `addSegment` and\n * `removeSegment` so consumers see consistent validation for any mutation\n * that takes a segment name.\n * @internal\n */\nconst SEGMENT_NAME_RE = /^[A-Z][A-Z0-9]{2}$/u;\n\n/**\n * Shallow-copy a readonly array to a mutable one. Mutation methods rebuild\n * the affected path from leaf to root to keep the declared `readonly Raw*`\n * shapes honest: this helper is the one sanctioned bridge from readonly to\n * mutable for Phase 3 mutation.\n * @internal\n */\nfunction toMutableArray<T>(arr: readonly T[]): T[] {\n return arr.slice();\n}\n\n/**\n * Constructor init shape for `Hl7Message`. Exposed for advanced use (e.g.\n * constructing synthetic messages in tests or higher-level builders) but\n * most consumers should rely on `parseHL7` to produce `Hl7Message`\n * instances.\n *\n * @remarks\n * With `exactOptionalPropertyTypes: true`, callers cannot pass\n * `{ profile: undefined }`: either omit the key or pass a real profile\n * descriptor. This matches the `Hl7Message.profile` public field shape\n * (`... | undefined`).\n *\n * The init key is still named `segments` (not `rawSegments`) so Phase 2\n * parser code that constructs `Hl7Message` does not need to change. Inside\n * the class body the raw tree is stored on `this.rawSegments`.\n *\n * @internal\n */\nexport interface Hl7MessageInit {\n readonly segments: readonly RawSegment[];\n readonly encodingCharacters: EncodingCharacters;\n readonly version: string;\n readonly warnings: readonly Hl7ParseWarning[];\n readonly profile?: { readonly name: string; readonly lineage: readonly string[] };\n /**\n * Merged customSegments map from the applied profile (D-16). Threaded\n * into Segment constructors so `seg.get(fieldName)` can resolve custom\n * positions (PROF-07). Absent when no profile was applied.\n */\n readonly customSegments?: Readonly<Record<string, CustomSegmentDefinition>>;\n /**\n * Merged `dateFormats` list: `options.dateFormats ++ profile.dateFormats`\n * deduped first-occurrence per D-21. Consumed by `msg.meta.timestamp` and\n * any future helper that calls `parseDtmCascade` directly. Absent when\n * neither `options.dateFormats` nor `profile.dateFormats` was supplied.\n */\n readonly dateFormats?: readonly string[];\n}\n\n/**\n * Parsed HL7 v2 message. Produced by `parseHL7`. Exposes the raw positional\n * tree (`rawSegments`), delimiter metadata, warnings, and a typed traversal\n * surface: `get(path)` for dot-paths, `getAll(type)` / `segments(type)` /\n * `allSegments()` for wrapper-level iteration.\n *\n * @remarks\n * The `warnings` array is frozen at the model boundary so downstream\n * traversal and helper phases cannot mutate parser output. The `profile`\n * field is populated by Phase 6 when a profile is passed; Phase 2 leaves\n * it `undefined` by default. Segment/Field wrappers are cached per-message\n * and invalidated wholesale by Plan 04 mutation methods.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.get(\"PID.5.1\")); // \"Smith\"\n * for (const obx of msg.segments(\"OBX\")) {\n * console.log(obx.field(5).value);\n * }\n * for (const w of msg.warnings) console.warn(w.code);\n * ```\n */\nexport class Hl7Message {\n /**\n * Raw positional tree produced by the parser. 1-indexed per HL7 convention\n * (`fields[0]` is the segment-name / MSH separator placeholder slot). Use\n * `segments(type)` / `allSegments()` for typed wrapper access: this field\n * is exposed for advanced callers that need the raw tree directly (e.g.\n * future serialization phase 5).\n */\n public readonly rawSegments: readonly RawSegment[];\n\n public readonly encodingCharacters: EncodingCharacters;\n public readonly version: string;\n public readonly warnings: readonly Hl7ParseWarning[];\n public readonly profile:\n | { readonly name: string; readonly lineage: readonly string[] }\n | undefined;\n\n /**\n * Merged `dateFormats` list: `options.dateFormats ++ profile.dateFormats`\n * deduped first-occurrence per D-21. Empty array when neither source\n * supplied any formats. Exposed publicly so helpers (`msg.meta.timestamp`)\n * and advanced callers can introspect the active cascade.\n */\n public readonly dateFormats: readonly string[];\n\n /**\n * Merged `customSegments` map from the applied profile, stored so\n * `allSegments()` can hand per-segment slices to `Segment` constructors\n * (D-16). Undefined when no profile was applied.\n * @internal\n */\n private _customSegments: Readonly<Record<string, CustomSegmentDefinition>> | undefined;\n\n /**\n * Lazily built cache of Segment wrappers keyed by segment type. Built on\n * first `segments(type)` call and filtered from `_allSegments` so\n * individual Segment instances are identical across both caches (D-11).\n * Plan 04 mutation methods drop this cache wholesale.\n * @internal\n */\n private _segmentsByType: Map<string, readonly Segment[]> | undefined;\n\n /**\n * Lazily built cache of every Segment wrapper in document order. Built on\n * first `segments(type)` / `allSegments()` call. Plan 04 mutation methods\n * drop this cache wholesale.\n * @internal\n */\n private _allSegments: readonly Segment[] | undefined;\n\n /**\n * Lazily built `Meta` view (Phase 4 D-02 memoization). Dropped wholesale\n * by `invalidateCaches`. `Meta` is always defined (D-03: MSH absence\n * throws `NO_MSH_SEGMENT` at parse time) so no null-sentinel is needed.\n * @internal\n */\n private _meta: Meta | undefined;\n\n /**\n * Lazily built `MessageStructure` view (Phase G). Dropped wholesale by\n * `invalidateCaches`. Always defined: `analyzeMessageStructure` returns an\n * `recognized: false` summary for unmodelled types rather than absence.\n * @internal\n */\n private _structure: MessageStructure | undefined;\n\n /**\n * Lazily built `Patient | undefined` view (Phase 4 D-02 memoization). Uses\n * a null-sentinel cache because `undefined` means \"not yet computed\" while\n * `null` means \"computed, absent\". D-04: no PID → public value `undefined`.\n * @internal\n */\n private _patient: Patient | null | undefined;\n\n /**\n * Lazily built `Visit | undefined` view (Phase 4 D-02 memoization). Same\n * null-sentinel convention as `_patient`. HELPERS-03: no PV1 → public\n * value `undefined`.\n * @internal\n */\n private _visit: Visit | null | undefined;\n\n /**\n * Construct a new `Hl7Message`. The constructor takes a plain init\n * object and freezes the warnings array so callers cannot mutate parser\n * output after handoff.\n *\n * @internal\n */\n public constructor(init: Hl7MessageInit) {\n this.rawSegments = init.segments;\n this.encodingCharacters = init.encodingCharacters;\n this.version = init.version;\n // Freeze the warnings array at the model boundary so downstream phases\n // cannot mutate parser output after handoff. `slice()` first to avoid\n // sharing a reference the parser may still hold internally.\n this.warnings = Object.freeze(init.warnings.slice());\n // exactOptionalPropertyTypes: `init.profile` is `{...} | undefined`\n // (the optional key was omitted or the caller passed the real value).\n // The public field declares `... | undefined`, so direct assignment is\n // sound.\n this.profile = init.profile;\n // D-16: stash the merged customSegments map so allSegments() can hand\n // per-segment slices to Segment constructors. Conditional assignment\n // under exactOptionalPropertyTypes: absent key stays undefined.\n if (init.customSegments !== undefined) this._customSegments = init.customSegments;\n // D-21: merged dateFormats list (options ++ profile). Empty array when\n // neither source supplied any formats so the public field is always\n // defined (simpler consumer contract than `readonly string[] | undefined`).\n this.dateFormats = init.dateFormats ?? [];\n }\n\n /**\n * Resolve a dot-path (e.g. `PID.5.1`, `OBX[2].5`, `PID.3[0].1`) to its\n * decoded leaf string (unescaped once at parse: never re-unescaped on read,\n * HL7-VALUE-REDECODE). Returns `undefined` when the path doesn't\n * resolve: never throws on missing path (MODEL-05). Throws `TypeError`\n * on malformed path syntax (e.g. `\"pid.5\"`, empty string).\n *\n * @example\n * ```ts\n * const msg = parseHL7(raw);\n * msg.get(\"PID.5.1\"); // \"Smith\"\n * msg.get(\"OBX[2].5\"); // third OBX's 5th field\n * msg.get(\"NOT.9.9\"); // undefined\n * msg.get(\"MSH.12\"); // \"2.5\": HL7 version string\n * ```\n */\n public get(path: string): string | undefined {\n return resolvePath(path, this.rawSegments, this.encodingCharacters);\n }\n\n /**\n * Return every `Segment` of `segmentType` in document order. Returns `[]`\n * (empty array, NEVER `undefined`) when no segment of that type exists\n * (MODEL-02). Alias for `segments(segmentType)`: shares the same cache.\n *\n * @example\n * ```ts\n * for (const obx of msg.getAll(\"OBX\")) {\n * console.log(obx.field(5).value);\n * }\n * ```\n */\n public getAll(segmentType: string): readonly Segment[] {\n return this.segments(segmentType);\n }\n\n /**\n * Return the cached array of `Segment` wrappers for `segmentType` in\n * document order. The returned array identity and the individual Segment\n * instances are both stable across calls (D-11). Invalidated wholesale\n * by Plan 04 mutation methods.\n *\n * @example\n * ```ts\n * const pid = msg.segments(\"PID\")[0];\n * if (pid !== undefined) console.log(pid.field(5).value);\n * ```\n */\n public segments(segmentType: string): readonly Segment[] {\n if (this._segmentsByType === undefined) {\n this._segmentsByType = new Map();\n }\n const cached = this._segmentsByType.get(segmentType);\n if (cached !== undefined) return cached;\n\n // Build from the master `_allSegments` cache so individual Segment\n // wrappers are identical across both caches (D-11 cross-cache\n // stability). `allSegments()` builds the master cache on first call.\n const all = this.allSegments();\n const filtered: readonly Segment[] = all.filter((s) => s.type === segmentType);\n this._segmentsByType.set(segmentType, filtered);\n return filtered;\n }\n\n /**\n * Iterate every `Segment` in document order (MSH first, then every\n * subsequent segment). Cached per-message; same array reference and same\n * Segment instances on repeat calls (D-11). Invalidated wholesale by\n * Plan 04 mutation methods.\n *\n * @example\n * ```ts\n * for (const seg of msg.allSegments()) {\n * console.log(seg.type);\n * }\n * ```\n */\n public allSegments(): readonly Segment[] {\n if (this._allSegments !== undefined) return this._allSegments;\n const built: Segment[] = [];\n for (let i = 0; i < this.rawSegments.length; i++) {\n const raw = this.rawSegments[i];\n if (raw === undefined) continue;\n // D-16: hand each Segment its per-segment customFields slice so\n // `seg.get(name)` can resolve named positions. Conditional-pass under\n // exactOptionalPropertyTypes so the optional 4th ctor param stays\n // truly absent (not explicitly undefined) when no profile applied.\n const customFields = this._customSegments?.[raw.name]?.fields;\n if (customFields !== undefined) {\n built.push(new Segment(raw, this.encodingCharacters, i, customFields));\n } else {\n built.push(new Segment(raw, this.encodingCharacters, i));\n }\n }\n this._allSegments = built;\n return built;\n }\n\n /**\n * MSH-derived message metadata (type, controlId, timestamp, version, etc.).\n * D-01: plain object. D-02: memoized: `msg.meta === msg.meta` across\n * reads until mutation invalidates. D-03: always defined (MSH absence\n * throws `NO_MSH_SEGMENT` at parse time).\n *\n * @example\n * ```ts\n * console.log(msg.meta.type); // \"ADT^A01\"\n * console.log(msg.meta.timestamp?.raw); // fidelity TS (Phase N)\n * console.log(msg.meta.controlId); // \"MSG001\"\n * ```\n */\n public get meta(): Meta {\n return (this._meta ??= buildMeta(this));\n }\n\n /**\n * Structural-conformance summary for the common message types (roadmap\n * Phase G): a misroute/truncation safety net, NOT a conformance validator.\n * Reports, per the message's recognized (MSH-9.1, MSH-9.2) type, which\n * Required segment groups are present and which are entirely absent\n * (`missingGroups`: the same set the parser flags as\n * `MISSING_EXPECTED_GROUP` warnings). For an unmodelled type, `recognized`\n * is `false` and `missingGroups` is empty. D-02: memoized.\n *\n * @example\n * ```ts\n * console.log(msg.structure.recognized); // true for ORU^R01, ADT^A01, …\n * console.log(msg.structure.missingGroups); // e.g. [\"result\"] if no OBR/OBX\n * ```\n */\n public get structure(): MessageStructure {\n return (this._structure ??= buildStructure(this));\n }\n\n /**\n * PID-derived patient view, or `undefined` when no PID segment exists\n * (D-04). D-02: memoized. HELPERS-07: never throws: absent fields\n * surface as `undefined` on the returned `Patient` object.\n *\n * @example\n * ```ts\n * console.log(msg.patient?.mrn);\n * console.log(msg.patient?.fullName);\n * console.log(msg.patient?.dateOfBirth?.raw); // fidelity TS: e.g. \"19800115\"\n * ```\n */\n public get patient(): Patient | undefined {\n if (this._patient === undefined) {\n this._patient = buildPatient(this) ?? null;\n }\n return this._patient === null ? undefined : this._patient;\n }\n\n /**\n * PV1-derived visit view, or `undefined` when no PV1 segment exists\n * (HELPERS-03). D-02: memoized. HELPERS-07: never throws.\n *\n * @example\n * ```ts\n * console.log(msg.visit?.patientClass); // \"I\"\n * console.log(msg.visit?.admitDateTime?.raw); // fidelity TS\n * console.log(msg.visit?.attendingDoctor?.familyName);\n * ```\n */\n public get visit(): Visit | undefined {\n if (this._visit === undefined) {\n this._visit = buildVisit(this) ?? null;\n }\n return this._visit === null ? undefined : this._visit;\n }\n\n /**\n * Every OBX segment as a typed Observation in document order. D-05:\n * returns `[]` when no OBX present. D-06: NOT memoized: each call\n * re-walks `rawSegments`. Value type is discriminated per D-13.\n *\n * @example\n * ```ts\n * for (const obs of msg.observations()) {\n * if (obs.valueType === \"NM\") console.log(obs.value); // number | undefined\n * }\n * ```\n */\n public observations(): readonly Observation[] {\n return walkObservations(this);\n }\n\n /**\n * Every OBR as an Order with its OBX children grouped positionally (D-12) and\n * its TQ1 / legacy embedded-TQ (ORC-7) `timings` (Phase M: the repeat pattern\n * surfaced verbatim, never resolved to a schedule). D-05: returns `[]` when no\n * OBR present. D-06: not memoized.\n *\n * @example\n * ```ts\n * for (const order of msg.orders()) {\n * console.log(order.placerOrderNumber, order.observations.length);\n * for (const t of order.timings) console.log(t.repeatPattern?.code); // e.g. \"Q6H\": verbatim\n * }\n * ```\n */\n public orders(): readonly Order[] {\n return walkOrders(this);\n }\n\n /**\n * Message-level NTE notes (Phase P): every NTE segment with no recognized\n * preceding parent (not immediately following a `PID`, `ORC`, `OBR`, or\n * `OBX`), surfaced verbatim in document order so nothing is dropped. Notes\n * that DO attach to a specific patient / order / result are exposed on those\n * helper outputs (`msg.patient?.notes`, `order.notes`, `observation.notes`),\n * not here. D-05: returns `[]` when there are none. D-06: NOT memoized.\n *\n * @example\n * ```ts\n * for (const note of msg.notes()) console.log(note); // message-level narrative\n * ```\n */\n public notes(): readonly string[] {\n return walkNotes(this);\n }\n\n /**\n * Every recognized ADT patient-identity event (merge / move / link /\n * unlink / person add/update: roadmap Phase K), with the MRG-sourced\n * `prior` and PID/PV1-sourced `surviving` parties labelled by role and the\n * spec-constant `direction: \"MRG_TO_PID\"` on merge/move events. Returns\n * `[]` when the trigger event is not in the identity family. D-06: not\n * memoized. Never throws; incomplete merge pairs surface a\n * `MERGE_MISSING_PRIOR_OR_SURVIVOR` warning on the event.\n *\n * @example\n * ```ts\n * for (const ev of msg.identityEvents()) {\n * if (ev.kind === \"merge\" && ev.prior && ev.surviving) {\n * // retire ev.prior.identifiers in favour of ev.surviving.identifiers\n * }\n * }\n * ```\n */\n public identityEvents(): readonly IdentityEvent[] {\n return walkIdentityEvents(this);\n }\n\n /**\n * Every RXO/RXE/RXD/RXA as a typed `Medication`, with RXR (route) and RXC\n * (component) segments grouped positionally under their parent (Phase D,\n * P0 safety). D-05: returns `[]` when no RX* parent present. D-06: not\n * memoized. The give *amount* and give *strength* are surfaced separately\n * and never reconciled (Phase D §4).\n *\n * Each medication also carries its TQ1 / legacy embedded-TQ (RXE-1) `timings`\n * (Phase M: repeat pattern verbatim, never resolved to a schedule).\n *\n * @example\n * ```ts\n * for (const med of msg.medications()) {\n * console.log(med.context, med.giveCode?.identifier, med.giveCode?.nameOfCodingSystem);\n * console.log(med.amount?.minimum, med.strength?.value);\n * for (const t of med.timings) console.log(t.repeatPattern?.code, t.totalOccurrences);\n * }\n * ```\n */\n public medications(): readonly Medication[] {\n return walkMedications(this);\n }\n\n /**\n * Every RXA of a VXU^V04 as a typed `Immunization`, with RXR (route/site)\n * and OBX children grouped positionally under the RXA and `orderControl`\n * from the preceding ORC of the VXU order group (Phase E, P0 safety). D-05:\n * returns `[]` when no RXA present. D-06: not memoized. The vaccine code\n * carries its own provenance; the action code (RXA-21) is surfaced verbatim\n * and `recordOrigin` (administered vs historical) is derived only from the\n * well-known NIP001 RXA-9.1 codes: never guessed.\n *\n * @example\n * ```ts\n * for (const imm of msg.immunizations()) {\n * console.log(imm.vaccineCode?.identifier, imm.doseAmount, imm.recordOrigin);\n * console.log(imm.actionCode, imm.completionStatus);\n * }\n * ```\n */\n public immunizations(): readonly Immunization[] {\n return walkImmunizations(this);\n }\n\n /**\n * Every NK1 as a NextOfKin entry in document order. D-05: returns `[]`\n * when no NK1 present.\n *\n * @example\n * ```ts\n * for (const nk of msg.nextOfKin()) {\n * console.log(nk.name?.familyName, nk.relationship?.text);\n * }\n * ```\n */\n public nextOfKin(): readonly NextOfKin[] {\n return walkNextOfKin(this);\n }\n\n /**\n * Every AL1 as an Allergy in document order. D-05: returns `[]` when no\n * AL1 present.\n *\n * @example\n * ```ts\n * for (const al of msg.allergies()) console.log(al.code?.text, al.severity);\n * ```\n */\n public allergies(): readonly Allergy[] {\n return walkAllergies(this);\n }\n\n /**\n * Every DG1 as a Diagnosis in document order. D-05: returns `[]` when no\n * DG1 present.\n *\n * @example\n * ```ts\n * for (const dg of msg.diagnoses()) console.log(dg.code?.identifier);\n * ```\n */\n public diagnoses(): readonly Diagnosis[] {\n return walkDiagnoses(this);\n }\n\n /**\n * Every IN1 as an Insurance entry with positional IN2/IN3 presence flags.\n * D-05: returns `[]` when no IN1 present.\n *\n * @example\n * ```ts\n * for (const ins of msg.insurance()) console.log(ins.planId?.text);\n * ```\n */\n public insurance(): readonly Insurance[] {\n return walkInsurance(this);\n }\n\n /**\n * Every SCH of an SIU message as a typed `Appointment` (roadmap Phase Q), with\n * the AIS/AIG/AIL/AIP resource segments that follow it grouped positionally\n * under that SCH. Surfaces the placer/filler appointment ids, SCH-25 filler\n * status (Table 0278), SCH-11 start/end timing, and the resource groups\n * (service / general / location / personnel). D-05: returns `[]` when no SCH\n * is present. D-06: not memoized. Never throws (HELPERS-07). Not a\n * scheduling-workflow state machine: see the package known-limitations.\n *\n * @example\n * ```ts\n * for (const appt of msg.appointments()) {\n * console.log(appt.fillerAppointmentId, appt.fillerStatusCode?.identifier);\n * for (const r of appt.resources) console.log(r.kind, r.code?.identifier);\n * }\n * ```\n */\n public appointments(): readonly Appointment[] {\n return walkAppointments(this);\n }\n\n /**\n * Every TXA of an MDM message as a typed `ClinicalDocument` (roadmap Phase Q),\n * with the OBX narrative body grouped positionally under that TXA. The\n * completion status (TXA-17) and availability status (TXA-19) are surfaced as\n * **distinct** fields and never conflated: a document can be available before\n * it is authenticated, and reading a preliminary document as final is the\n * harm. D-05: returns `[]` when no TXA is present. D-06: not memoized. Never\n * throws (HELPERS-07).\n *\n * @example\n * ```ts\n * for (const doc of msg.documents()) {\n * console.log(doc.documentType, doc.completionStatus, doc.availabilityStatus);\n * for (const obx of doc.observations) console.log(obx.value); // narrative body\n * }\n * ```\n */\n public documents(): readonly ClinicalDocument[] {\n return walkDocuments(this);\n }\n\n /**\n * Every FT1 of a DFT message as a typed `Charge` (roadmap Phase Q), one per\n * FT1 in document order. Surfaces billing-critical fields (FT1-6 transaction\n * type, FT1-7 code, FT1-11/12 extended/unit amount, FT1-19 diagnosis linkage)\n * with **no billing logic and no money-as-float**: amounts are the verbatim\n * CP wire text. D-05: returns `[]` when no FT1 is present. D-06: not memoized.\n * Never throws (HELPERS-07).\n *\n * @example\n * ```ts\n * for (const charge of msg.charges()) {\n * console.log(charge.transactionType, charge.transactionCode?.identifier);\n * console.log(charge.amountExtended); // verbatim, never a number\n * }\n * ```\n */\n public charges(): readonly Charge[] {\n return walkCharges(this);\n }\n\n /**\n * Emit this message as spec-clean HL7 (SER-01). Re-walks `rawSegments`\n * on every call (D-30 no caching). Segments are joined with `\\r` per\n * D-05; MSH-1 and MSH-2 are inlined verbatim from\n * `this.encodingCharacters` per D-06; every field string passes through\n * `reescape` per D-04. `RawField.isNull === true` is preserved as the\n * HL7 literal `\"\"` (D-02). Pure: never warns, never throws (D-07).\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.toString()); // spec-clean, CR-separated HL7\n * ```\n */\n public toString(): string {\n return emitMessage(this);\n }\n\n /**\n * Emit this message as a structured `SerializedMessage` JSON projection\n * (SER-03). Invoked automatically by `JSON.stringify(msg)` (D-18).\n * Re-walks `rawSegments` on every call (D-30 no caching). Mirrors the\n * raw tree one-for-one, preserves `isNull`, always includes\n * `warnings: []`, and includes `profile: { name, lineage }` only when\n * `this.profile` is truthy (D-19/D-20). Pure: never warns, never throws.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * const snap = msg.toJSON();\n * console.log(snap.segments[0]?.name); // \"MSH\"\n * console.log(JSON.stringify(msg)); // same content, auto-invokes toJSON\n * ```\n */\n public toJSON(): SerializedMessage {\n return emitJson(this);\n }\n\n /**\n * Emit this message as a human-readable multi-line string for logs and\n * debugging (SER-04). Single opinionated format (D-22 no options):\n * header line with type / controlId / timestamp / segment count, then\n * one line per segment with labeled `[N]=value` fields (D-23). Composite\n * values render as their raw HL7 string: depth stops at field level\n * (D-24). Pure: never warns, never throws (D-26).\n *\n * **Field values render as their raw HL7 string representation.**\n * Embedded delimiters in user data appear as escape sequences: e.g.\n * a patient family name containing `|` renders as `Smith\\F\\Jones`\n * (NOT `Smith|Jones`). This preserves round-trip fidelity: copy-pasting\n * prettyPrint output into `parseHL7` yields a structurally equivalent\n * message. For un-escaped human display, parse the composite first via\n * typed accessors (e.g. `msg.patient?.familyName`): those return\n * already-decoded strings.\n *\n * @example\n * ```ts\n * import { parseHL7 } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * console.log(msg.prettyPrint());\n * // HL7 ADT^A01 controlId=MSG001 timestamp=2026-04-19T10:15:00Z (5 segments)\n * // MSH [3]=SENDAPP [4]=SENDFAC ...\n * // PID [1]=1 [3]=MRN123 [5]=Doe^John\n * ```\n */\n public prettyPrint(): string {\n return emitPrettyPrint(this);\n }\n\n /**\n * Set the string value at a dot-path. Mutates the underlying tree and\n * returns `this` for chaining (D-15). Auto-creates missing repetitions,\n * components, and subcomponents WITHIN an existing field, but does NOT\n * auto-create segments: callers must `addSegment` first (throws\n * `TypeError` with an actionable message otherwise).\n *\n * The value is accepted verbatim: unescaped delimiter characters are NOT\n * rejected on input (D-18). Re-escaping on serialize is Phase 5's concern.\n *\n * MSH-1 / MSH-2 follow the user-facing HL7 convention: `setField(\"MSH.3\", ...)`\n * targets MSH-3 (sending application), matching `msg.get(\"MSH.3\")`.\n *\n * Segment/Field wrapper caches are invalidated wholesale on success (D-17).\n * The frozen `warnings` array is never touched (D-16).\n *\n * @example\n * ```ts\n * msg.setField(\"PID.8\", \"F\"); // patient sex → F\n * msg.setField(\"PID.5.1\", \"Jones\"); // family name\n * msg.setField(\"PID.4[2].1\", \"MRN2\"); // create third repetition of PID-4\n * ```\n */\n public setField(path: string, value: string): this {\n // D-18: parsePath throws TypeError on malformed path.\n const parsed = parsePath(path);\n\n // Find the target segment by type + 0-indexed occurrence.\n let seen = 0;\n let segIdx = -1;\n for (let i = 0; i < this.rawSegments.length; i++) {\n const s = this.rawSegments[i];\n if (s === undefined) continue;\n if (s.name === parsed.segmentType) {\n if (seen === parsed.segmentIndex) {\n segIdx = i;\n break;\n }\n seen++;\n }\n }\n if (segIdx === -1) {\n throw new TypeError(\n `setField: segment \"${parsed.segmentType}\" (occurrence ${String(parsed.segmentIndex)}) not found. ` +\n `Add it first with addSegment(\"${parsed.segmentType}\", [...]).`,\n );\n }\n\n // MSH offset: HL7 MSH-3 lives at fields[2], MSH-12 at fields[11]. Non-MSH\n // segments keep straight 1-indexed access (fields[0] = name placeholder).\n const rawFieldIndex = parsed.segmentType === \"MSH\" ? parsed.fieldIndex - 1 : parsed.fieldIndex;\n\n // Rebuild the affected path from leaf to root, keeping every Raw* shape\n // structurally immutable. The only readonly bypass is reassigning the\n // `rawSegments` reference on `this`: per D-16, the tree is mutable\n // through the mutation API.\n const mutSegments = toMutableArray(this.rawSegments);\n const seg = mutSegments[segIdx];\n // Exhaustive guard: the index was just located above.\n if (seg === undefined) {\n throw new Error(\"setField: internal invariant, segment disappeared after lookup.\");\n }\n\n const mutFields = toMutableArray(seg.fields);\n while (mutFields.length <= rawFieldIndex) {\n mutFields.push({ repetitions: [], isNull: false });\n }\n const field = mutFields[rawFieldIndex];\n if (field === undefined) {\n throw new Error(\"setField: internal invariant, field missing after growth.\");\n }\n\n const mutReps = toMutableArray(field.repetitions);\n const repIdx = parsed.repetitionIndex ?? 0;\n while (mutReps.length <= repIdx) {\n mutReps.push({ components: [] });\n }\n const rep = mutReps[repIdx];\n if (rep === undefined) {\n throw new Error(\"setField: internal invariant, repetition missing after growth.\");\n }\n\n const mutComps = toMutableArray(rep.components);\n const compIdx = (parsed.componentIndex ?? 1) - 1;\n while (mutComps.length <= compIdx) {\n mutComps.push({ subcomponents: [] });\n }\n const comp = mutComps[compIdx];\n if (comp === undefined) {\n throw new Error(\"setField: internal invariant, component missing after growth.\");\n }\n\n const mutSubs = toMutableArray(comp.subcomponents);\n const subIdx = (parsed.subcomponentIndex ?? 1) - 1;\n while (mutSubs.length <= subIdx) {\n mutSubs.push(\"\");\n }\n mutSubs[subIdx] = value;\n\n const newComp: RawComponent = { subcomponents: mutSubs };\n mutComps[compIdx] = newComp;\n const newRep: RawRepetition = { components: mutComps };\n mutReps[repIdx] = newRep;\n const newField: RawField = { repetitions: mutReps, isNull: field.isNull };\n mutFields[rawFieldIndex] = newField;\n const newSeg: RawSegment = { name: seg.name, fields: mutFields };\n mutSegments[segIdx] = newSeg;\n\n // One readonly bypass: reassign the rawSegments reference. Consumers are\n // warned by D-16 that the tree is mutable via the mutation API.\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = mutSegments;\n\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Set a **typed composite** at a field (or field-repetition) dot-path,\n * roadmap Phase T, the conservative-emit mirror of the typed read accessors\n * (`asXpn`/`asCx`/…). The caller passes a structured value (an XPN name, a CX\n * identifier, a TS timestamp, …) by its {@link CompositeKind}, and the setter\n * encodes it into a spec-clean field using the HL7-R encode-safe path: any\n * delimiter embedded in a component value is **escaped, never injected**, so\n * a `familyName` of `\"Smith^Jr\"` re-parses to exactly that string rather than\n * forging a component boundary. No hand-assembly of `^`/`&`/`~`.\n *\n * The path must resolve to a **field** (`\"PID.5\"`) or a specific\n * **repetition** of a field (`\"PID.11[1]\"`). A component/subcomponent-level\n * path (`\"PID.5.1\"`) is rejected with `TypeError`: a composite occupies a\n * whole field, not a single component. Like {@link setField}, the target\n * segment must already exist (`addSegment` first); the repetition defaults to\n * index 0 and other repetitions of the field are preserved.\n *\n * Never fabricates: an omitted optional composite field encodes to an\n * empty/absent component, never a defaulted value; an all-empty composite\n * clears the field. Segment/helper caches are invalidated on success; the\n * frozen `warnings` array is untouched.\n *\n * @example\n * ```ts\n * const msg = buildMessage({ type: \"ADT^A01\" }).addSegment(\"PID\", [\"\"]);\n * msg.setComposite(\"PID.5\", \"XPN\", { familyName: \"Smith\", givenName: \"Ann\" });\n * msg.setComposite(\"PID.3\", \"CX\", { idNumber: \"MRN001\", identifierTypeCode: \"MR\" });\n * msg.setComposite(\"PID.7\", \"TS\", \"19880705\");\n * msg.get(\"PID.5.1\"); // \"Smith\"\n * ```\n */\n public setComposite<K extends CompositeKind>(\n path: string,\n kind: K,\n value: CompositeValueByKind[K],\n ): this {\n // parsePath throws TypeError on malformed path syntax.\n const parsed = parsePath(path);\n\n if (parsed.componentIndex !== undefined || parsed.subcomponentIndex !== undefined) {\n throw new TypeError(\n `setComposite: path \"${path}\" targets a component/subcomponent, but a typed ` +\n `composite occupies a whole field. Use a field path (e.g. \"PID.5\") or a ` +\n `field-repetition path (e.g. \"PID.11[1]\").`,\n );\n }\n\n // Locate the target segment by type + 0-indexed occurrence (same rule as\n // setField: the segment must already exist).\n let seen = 0;\n let segIdx = -1;\n for (let i = 0; i < this.rawSegments.length; i++) {\n const s = this.rawSegments[i];\n if (s === undefined) continue;\n if (s.name === parsed.segmentType) {\n if (seen === parsed.segmentIndex) {\n segIdx = i;\n break;\n }\n seen++;\n }\n }\n if (segIdx === -1) {\n throw new TypeError(\n `setComposite: segment \"${parsed.segmentType}\" (occurrence ${String(parsed.segmentIndex)}) not found. ` +\n `Add it first with addSegment(\"${parsed.segmentType}\", [...]).`,\n );\n }\n\n // Encode the typed value into a spec-clean field. The single repetition it\n // produces (or none, for an all-empty composite) is placed at repIdx.\n const encoded = encodeComposite(kind, value);\n const encodedRep: RawRepetition = encoded.repetitions[0] ?? { components: [] };\n\n const rawFieldIndex = parsed.segmentType === \"MSH\" ? parsed.fieldIndex - 1 : parsed.fieldIndex;\n\n const mutSegments = toMutableArray(this.rawSegments);\n const seg = mutSegments[segIdx];\n if (seg === undefined) {\n throw new Error(\"setComposite: internal invariant, segment disappeared after lookup.\");\n }\n\n const mutFields = toMutableArray(seg.fields);\n while (mutFields.length <= rawFieldIndex) {\n mutFields.push({ repetitions: [], isNull: false });\n }\n const field = mutFields[rawFieldIndex];\n if (field === undefined) {\n throw new Error(\"setComposite: internal invariant, field missing after growth.\");\n }\n\n const mutReps = toMutableArray(field.repetitions);\n const repIdx = parsed.repetitionIndex ?? 0;\n while (mutReps.length <= repIdx) {\n mutReps.push({ components: [] });\n }\n mutReps[repIdx] = encodedRep;\n\n const newField: RawField = { repetitions: mutReps, isNull: false };\n mutFields[rawFieldIndex] = newField;\n const newSeg: RawSegment = { name: seg.name, fields: mutFields };\n mutSegments[segIdx] = newSeg;\n\n (this as { -readonly [K2 in keyof this]: this[K2] }).rawSegments = mutSegments;\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Append a new segment to the end of the message. `name` must match\n * `/^(?:[A-Z]{3}|Z[A-Z0-9]{2})$/u`: throws `TypeError` otherwise (D-19).\n *\n * `fields` is interpreted in HL7 1-indexed terms: `addSegment(\"NTE\", [a, b, c])`\n * produces a segment whose `NTE-1 = a`, `NTE-2 = b`, `NTE-3 = c`. The\n * internal `RawSegment.fields[0]` name/separator placeholder is synthesized\n * by this method.\n *\n * Each entry may be a plain string (treated as a single-subcomponent\n * single-component single-repetition field) or a full `RawField` object\n * for advanced callers who need structured content.\n *\n * Invalidates caches on return; warnings untouched (D-16).\n *\n * @example\n * ```ts\n * msg.addSegment(\"NTE\", [\"\", \"note text\"]);\n * msg.get(\"NTE.2\"); // \"note text\"\n * ```\n */\n public addSegment(name: string, fields: readonly (string | RawField)[]): this {\n if (!SEGMENT_NAME_RE.test(name)) {\n throw new TypeError(\n `addSegment: invalid segment name \"${name}\". ` +\n `Expected 3 chars matching [A-Z][A-Z0-9]{2} (e.g. \"PID\", \"PV1\", \"OBX\", \"ZPI\").`,\n );\n }\n\n // fields[0] is the name-placeholder slot; user-supplied fields start at\n // position 1. An empty string becomes an empty field (no repetitions),\n // matching the natural HL7 \"empty field between pipes\" semantics.\n const rawFields: RawField[] = [{ repetitions: [], isNull: false }];\n for (const f of fields) {\n if (typeof f === \"string\") {\n if (f === \"\") {\n rawFields.push({ repetitions: [], isNull: false });\n } else {\n rawFields.push({\n repetitions: [{ components: [{ subcomponents: [f] }] }],\n isNull: false,\n });\n }\n } else {\n rawFields.push(f);\n }\n }\n\n const newSegment: RawSegment = { name, fields: rawFields };\n const mut = toMutableArray(this.rawSegments);\n mut.push(newSegment);\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = mut;\n\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Remove segments by type + occurrence or by type + all. Call shapes:\n *\n * - `removeSegment(\"NTE\")`: remove the FIRST NTE (occurrence 0).\n * - `removeSegment(\"OBX\", 1)`: remove the SECOND OBX (0-indexed per D-01).\n * - `removeSegment(\"OBX\", { all: true })`: remove ALL OBX segments.\n *\n * `MSH` is protected: `removeSegment(\"MSH\")` throws `TypeError` (every\n * HL7 message must retain its MSH segment). Unknown segment types are a\n * no-op (idempotent; no throw). Segment name must match the D-19 shape\n * regex: invalid shapes throw `TypeError` for symmetry with `addSegment`.\n *\n * Invalidates caches on return; warnings untouched (D-16).\n *\n * @example\n * ```ts\n * msg.removeSegment(\"NTE\"); // remove first NTE\n * msg.removeSegment(\"OBX\", 1); // remove second OBX\n * msg.removeSegment(\"OBX\", { all: true }); // remove all remaining OBX\n * ```\n */\n public removeSegment(\n segmentType: string,\n occurrenceOrOptions?: number | { readonly all?: boolean },\n ): this {\n if (!SEGMENT_NAME_RE.test(segmentType)) {\n throw new TypeError(\n `removeSegment: invalid segment name \"${segmentType}\". ` +\n `Expected 3 chars matching [A-Z][A-Z0-9]{2} (e.g. \"PID\", \"PV1\", \"OBX\", \"ZPI\").`,\n );\n }\n if (segmentType === \"MSH\") {\n throw new TypeError(\n `removeSegment: refusing to remove MSH (every HL7 message must have exactly one MSH segment).`,\n );\n }\n\n const all = typeof occurrenceOrOptions === \"object\" && occurrenceOrOptions.all === true;\n const targetOccurrence = typeof occurrenceOrOptions === \"number\" ? occurrenceOrOptions : 0;\n\n const mut = toMutableArray(this.rawSegments);\n if (all) {\n const filtered = mut.filter((s) => s.name !== segmentType);\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = filtered;\n } else {\n let seen = 0;\n let removeAt = -1;\n for (let i = 0; i < mut.length; i++) {\n const s = mut[i];\n if (s === undefined) continue;\n if (s.name === segmentType) {\n if (seen === targetOccurrence) {\n removeAt = i;\n break;\n }\n seen++;\n }\n }\n if (removeAt !== -1) {\n mut.splice(removeAt, 1);\n (this as { -readonly [K in keyof this]: this[K] }).rawSegments = mut;\n }\n // else: no-op: unknown segment type or occurrence out of range.\n }\n\n this.invalidateCaches();\n return this;\n }\n\n /**\n * Drop every wrapper AND helper cache wholesale (Phase 3 D-17 + Phase 4\n * D-02). Called by every mutation method so subsequent `segments(type)` /\n * `allSegments()` / `meta` / `patient` / `visit` reads rebuild from the\n * mutated `rawSegments` tree.\n * @internal\n */\n private invalidateCaches(): void {\n this._segmentsByType = undefined;\n this._allSegments = undefined;\n this._meta = undefined;\n this._structure = undefined;\n this._patient = undefined;\n this._visit = undefined;\n }\n}\n","/**\n * Process-scoped default profile management (PROF-08 / D-18). This module\n * holds the first mutable module-scoped state in the codebase: an\n * intentional trade-off documented in PROJECT.md Key Decisions:\n * `setDefaultProfile` EXISTS but is DISCOURAGED. It is scoped to the\n * current Node process, NOT shared across workers, NOT a symbol-keyed\n * globalThis registry, and NOT reset between test files automatically.\n *\n * Tests that touch the default profile MUST clean up in `afterEach` /\n * `afterAll` (`setDefaultProfile(null)`) to prevent cross-test bleed.\n *\n * Zero runtime deps. Single `let` variable; no class, no registry object,\n * no magic.\n */\n\nimport type { Profile } from \"../parser/types.js\";\n\n/**\n * Process-scoped default profile. `undefined` means \"unset\" (the initial\n * state). `null` is not a stable stored value: `setDefaultProfile(null)`\n * resets this to `undefined` per D-18.\n * @internal\n */\nlet _defaultProfile: Profile | undefined = undefined;\n\n/**\n * Register a process-scoped default profile. `parseHL7(raw)` (with no\n * explicit profile arg) consults `getDefaultProfile()` and applies the\n * returned profile if any. Pass `null` (or `undefined`) to clear.\n *\n * Effects are IDENTICAL to passing the profile explicitly as the second\n * arg of `parseHL7` (D-20): customSegments, dateFormats, onWarning chain,\n * and profile attribution all apply the same way.\n *\n * Explicit args ALWAYS win: `parseHL7(raw, myProfile)` uses `myProfile`\n * regardless of the default; `parseHL7(raw, { profile: null })` opts out\n * of the default for a single call without changing the registered\n * default.\n *\n * **Test hygiene:** This is the ONLY mutable module-scoped state in the\n * library. Tests that call `setDefaultProfile` MUST clean up in\n * `afterEach` (`setDefaultProfile(null)`) or default-profile bleed will\n * infect subsequent tests.\n *\n * @example\n * ```ts\n * import { setDefaultProfile, profiles, parseHL7 } from \"@cosyte/hl7\";\n *\n * // Set once at app startup\n * setDefaultProfile(profiles.epic);\n *\n * // Every parseHL7 call in the app now uses profiles.epic unless\n * // another profile is passed explicitly.\n * const msg = parseHL7(raw);\n * console.log(msg.profile?.name); // \"epic\"\n *\n * // Clear when done (or in test teardown):\n * setDefaultProfile(null);\n * ```\n */\nexport function setDefaultProfile(profile: Profile | null): void {\n // Accept `undefined` defensively: TypeScript narrows to `Profile | null`,\n // but a JS caller may pass `undefined`. Treat it like null (clear).\n _defaultProfile = profile ?? undefined;\n}\n\n/**\n * Return the current default profile, or `undefined` if none is\n * registered. Consistent with `msg.profile` convention: `undefined`\n * rather than `null`.\n *\n * @example\n * ```ts\n * import { getDefaultProfile } from \"@cosyte/hl7\";\n * const p = getDefaultProfile();\n * if (p !== undefined) console.log(\"default profile:\", p.name);\n * ```\n */\nexport function getDefaultProfile(): Profile | undefined {\n return _defaultProfile;\n}\n","/**\n * Public entry point for the `@cosyte/hl7` parser: composes every\n * parser stage built across Plans 01–05 (normalize, strip MLLP, split\n * segments, read delimiters, tokenize) and routes every Tier-2 warning\n * through a single `emitWarning` chokepoint. The four Tier-3 fatal codes\n * (`EMPTY_INPUT`, `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`,\n * `INVALID_ENCODING_CHARACTERS`) are thrown even in lenient mode; every\n * other recoverable deviation is a warning unless `{ strict: true }` is\n * passed.\n *\n * Pipeline order (locked by CONTEXT.md D-03): Buffer decode → EMPTY_INPUT\n * check → BOM strip → MLLP strip → re-check EMPTY_INPUT → line-ending\n * normalize → emitter build → MLLP warning → segment split → delimiter\n * discovery → tokenize → version extract → Hl7Message construct.\n */\n\nimport type { Buffer } from \"node:buffer\";\n\nimport { DEFAULT_ENCODING_CHARACTERS, readDelimiters } from \"./delimiters.js\";\nimport { FATAL_CODES, Hl7ParseError } from \"./errors.js\";\nimport { KNOWN_SEGMENTS } from \"./known-segments.js\";\nimport { emitIfFramed, stripMllp } from \"./mllp.js\";\nimport { canonicalCharset } from \"./charset.js\";\nimport { normalize, normalizeBuffer } from \"./normalize.js\";\nimport { snippet as segmentSnippet, splitSegments } from \"./segments.js\";\nimport { tokenize } from \"./tokenize.js\";\nimport { analyzeMessageStructure } from \"./message-structure.js\";\nimport { encodingMismatch, missingExpectedGroup, unknownSegment } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\nimport type {\n CustomSegmentDefinition,\n Hl7Position,\n ParseOptions,\n Profile,\n RawSegment,\n} from \"./types.js\";\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { getDefaultProfile } from \"../profiles/default.js\";\n\n/**\n * The list of `ParseOptions` keys that are TRULY options-only: i.e. keys\n * that appear on `ParseOptions` but NOT on `Profile`. Used by\n * `discriminateOptionsOrProfile` to decide whether an anonymous second\n * argument is a `ParseOptions` (has at least one of these keys) or a\n * `Profile` (no options-only key, has a string `name`).\n *\n * Deliberately EXCLUDES `onWarning` and `dateFormats` even though they're\n * valid `ParseOptions` keys: those two also appear on `Profile` (Profile\n * carries `onWarning`/`dateFormats` fields), so checking for them would\n * mis-classify a `defineProfile()` output (which always has `dateFormats`,\n * even as `[]`) as a `ParseOptions` when a caller passes it as the second\n * arg. The subset below is the precise \"disambiguates options from\n * profile\" witness set: every key here is options-only.\n *\n * @internal\n */\nconst OPTIONS_ONLY_KEYS: readonly (keyof ParseOptions)[] = [\n \"strict\",\n \"stripMllpFraming\",\n \"trimFields\",\n \"profile\",\n \"charset\",\n];\n\n/**\n * Discriminate the optional second argument of `parseHL7` per CONTEXT.md\n * D-06. `undefined` → empty options. A bare `Profile` (object with\n * `name: string` and none of the options-only keys) → wrapped into\n * `{ profile }`. Anything else with an options-only key wins the\n * `ParseOptions` branch (even when it also has a `name` field) so callers\n * who pass `{ name: \"epic\", strict: true }` get options semantics.\n *\n * Uses `Object.prototype.hasOwnProperty.call` rather than the `in`\n * operator so a prototype-polluted object cannot trip the options-only\n * branch by inheriting a `strict` / `onWarning` key (T-02-06-01).\n *\n * @internal\n */\nfunction discriminateOptionsOrProfile(arg: ParseOptions | Profile | undefined): ParseOptions {\n if (arg === undefined) return {};\n // A Profile is REQUIRED to have `name: string` (parser/types.ts locked\n // interface). Any arg without a string `name` is therefore unambiguously\n // ParseOptions: including bare option bags like `{ onWarning }` or\n // `{ dateFormats }` whose keys overlap with Profile but whose shape\n // lacks the required `name` witness.\n const hasStringName = typeof (arg as { name?: unknown }).name === \"string\";\n if (!hasStringName) {\n return arg;\n }\n // Arg has a string `name`. Check for TRULY options-only keys (keys that\n // cannot appear on a Profile) to decide whether the caller intended\n // options with a rogue `name` field (e.g. `{ name: \"x\", strict: true }`)\n // vs a real Profile. Uses hasOwnProperty.call against prototype\n // pollution per T-02-06-01.\n const hasOptionsOnlyKey = OPTIONS_ONLY_KEYS.some((k) =>\n Object.prototype.hasOwnProperty.call(arg, k),\n );\n if (hasOptionsOnlyKey) {\n return arg;\n }\n return { profile: arg as Profile };\n}\n\n/**\n * Build the single `emit` chokepoint passed into every parser stage per\n * CONTEXT.md D-11. Lenient mode: push the warning to the accumulator\n * array, invoke `effectiveProfile?.onWarning` FIRST (D-22) inside its own\n * try/catch so handler throws are swallowed silently, THEN invoke\n * `options.onWarning` inside its own try/catch (consistency with the\n * profile chain so a noisy caller handler cannot break the parser).\n * Strict mode: throw an `Hl7ParseError` whose `code` carries the warning\n * code; neither onWarning handler fires (preserves the existing\n * lenient-vs-strict split from Phase 2).\n *\n * D-22 ordering: profile handlers are observers that run FIRST; caller\n * handler runs LAST. Preserves the \"profile behavior, then caller\n * behavior\" layering pattern: the profile sees warnings as they arise;\n * the caller's handler sees post-profile-handler warnings (same object,\n * same time, just guaranteed ordering).\n *\n * @remarks\n * Under strict mode the thrown error's `code` is a `WarningCode` string\n * which is NOT in `FATAL_CODES`. This intentionally widens the runtime\n * set of values `Hl7ParseError.code` can take without widening the\n * compile-time type: consumers narrow on `err.code` after catching.\n * See the `as unknown as` comment in the implementation for the\n * justification (Plan 06 decision (b)).\n *\n * @internal\n */\nfunction makeEmitter(\n warnings: Hl7ParseWarning[],\n options: ParseOptions,\n input: string,\n effectiveProfile: Profile | undefined,\n): (w: Hl7ParseWarning) => void {\n return (w) => {\n if (options.strict === true) {\n // Justification for `as unknown as FatalCode`: strict mode escalates\n // Tier-2 warnings into thrown `Hl7ParseError`s per TOL-01. The thrown\n // error reuses the existing error shape (code / message / position /\n // snippet) so consumers have one catch surface. The `code` field is\n // typed as `FatalCode` (the 4 Tier-3 codes) at compile time, but at\n // runtime under strict mode it also carries any `WarningCode`. We\n // preserve the narrow compile-time type so lenient-mode callers get\n // exhaustive-switch checks on `FatalCode`; strict-mode consumers\n // narrow on the runtime string. Alternative (a): widening\n // FatalCode: would leak strict-mode semantics into the lenient-mode\n // type surface; alternative (c), a separate Hl7StrictError class,\n // would introduce a third error class. (b) is the minimum-surface\n // change and matches Plan 06's recommendation.\n throw new Hl7ParseError(\n w.code as unknown as (typeof FATAL_CODES)[keyof typeof FATAL_CODES],\n w.message,\n w.position,\n buildSnippet(input, w.position),\n );\n }\n warnings.push(w);\n // D-22: profile.onWarning fires BEFORE options.onWarning. Each call is\n // wrapped in its own try/catch so a throw in one handler cannot prevent\n // the other from receiving the warning, and cannot bubble out of the\n // parser (consistent with the D-12 silent-swallow contract for the\n // profile-chain composer). Symmetric treatment of options.onWarning\n // keeps the contract uniform: a noisy caller handler is as contained\n // as a noisy profile handler.\n if (effectiveProfile?.onWarning !== undefined) {\n try {\n effectiveProfile.onWarning(w);\n } catch {\n /* D-22 silent swallow */\n }\n }\n if (options.onWarning !== undefined) {\n try {\n options.onWarning(w);\n } catch {\n /* D-22 symmetric silent swallow */\n }\n }\n };\n}\n\n/**\n * Build a bounded snippet of the input for attaching to a strict-mode\n * `Hl7ParseError`. Phase 2 does not track character offsets: positions\n * are segment/field/component indices: so we return a leading excerpt\n * of the input bounded by `segments.snippet`.\n *\n * @internal\n */\nfunction buildSnippet(input: string, _position: Hl7Position): string {\n return segmentSnippet(input.slice(0, 80));\n}\n\n/**\n * Shallow MSH-18 extractor for the tentative-decode first pass of Buffer\n * charset resolution. Deliberately avoids calling `readDelimiters` or\n * `tokenize`: those can throw on malformed MSH, which would defeat the\n * \"tentative\" contract of the first pass.\n *\n * Line-ending agnostic: splits on `/[\\r\\n]/` so a Buffer that uses Unix\n * (`\\n`), classic Mac (`\\r`), or mixed line endings still isolates segment\n * 0 correctly. A bare split on `\\r` alone here would silently regress\n * PARSE-09 on `\\n`-only Buffer traffic (the whole message would become\n * segment 0, `parts[17]` would swallow subsequent segments, and the\n * charset token would become a garbage string that falls through to\n * UTF-8).\n *\n * MSH-18 is a **repeating** field (HL7 v2 Ch. 2): the **first** occurrence is\n * the message's default encoding; later occurrences are alternates activated\n * mid-message by the charset-switch escapes. Only the first repetition governs\n * the whole-buffer decode, so this returns it: split on the message's own\n * repetition separator (MSH-2 char 2, default `~`).\n *\n * Returns the trimmed first MSH-18 repetition, or `undefined` on any failure\n * (no segment boundary, segment not `MSH`, `parts[17]` missing or empty). The\n * caller applies the ASCII default on `undefined`.\n *\n * @internal\n */\nfunction extractMsh18FromTentativeDecode(tentativeText: string): string | undefined {\n const firstSegment = tentativeText.split(/[\\r\\n]/)[0];\n if (firstSegment === undefined) return undefined;\n if (!firstSegment.startsWith(\"MSH\")) return undefined;\n // HL7 field-separator character is at index 3 of the MSH segment (after\n // the three-letter segment name).\n const fieldSep = firstSegment.charAt(3);\n if (fieldSep === \"\") return undefined;\n const parts = firstSegment.split(fieldSep);\n // Per the unified 1-indexed convention: parts[0] = \"MSH\", parts[1] =\n // encoding characters (MSH-2 = `^~\\&`), ..., parts[17] = MSH-18.\n const raw = parts[17];\n if (raw === undefined) return undefined;\n // Repetition separator = MSH-2 character 2 (0-indexed 1); default `~` when\n // MSH-2 is short/malformed. Take the first repetition = the message default.\n const repSep = (parts[1] ?? \"\").charAt(1) || \"~\";\n const firstRep = raw.split(repSep)[0] ?? raw;\n const trimmed = firstRep.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Resolve the effective charset for a `Buffer` input and return the\n * decoded, line-ending-normalized text. Implements the locked precedence\n * rule (design decision (c)):\n *\n * 1. If `options.charset` is supplied AND MSH-18 is declared, emit\n * `ENCODING_MISMATCH` when they disagree after canonicalization;\n * always honour the override.\n * 2. Else if `options.charset` is supplied, use it.\n * 3. Else if MSH-18 is declared, use it (a recognized-but-undecoded set\n * trips `UNSUPPORTED_CHARSET`, an unrecognized label `UNKNOWN_CHARSET`,\n * both preserving bytes verbatim inside `normalizeBuffer`).\n * 4. Else fall through to `normalizeBuffer`'s ASCII default (decoded as its\n * UTF-8 superset), which emits nothing.\n *\n * Two-pass mechanics: MSH-1 through MSH-18 are always 7-bit ASCII in real\n * HL7 traffic, so a tentative UTF-8 decode reliably surfaces MSH-18 even\n * when the payload declares a non-UTF-8 charset. The second pass\n * (`normalizeBuffer`) re-decodes with the resolved charset.\n *\n * @internal\n */\nfunction resolveBufferCharset(\n raw: Buffer,\n options: ParseOptions,\n emit: (w: Hl7ParseWarning) => void,\n): string {\n const override = options.charset;\n // Pass 1: tentative UTF-8 decode to read MSH-18. This is cheap: for\n // UTF-8 payloads the tentative decode is exactly what `normalizeBuffer`\n // would produce anyway; for non-UTF-8 payloads the MSH header bytes are\n // ASCII so MSH-18 still surfaces correctly even if the body garbles.\n const tentative = new TextDecoder(\"utf-8\").decode(raw);\n const declared = extractMsh18FromTentativeDecode(tentative);\n\n if (override !== undefined && declared !== undefined) {\n const overrideNorm = canonicalCharset(override);\n const declaredNorm = canonicalCharset(declared);\n if (overrideNorm !== declaredNorm) {\n emit(\n encodingMismatch(\n { segmentIndex: 0 },\n `options.charset=\"${override}\" disagrees with MSH-18=\"${declared}\"`,\n ),\n );\n }\n return normalizeBuffer(raw, override, emit);\n }\n if (override !== undefined) {\n return normalizeBuffer(raw, override, emit);\n }\n if (declared !== undefined) {\n return normalizeBuffer(raw, declared, emit);\n }\n return normalizeBuffer(raw, undefined, emit);\n}\n\n/**\n * Read MSH-12 (version) from the first tokenized segment. Per the unified\n * HL7 1-indexed convention locked in Plan 03, `fields[0]` is the\n * separator/name placeholder, `fields[1]` is MSH-2 (encoding chars),\n * `fields[11]` is MSH-12 (version). Returns the empty string when the\n * first segment is absent, not an MSH, or MSH-12 has no content: the\n * `noUncheckedIndexedAccess` strictness flag forces every intermediate\n * index guard to be explicit.\n *\n * @internal\n */\nfunction extractVersion(msh: RawSegment | undefined): string {\n if (msh === undefined || msh.name !== \"MSH\") return \"\";\n const versionField = msh.fields[11];\n if (versionField === undefined) return \"\";\n const firstRep = versionField.repetitions[0];\n if (firstRep === undefined) return \"\";\n const firstComp = firstRep.components[0];\n if (firstComp === undefined) return \"\";\n const firstSub = firstComp.subcomponents[0];\n return firstSub ?? \"\";\n}\n\n/**\n * Read MSH-9.1 (message code) and MSH-9.2 (trigger event) from the first\n * tokenized segment for the Phase G structure safety net. MSH-9 is\n * `fields[8]` under the unified 1-indexed convention (`fields[0]` is the\n * name/separator placeholder). Returns empty strings when the first segment is\n * absent, not an MSH, or the components have no content: every intermediate\n * index guard is explicit under `noUncheckedIndexedAccess`.\n *\n * @internal\n */\nfunction extractMessageType(msh: RawSegment | undefined): {\n readonly messageCode: string;\n readonly triggerEvent: string;\n} {\n if (msh === undefined || msh.name !== \"MSH\") return { messageCode: \"\", triggerEvent: \"\" };\n const typeField = msh.fields[8];\n if (typeField === undefined) return { messageCode: \"\", triggerEvent: \"\" };\n const firstRep = typeField.repetitions[0];\n if (firstRep === undefined) return { messageCode: \"\", triggerEvent: \"\" };\n const messageCode = firstRep.components[0]?.subcomponents[0] ?? \"\";\n const triggerEvent = firstRep.components[1]?.subcomponents[0] ?? \"\";\n return { messageCode, triggerEvent };\n}\n\n/**\n * Parse a raw HL7 v2 message (string or `Buffer`) into an `Hl7Message`.\n * The parser is lenient by default: recoverable deviations from the HL7\n * spec are reported via `msg.warnings` and (optionally)\n * `options.onWarning` but do not throw. Four unrecoverable structural\n * errors throw `Hl7ParseError`: `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`,\n * `INVALID_ENCODING_CHARACTERS`, `EMPTY_INPUT`. Opt into strict mode\n * with `{ strict: true }` to escalate every Tier-2 warning into an\n * `Hl7ParseError`.\n *\n * @example\n * ```ts\n * import { parseHL7, WARNING_CODES } from \"@cosyte/hl7\";\n *\n * const msg = parseHL7(\n * \"MSH|^~\\\\&|APP|FAC|APP|FAC|20250101||ADT^A01|1|P|2.5\\rPID|||123\",\n * );\n * console.log(msg.version); // \"2.5\"\n * console.log(msg.warnings.length); // 0\n * for (const w of msg.warnings) {\n * if (w.code === WARNING_CODES.MLLP_FRAMING_STRIPPED) {\n * // handle MLLP-framed sender\n * }\n * }\n * ```\n */\nexport function parseHL7(raw: string | Buffer): Hl7Message;\nexport function parseHL7(raw: string | Buffer, profile: Profile): Hl7Message;\nexport function parseHL7(raw: string | Buffer, options: ParseOptions): Hl7Message;\n/** @internal implementation signature; overload signatures above carry the public JSDoc + @example. */\nexport function parseHL7(\n raw: string | Buffer,\n optionsOrProfile?: ParseOptions | Profile,\n): Hl7Message {\n const options = discriminateOptionsOrProfile(optionsOrProfile);\n const warnings: Hl7ParseWarning[] = [];\n\n // Step 1: Buffer → string decode (if needed). UNKNOWN_CHARSET warnings\n // captured here are forwarded through the real emitter after the\n // fatal checks pass.\n const bufferWarnings: Hl7ParseWarning[] = [];\n const bufferEmit = (w: Hl7ParseWarning): void => {\n bufferWarnings.push(w);\n };\n let text: string;\n if (typeof raw === \"string\") {\n text = raw;\n } else {\n text = resolveBufferCharset(raw, options, bufferEmit);\n }\n\n // Step 2: EMPTY_INPUT fatal check at the top of the pipeline (D-03).\n if (text.length === 0) {\n throw new Hl7ParseError(FATAL_CODES.EMPTY_INPUT, \"Input is empty.\", { segmentIndex: 0 }, \"\");\n }\n\n // Step 3: Strip UTF-8 BOM silently (Tier-1; no warning).\n if (text.charCodeAt(0) === 0xfeff) {\n text = text.slice(1);\n }\n\n // Step 4: Strip MLLP framing bytes. Even if `stripMllpFraming` is\n // disabled we still strip: leaving VT/FS in the buffer would corrupt\n // segment splitting: but we suppress the warning in that case.\n const mllpResult = stripMllp(text);\n text = mllpResult.stripped;\n\n // Step 5: Re-check EMPTY_INPUT: MLLP strip may have emptied the payload.\n if (text.length === 0) {\n throw new Hl7ParseError(\n FATAL_CODES.EMPTY_INPUT,\n \"Input is empty after MLLP framing was stripped.\",\n { segmentIndex: 0 },\n \"\",\n );\n }\n\n // Step 6: Normalize line endings to `\\r` (Tier-1 silent).\n const inputForPipeline = normalize(text);\n\n // Step 6.5 (Plan 04 extends): Resolve effectiveProfile BEFORE makeEmitter\n // so the D-22 onWarning chain is wired from the VERY FIRST emission\n // (Buffer-decode warnings in Step 7 replay included). Plan 04 extends\n // Plan 03's single-line assignment into a 3-branch discrimination per\n // D-19 \"explicit wins; null opts out; undefined falls back to default\":\n // - options.profile === null → explicit opt-out for this call (D-19).\n // Registered default is IGNORED; msg.profile === undefined.\n // - options.profile !== undefined → explicit Profile wins over any\n // registered default.\n // - options.profile === undefined → fall back to the registered default\n // via getDefaultProfile() (which may itself be undefined, in which\n // case effectiveProfile stays undefined and parseHL7 behaves exactly\n // like the no-profile case: zero semantic change for unregistered\n // consumers).\n let effectiveProfile: Profile | undefined;\n if (options.profile === null) {\n effectiveProfile = undefined;\n } else if (options.profile !== undefined) {\n effectiveProfile = options.profile;\n } else {\n effectiveProfile = getDefaultProfile();\n }\n\n // Step 7: All Tier-3 fatals are past. Build the real emitter (now\n // profile-aware per D-22) and forward any warnings captured during the\n // Buffer decode. Buffer-decode warnings route through BOTH profile and\n // options handlers: full fidelity from the first warning onwards.\n const emit = makeEmitter(warnings, options, inputForPipeline, effectiveProfile);\n for (const pre of bufferWarnings) emit(pre);\n\n // Step 8: MLLP framing warning (Tier-2): fired AFTER the fatal checks\n // so `EMPTY_INPUT` always takes precedence over\n // `MLLP_FRAMING_STRIPPED` (D-03 ordering).\n if ((options.stripMllpFraming ?? true) === true) {\n emitIfFramed(mllpResult, emit, { segmentIndex: 0 });\n }\n\n // Step 9: Segment split.\n const segments = splitSegments(inputForPipeline);\n if (segments.length === 0) {\n // Defensive: splitSegments returning [] implies empty input, which the\n // earlier EMPTY_INPUT checks would have caught. Fall through with a\n // NO_MSH_SEGMENT fatal so the invariant \"first segment exists\" holds.\n throw new Hl7ParseError(\n FATAL_CODES.NO_MSH_SEGMENT,\n \"No segments found after normalization.\",\n { segmentIndex: 0 },\n \"\",\n );\n }\n\n // Step 10: Delimiter discovery (may throw NO_MSH_SEGMENT / MSH_TOO_SHORT\n // / INVALID_ENCODING_CHARACTERS).\n const firstSegment = segments[0] ?? \"\";\n const encoding = readDelimiters(firstSegment);\n\n // Step 11: Tokenize (may emit FIELD_WHITESPACE_TRIMMED).\n const rawSegments: readonly RawSegment[] = tokenize(\n segments,\n encoding,\n emit,\n options.trimFields ?? true,\n );\n\n // Step 11.5: Emit UNKNOWN_SEGMENT for any non-standard segment name that\n // is not declared in the active profile (D-31). Uses the already-resolved\n // effectiveProfile for customSegments suppression. O(N): one Set.has +\n // one hasOwnProperty per segment. Uses Object.prototype.hasOwnProperty.call\n // to guard against prototype pollution (matches the T-02-06-01 mitigation\n // in discriminateOptionsOrProfile).\n const profileCustomSegments = effectiveProfile?.customSegments;\n for (let segIdx = 0; segIdx < rawSegments.length; segIdx++) {\n const rawSeg = rawSegments[segIdx];\n if (rawSeg === undefined) continue;\n const isKnown = KNOWN_SEGMENTS.has(rawSeg.name);\n const isProfileClaimed =\n profileCustomSegments !== undefined &&\n Object.prototype.hasOwnProperty.call(profileCustomSegments, rawSeg.name);\n if (!isKnown && !isProfileClaimed) {\n emit(unknownSegment({ segmentIndex: segIdx }, rawSeg.name));\n }\n }\n\n // Step 11.6 (Phase G): structural-conformance safety net. For the common\n // message types the registry recognizes, warn ADDITIVELY when an expected\n // Required segment group is entirely absent (e.g. ORU^R01 with no OBR/OBX),\n // the signature of a truncated or misrouted feed. Warning-only (Tier-2);\n // lenient parse never throws, `strict` may promote via the emitter. The\n // warning carries only structural facts (type, group, anchor names): never\n // a field value, so no PHI is exposed. Conservative by construction: an\n // unrecognized type yields no expected groups and emits nothing.\n const { messageCode, triggerEvent } = extractMessageType(rawSegments[0]);\n if (messageCode !== \"\") {\n const presentSegmentNames = new Set<string>();\n for (const seg of rawSegments) {\n if (seg !== undefined) presentSegmentNames.add(seg.name);\n }\n const structure = analyzeMessageStructure(messageCode, triggerEvent, presentSegmentNames);\n const messageType = triggerEvent !== \"\" ? `${messageCode}^${triggerEvent}` : messageCode;\n for (const group of structure.expectedGroups) {\n if (!group.present) {\n emit(\n missingExpectedGroup(\n { segmentIndex: 0, fieldIndex: 9 },\n messageType,\n group.name,\n group.anchorSegments,\n ),\n );\n }\n }\n }\n\n // Step 12: Version extraction: Phase 4 extends this via msg.meta.\n const version = extractVersion(rawSegments[0]);\n\n // Step 13: Profile attribution + merged customSegments / dateFormats for\n // Hl7Message init. Step 13 is a CONSUMER of the already-resolved\n // effectiveProfile (resolution moved to Step 6.5 per Plan 03 Option A).\n const profileInit =\n effectiveProfile !== undefined\n ? {\n name: effectiveProfile.name,\n lineage: effectiveProfile.lineage ?? [effectiveProfile.name],\n }\n : undefined;\n\n // D-21: options.dateFormats precede profile.dateFormats in the try-order.\n // Dedupe preserving first occurrence. `mergedDateFormats` stays undefined\n // when neither source supplied any formats so the Hl7MessageInit omission\n // discipline (exactOptionalPropertyTypes) is honoured.\n const optionFormats = options.dateFormats ?? [];\n const profileFormats = effectiveProfile?.dateFormats ?? [];\n const mergedFormats: string[] = [];\n const seenFormats = new Set<string>();\n for (const f of optionFormats) {\n if (!seenFormats.has(f)) {\n seenFormats.add(f);\n mergedFormats.push(f);\n }\n }\n for (const f of profileFormats) {\n if (!seenFormats.has(f)) {\n seenFormats.add(f);\n mergedFormats.push(f);\n }\n }\n const mergedDateFormats: readonly string[] | undefined =\n mergedFormats.length > 0 ? Object.freeze(mergedFormats) : undefined;\n\n const mergedCustomSegments = effectiveProfile?.customSegments;\n\n // exactOptionalPropertyTypes: conditionally assign each optional init key.\n type Init = {\n segments: readonly RawSegment[];\n encodingCharacters: typeof encoding;\n version: string;\n warnings: readonly Hl7ParseWarning[];\n profile?: { readonly name: string; readonly lineage: readonly string[] };\n customSegments?: Readonly<Record<string, CustomSegmentDefinition>>;\n dateFormats?: readonly string[];\n };\n const init: Init = {\n segments: rawSegments,\n encodingCharacters: encoding,\n version,\n warnings,\n };\n if (profileInit !== undefined) init.profile = profileInit;\n if (mergedCustomSegments !== undefined) init.customSegments = mergedCustomSegments;\n if (mergedDateFormats !== undefined) init.dateFormats = mergedDateFormats;\n\n return new Hl7Message(init);\n}\n\n// Re-export DEFAULT_ENCODING_CHARACTERS so consumers who need it do not\n// have to reach into `./delimiters.js`.\nexport { DEFAULT_ENCODING_CHARACTERS };\n","/**\n * First-class HL7 v2 text codec for `@cosyte/hl7`: the ergonomic\n * decode / encode pair that sits on top of the parser-internal\n * `unescape` / `reescape` primitives.\n *\n * - {@link decodeText} turns a field's escape-bearing wire text into its\n * decoded value (delimiter + hex + `\\.br\\` escapes resolved; presentational\n * escapes preserved verbatim), with no warning plumbing to wire up.\n * - {@link encodeText} is the **encode-safe** direction: an arbitrary string in,\n * a spec-clean field body out that can **never inject a delimiter or forge a\n * component boundary**. This is the primitive Phase T (typed emit) builds on.\n *\n * For a human-readable rendering (formatting commands → whitespace, highlight\n * dropped), use {@link renderText} instead of {@link decodeText}.\n */\n\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport { reescape, unescape } from \"../parser/escapes.js\";\nimport type { EncodingCharacters } from \"../parser/types.js\";\n\n/** No-op warning sink for the codec's decode direction. @internal */\nfunction ignore(): void {\n /* decode warnings are informational; the decoded string preserves unknown\n * escapes verbatim regardless, so the ergonomic codec drops them. */\n}\n\n/**\n * Decode a field's escape-bearing HL7 text to its human value: the five\n * delimiter escapes (`\\F\\ \\S\\ \\T\\ \\R\\ \\E\\`), the truncation escape (`\\P\\`),\n * `\\.br\\` (→ newline), and hex (`\\Xdddd…\\`) are resolved; presentational\n * escapes (`\\H\\`/`\\N\\`, formatting, charset, vendor `\\Z..\\`) are **preserved\n * verbatim** so nothing is lost. Never throws.\n *\n * This is the one-call inverse of {@link encodeText} for delimiter-bearing\n * content. It does **not** interpret formatting/highlight: for a normalized\n * display string use {@link renderText}.\n *\n * @param input - the field's escape-bearing text.\n * @param enc - encoding characters; defaults to the HL7 standard `|^~\\&`.\n * @returns the decoded value string.\n *\n * @example\n * ```ts\n * import { decodeText } from \"@cosyte/hl7\";\n * decodeText(\"Doe\\\\S\\\\John\"); // \"Doe^John\": \\S\\ → component separator\n * decodeText(\"line1\\\\.br\\\\line2\"); // \"line1\\nline2\"\n * ```\n */\nexport function decodeText(\n input: string,\n enc: EncodingCharacters = DEFAULT_ENCODING_CHARACTERS,\n): string {\n return unescape(input, enc, ignore, { segmentIndex: 0 });\n}\n\n/**\n * **Encode-safe** direction: escape an arbitrary string so it can be placed in\n * an HL7 field as data without ever breaking framing. Every reserved character\n *: the escape char (escaped **first**, so decoding is unambiguous), the field,\n * component, subcomponent, and repetition separators, the declared truncation\n * char, and the framing-critical `\\n`/`\\r`: is replaced by its escape\n * sequence, so the value **cannot inject a delimiter or forge a component /\n * subcomponent / repetition boundary**.\n *\n * The hard invariant, property-tested over arbitrary strings:\n * `decodeText(encodeText(s, enc), enc) === s`, and a message field carrying\n * `encodeText(s)` **cannot forge a component / subcomponent / repetition\n * boundary or break framing**: the value never escapes its field.\n *\n * Two caveats are inherent to HL7 field encoding, not to this codec, and apply\n * to *whole-field* re-parse (they do not weaken the no-injection guarantee):\n * the two-character string `\"\"` is HL7's explicit-null token, so a field whose\n * entire value is `\"\"` re-parses as null; and the default parser trims field\n * whitespace, so a value with leading/trailing spaces re-parses trimmed. Encode\n * such values into a component/subcomponent position, or parse with trimming\n * off, to preserve them exactly.\n *\n * @param input - the arbitrary string to encode.\n * @param enc - encoding characters; defaults to the HL7 standard `|^~\\&`.\n * @returns the spec-clean, delimiter-safe field body.\n *\n * @example\n * ```ts\n * import { encodeText, parseHL7 } from \"@cosyte/hl7\";\n * // A value full of delimiters cannot break out of its field:\n * const hostile = \"a|b^c~d\\\\e&f\";\n * const body = encodeText(hostile); // \"a\\\\F\\\\b\\\\S\\\\c\\\\R\\\\d\\\\E\\\\e\\\\T\\\\f\"\n * const msg = parseHL7(`MSH|^~\\\\&|A|B|C|D|20260101||ADT^A01|1|P|2.5\\rNTE|1||${body}`);\n * msg.segments(\"NTE\")[0]?.field(3).value === hostile; // true: round-trips exactly\n * ```\n */\nexport function encodeText(\n input: string,\n enc: EncodingCharacters = DEFAULT_ENCODING_CHARACTERS,\n): string {\n return reescape(input, enc);\n}\n","/**\n * The `@cosyte/hl7` **text codec**: a first-class, documented namespace for\n * getting the human string out of a field and safely encoding an arbitrary\n * string in.\n *\n * Exposed on the package as the `text` namespace object so a consumer can, in\n * one call:\n *\n * - `text.decode(field.text)`: resolve delimiter/hex/`\\.br\\` escapes to a value;\n * - `text.render(field.text)`: normalize formatting + highlight to a display model;\n * - `text.encode(anyString)`: encode-safe: no delimiter injection (Phase T's primitive).\n *\n * ```ts\n * import { text } from \"@cosyte/hl7\";\n * text.render(\"Result \\\\H\\\\HIGH\\\\N\\\\\\\\.br\\\\see note\").text; // \"Result HIGH\\nsee note\"\n * text.encode(\"a|b^c\").length > 0; // delimiter-safe\n * ```\n *\n * The same functions are also available as top-level named exports\n * (`decodeText`, `encodeText`, `renderText`) for tree-shaking-friendly imports.\n */\n\nexport { decodeText as decode, encodeText as encode } from \"./codec.js\";\nexport { renderText as render } from \"./render.js\";\n","/**\n * `HL7` namespace: type-only re-exports of the 10 composite interfaces\n * (XPN, XAD, CX, CWE, CE, XTN, PL, TS, NM, HD). Consumed via\n * `export * as HL7 from \"./model/types/namespace.js\";` in the top-level barrel\n * (`src/index.ts`). Named exports of the same interfaces live in the public\n * barrel alongside this namespace for developers who prefer the direct\n * `import type { XPN } ...` style (D-13).\n *\n * The namespace is TYPES-ONLY: parser functions (`parseXpn`, `parseXad`, ...)\n * are exported as value exports from the main barrel, not under `HL7`.\n */\n\nexport type { XPN } from \"./xpn.js\";\nexport type { XAD } from \"./xad.js\";\nexport type { CX } from \"./cx.js\";\nexport type { CWE } from \"./cwe.js\";\nexport type { CE } from \"./ce.js\";\nexport type { XTN } from \"./xtn.js\";\nexport type { PL } from \"./pl.js\";\nexport type { TS } from \"./ts.js\";\nexport type { NM } from \"./nm.js\";\nexport type { SN } from \"./sn.js\";\nexport type { HD } from \"./hd.js\";\nexport type { XCN } from \"./xcn.js\";\n","/**\n * `generateControlId`: synthesise an HL7 message control ID for outbound\n * messages. Shape: 17-char UTC timestamp `YYYYMMDDHHmmssSSS` + 6 random\n * alphanumeric chars = 23 chars total (D-12).\n *\n * Implementation lives in Phase 5 Plan 05 (build-message).\n *\n * Decisions:\n * - D-12: exact shape above; uniqueness via `Date.now()` + cryptographic\n * random bytes from `node:crypto.randomBytes` (WR-03 hardening: was\n * `Math.random` originally); alphabet is plain `[A-Za-z0-9]` (Claude's\n * Discretion: readability doesn't matter: IDs aren't human-typed).\n * - D-31: zero deps: Node stdlib only (`node:crypto` is stdlib).\n *\n * @internal\n */\n\nimport { randomBytes } from \"node:crypto\";\n\n/**\n * Alphabet for the random suffix: plain alphanumeric. Readability doesn't\n * matter (IDs aren't human-typed), so no ambiguous-char filtering.\n * @internal\n */\nconst ALNUM_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Zero-pad a number to N digits (stdlib: avoid regex for perf).\n * @internal\n */\nfunction pad(n: number, width: number): string {\n return String(n).padStart(width, \"0\");\n}\n\n/**\n * Generate an HL7 message control ID per D-12. Shape: 17-char UTC timestamp\n * `YYYYMMDDHHmmssSSS` + 6 random alphanumeric chars = 23 chars total.\n *\n * The 6-char suffix is sourced from `node:crypto.randomBytes(6)` and mapped\n * into the 62-char alnum alphabet. This avoids the `Math.random` collision\n * risk flagged in WR-03 under heavy concurrent load (many parallel workers\n * generating IDs in the same millisecond). Note: mapping 256-bucket bytes\n * into a 62-bucket alphabet via modulo introduces a tiny distributional\n * bias (the first 20 alphabet slots are ~slightly more likely than the\n * last 42), but the bias is negligible for uniqueness: the effective\n * entropy on the suffix remains > 35 bits, and the 17-char ms timestamp\n * prefix further partitions the ID space.\n *\n * Zero dependencies: uses `Date` + `node:crypto` only (D-31); both are\n * Node stdlib.\n *\n * @internal\n */\nexport function generateControlId(): string {\n const now = new Date();\n const ts =\n pad(now.getUTCFullYear(), 4) +\n pad(now.getUTCMonth() + 1, 2) +\n pad(now.getUTCDate(), 2) +\n pad(now.getUTCHours(), 2) +\n pad(now.getUTCMinutes(), 2) +\n pad(now.getUTCSeconds(), 2) +\n pad(now.getUTCMilliseconds(), 3);\n const bytes = randomBytes(6);\n let suffix = \"\";\n for (let i = 0; i < 6; i++) {\n // noUncheckedIndexedAccess: bytes is a Buffer of known length 6, so\n // bytes[i] is a number (0..255). The `?? 0` reflects that invariant\n // without a forbidden non-null assertion: the loop bound is a literal 6\n // that matches the requested byte count, so bytes[i] is always defined.\n const byte = bytes[i] ?? 0;\n const idx = byte % ALNUM_ALPHABET.length;\n // ALNUM_ALPHABET.charAt(idx) is always a single-char string.\n suffix += ALNUM_ALPHABET.charAt(idx);\n }\n return ts + suffix;\n}\n","/**\n * `formatHl7Timestamp`: format a JS `Date` to HL7 TS `YYYYMMDDHHmmss`\n * (UTC, second precision). The outbound (builder) counterpart to the inbound\n * `src/parser/dates.ts::parseDtm`; this side intentionally emits full\n * second-precision UTC for newly-constructed messages.\n *\n * Implementation lives in Phase 5 Plan 05 (build-message).\n *\n * Decisions:\n * - D-13: second precision only (no `.SSSS`); UTC via `getUTC*` methods.\n * - D-31: zero deps: stdlib `Date` only.\n *\n * @internal\n */\n\n/**\n * Format a JS `Date` to HL7 TS `YYYYMMDDHHmmss` (UTC, second precision,\n * always 14 chars). The builder counterpart to the parser's `parseDtm`.\n * D-13: sub-second precision is NOT emitted (acceptable asymmetry: most\n * outbound use cases don't need ms, and HL7 TS `.SSSS` is optional).\n *\n * Always uses UTC: callers who need local-time emission should supply a\n * pre-formatted HL7 TS string to `buildMessage({ timestamp: \"...\" })`.\n *\n * On an Invalid Date (`new Date(\"not-a-date\")`) the output is a string of\n * 14 `NaN`-derived chars. `buildMessage`'s upstream validation never passes\n * an invalid Date: sibling functions don't throw (D-07), so this pathological\n * case is accepted silently.\n *\n * @example\n * ```ts\n * // formatHl7Timestamp is internal, call buildMessage's `timestamp`\n * // option instead. Internally this maps Date -> YYYYMMDDHHmmss:\n * // new Date(\"2026-04-19T10:15:00Z\") -> \"20260419101500\"\n * ```\n *\n * @internal\n */\nexport function formatHl7Timestamp(date: Date): string {\n const yyyy = String(date.getUTCFullYear()).padStart(4, \"0\");\n const mm = String(date.getUTCMonth() + 1).padStart(2, \"0\"); // +1: getUTCMonth is 0-indexed\n const dd = String(date.getUTCDate()).padStart(2, \"0\");\n const hh = String(date.getUTCHours()).padStart(2, \"0\");\n const min = String(date.getUTCMinutes()).padStart(2, \"0\");\n const ss = String(date.getUTCSeconds()).padStart(2, \"0\");\n return `${yyyy}${mm}${dd}${hh}${min}${ss}`;\n}\n","/**\n * `buildMessage`: top-level outbound factory for the `@cosyte/hl7`\n * package. Synthesizes a complete MSH `RawSegment` from `BuildMessageInit`\n * and returns a real `Hl7Message` (not a builder subtype). Callers chain\n * `.addSegment(...)` (Phase 3 mutation method, unchanged) to append PID,\n * OBX, etc. Symmetric with `parseHL7` (D-09).\n *\n * The `BuildMessageInit` interface is exported in Plan 01 (this file) so\n * consumers + `src/index.ts` can reference the type immediately. The\n * `buildMessage` function body is filled in Phase 5 Plan 05 (build-message).\n *\n * Decisions:\n * - D-09: top-level named export from `src/index.ts`.\n * - D-10: `BuildMessageInit` shape below.\n * - D-11: internally synthesises a complete MSH `RawSegment` and hands to\n * `new Hl7Message({...})`.\n * - D-12: controlId auto-gen: YYYYMMDDHHmmssSSS + 6 alnum = 23 chars.\n * - D-13: `timestamp` accepts `Date | string`; `Date` formats to\n * `YYYYMMDDHHmmss` UTC.\n * - D-14: encoding chars always `DEFAULT_ENCODING_CHARACTERS`.\n * - D-15: subsequent `.addSegment(name, fields)` uses Phase 3 unchanged\n * (`readonly string[]` field input).\n * - D-16: missing/empty `type` throws `TypeError`.\n *\n * **Absent vs. explicit null at the wire level:** at the HL7 wire level,\n * an empty-string field and an omitted field produce IDENTICAL output\n * (both emit as absent: `||` in the line). If you need to distinguish\n * \"explicitly null\" (HL7 `\"\"`) from \"absent\" in an outbound message, use\n * `buildMessage({...}).setField(path, '\"\"')` after construction: the\n * Phase 3 `setField` mutation method sets `RawField.isNull = true`, which\n * the emitter preserves as the literal two-char string `\"\"` per D-02.\n */\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { RawField, RawSegment } from \"../parser/types.js\";\n\nimport { generateControlId } from \"./control-id.js\";\nimport { formatHl7Timestamp } from \"./format-timestamp.js\";\n\n/**\n * Input shape for `buildMessage` (SER-06). Mirrors `msg.meta` 1-for-1 so\n * read and write surfaces share field names (`sendingApp`, `sendingFacility`,\n * `receivingApp`, `receivingFacility`, `controlId`, `timestamp`, `version`,\n * `processingId`). `type` is the only required field.\n *\n * **Empty string vs. undefined semantics:** omitting a field and passing an\n * empty string produce IDENTICAL wire output (both emit as an absent\n * positional field). To emit an HL7 explicit null (`\"\"`) at a specific\n * position in an outbound message, build the message first and then call\n * `.setField(path, '\"\"')`: the Phase 3 mutation method sets `isNull=true`\n * on the underlying `RawField`, and the emitter preserves that as the\n * literal two-char output per D-02.\n *\n * @example\n * ```ts\n * import { buildMessage } from \"@cosyte/hl7\";\n * const msg = buildMessage({\n * type: \"ADT^A01\",\n * sendingApp: \"CLINIC\",\n * sendingFacility: \"MAIN\",\n * receivingApp: \"LAB\",\n * receivingFacility: \"REF\",\n * timestamp: new Date(\"2026-04-19T10:15:00Z\"),\n * })\n * .addSegment(\"PID\", [\"\", \"\", \"MRN123\", \"\", \"Doe^John\"]);\n * console.log(msg.toString());\n *\n * // To emit HL7 explicit null (\"\") instead of absent:\n * // msg.setField(\"PID.2\", '\"\"'); // distinct from empty/omitted\n * ```\n */\nexport interface BuildMessageInit {\n /**\n * HL7 message type, e.g. `\"ADT^A01\"` (code + trigger) or\n * `\"ORU^R01^ORU_R01\"` (code + trigger + structure). Required (D-16).\n *\n * The string is split on `^` into MSH-9 components; each component is\n * emitted verbatim. Literal `^` characters in a component are NOT\n * representable via this field: splitting is unconditional. Callers\n * needing that edge case should build the message and then use\n * `.setField(\"MSH.9.1\", ...)` etc. after construction.\n *\n * Rejected at runtime (D-16 / WR-04):\n * - empty string `\"\"` or whitespace-only `\" \"`;\n * - strings whose every `^`-split component is empty/whitespace\n * (e.g. `\"^\"`, `\"^^\"`, `\" ^ \"`).\n */\n readonly type: string;\n readonly sendingApp?: string;\n readonly sendingFacility?: string;\n readonly receivingApp?: string;\n readonly receivingFacility?: string;\n /** Auto-generated via `generateControlId()` when omitted (D-12). */\n readonly controlId?: string;\n /**\n * `Date` formatted to HL7 `YYYYMMDDHHmmss` (UTC, seconds) when supplied;\n * pre-formatted HL7 TS string passed through verbatim (D-13). Defaults to\n * `new Date()`.\n */\n readonly timestamp?: Date | string;\n /** Defaults to `\"2.5\"`. */\n readonly version?: string;\n /** Defaults to `\"P\"` (production). */\n readonly processingId?: string;\n}\n\n/**\n * Construct an outbound `Hl7Message` from semantic MSH fields (SER-06).\n * Synthesises a complete MSH `RawSegment` per D-10/D-11 and hands to\n * `new Hl7Message({...})`. Callers chain `.addSegment(name, fields)`\n * (Phase 3 mutation method, unchanged) to append PID, OBX, etc.\n *\n * Defaults applied when fields are omitted (D-10):\n * - `controlId` → `generateControlId()` (D-12)\n * - `timestamp` → `formatHl7Timestamp(new Date())` (D-13)\n * - `version` → `\"2.5\"`\n * - `processingId` → `\"P\"`\n * - `sendingApp`/`sendingFacility`/`receivingApp`/`receivingFacility` → empty\n *\n * Encoding characters are always `DEFAULT_ENCODING_CHARACTERS` (D-14); no\n * option to customise in v1.\n *\n * **Empty string vs. omitted field (W1):** at the HL7 wire level, passing\n * `sendingApp: \"\"` and omitting `sendingApp` produce IDENTICAL output\n * (both emit as absent: `||` at the MSH-3 position). If you need to\n * emit an HL7 explicit null (`\"\"`, the two-char literal) at a specific\n * position, build the message first, then use `setField`:\n *\n * ```ts\n * const msg = buildMessage({ type: \"ADT^A01\" });\n * msg.setField(\"MSH.3\", '\"\"'); // sets RawField.isNull = true\n * // msg.toString() now emits MSH-3 as `\"\"` (2 chars), not as absent.\n * ```\n *\n * The `BuildMessageInit` interface JSDoc (Plan 01) has the same note on\n * the input shape; this function-level doc reinforces it for developers\n * who land on the impl.\n *\n * @example\n * ```ts\n * import { buildMessage, parseHL7 } from \"@cosyte/hl7\";\n * const msg = buildMessage({\n * type: \"ADT^A01\",\n * sendingApp: \"CLINIC\",\n * sendingFacility: \"MAIN\",\n * receivingApp: \"LAB\",\n * receivingFacility: \"REF\",\n * }).addSegment(\"PID\", [\"\", \"\", \"MRN123\", \"\", \"Doe^John\"]);\n *\n * // Spec-clean HL7 string round-trips through parseHL7:\n * const round = parseHL7(msg.toString());\n * console.log(round.meta.type); // \"ADT^A01\"\n * ```\n */\nexport function buildMessage(init: BuildMessageInit): Hl7Message {\n // D-16 validation: type must be a non-empty, non-whitespace string.\n // `init` may be `null`/`undefined` at runtime if a JS caller bypasses the\n // type: guard defensively.\n if (\n init === null ||\n init === undefined ||\n typeof init.type !== \"string\" ||\n init.type.trim().length === 0\n ) {\n throw new TypeError(\n \"buildMessage: `type` is required and must be a non-empty string \" +\n '(e.g. \"ADT^A01\" or \"ORU^R01^ORU_R01\"). ' +\n `Received: ${JSON.stringify(init === null || init === undefined ? init : init.type)}.`,\n );\n }\n\n // WR-04: tighten D-16: split on `^` and reject a string whose every\n // component is empty/whitespace (e.g. `\"^\"`, `\" ^ \"`, `\"^^\"`). The\n // outer `.trim().length === 0` check above catches `\"\"` and `\" \"`, but\n // passes `\"^\"` (split → `[\"\",\"\"]` → MSH-9 emits as `^` which round-trips\n // but is malformed). Reject at the factory instead of letting garbage\n // through.\n const typeParts = init.type.split(\"^\");\n if (typeParts.every((p) => p.trim().length === 0)) {\n throw new TypeError(\n \"buildMessage: `type` must contain at least one non-empty component \" +\n '(e.g. \"ADT^A01\", not \"^\" or \"^^\"). ' +\n `Received: ${JSON.stringify(init.type)}.`,\n );\n }\n\n const enc = DEFAULT_ENCODING_CHARACTERS; // D-14\n\n // Resolve timestamp per D-13.\n const tsString: string = resolveTimestamp(init.timestamp);\n\n // Resolve controlId per D-12.\n const controlId = init.controlId ?? generateControlId();\n\n // Resolve version + processingId defaults.\n const version = init.version ?? \"2.5\";\n const processingId = init.processingId ?? \"P\";\n\n // Build MSH fields[0..11] per the positional mapping documented in\n // `RawSegment.fields` JSDoc + CONTEXT.md D-11.\n //\n // fields[0] = field-separator placeholder (content: \"|\")\n // fields[1] = MSH-2 encoding chars (content: \"^~\\\\&\")\n // fields[2] = MSH-3 sendingApp\n // fields[3] = MSH-4 sendingFacility\n // fields[4] = MSH-5 receivingApp\n // fields[5] = MSH-6 receivingFacility\n // fields[6] = MSH-7 timestamp\n // fields[7] = MSH-8 (unused) empty\n // fields[8] = MSH-9 = message type (possibly composite).\n // fields[9] = MSH-10 controlId\n // fields[10] = MSH-11 processingId\n // fields[11] = MSH-12 version\n //\n // W1: `scalarField(\"\")` produces an absent RawField (zero repetitions,\n // isNull:false): identical to omitting the field. That's the correct\n // wire semantic; callers who want explicit null use `.setField(\"MSH.N\",\n // '\"\"')` after construction.\n const mshFields: RawField[] = [\n scalarField(enc.field), // fields[0]\n scalarField(\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\"),\n ), // fields[1] MSH-2 (5th char only when truncation is set, v2.7+)\n scalarField(init.sendingApp ?? \"\"), // MSH-3\n scalarField(init.sendingFacility ?? \"\"), // MSH-4\n scalarField(init.receivingApp ?? \"\"), // MSH-5\n scalarField(init.receivingFacility ?? \"\"), // MSH-6\n scalarField(tsString), // MSH-7\n absentField(), // MSH-8\n compositeField(init.type), // MSH-9 (split on ^)\n scalarField(controlId), // MSH-10\n scalarField(processingId), // MSH-11\n scalarField(version), // MSH-12\n ];\n\n const mshSegment: RawSegment = {\n name: \"MSH\",\n fields: mshFields,\n };\n\n // D-11: construct the Hl7Message with the synthesised MSH as the sole\n // initial segment. Subsequent .addSegment() calls append PID/OBX/etc.\n return new Hl7Message({\n segments: [mshSegment],\n encodingCharacters: enc,\n version,\n warnings: [],\n });\n}\n\n/**\n * D-13: `Date` formats to HL7 `YYYYMMDDHHmmss` UTC; string passes through\n * verbatim; omitted defaults to `formatHl7Timestamp(new Date())`.\n * @internal\n */\nfunction resolveTimestamp(ts: Date | string | undefined): string {\n if (ts === undefined) return formatHl7Timestamp(new Date());\n if (typeof ts === \"string\") return ts;\n return formatHl7Timestamp(ts);\n}\n\n/**\n * Build a RawField carrying a single plain-string value (one repetition,\n * one component, one subcomponent). Empty string → absent field (W1 wire\n * semantic: empty and omitted are indistinguishable on the wire).\n * @internal\n */\nfunction scalarField(value: string): RawField {\n if (value === \"\") return { repetitions: [], isNull: false };\n return {\n repetitions: [\n {\n components: [{ subcomponents: [value] }],\n },\n ],\n isNull: false,\n };\n}\n\n/**\n * Build an absent RawField (no content, not null).\n * @internal\n */\nfunction absentField(): RawField {\n return { repetitions: [], isNull: false };\n}\n\n/**\n * Build MSH-9 from a `^`-delimited type string per the Claude's Discretion\n * resolution (accept a single string, split on `^` for component\n * decomposition). Empty parts suppressed via D-02 trailing-empty strip at\n * emit time.\n * @internal\n */\nfunction compositeField(typeString: string): RawField {\n const parts = typeString.split(\"^\");\n const components = parts.map((p) => ({ subcomponents: [p] }));\n return {\n repetitions: [{ components }],\n isNull: false,\n };\n}\n","/**\n * Shared field/segment assembly primitives for the typed builders\n * (`buildAdt`/`buildOru`: roadmap Phase T). Centralises the MSH synthesis and\n * the sparse positional-segment assembly so each builder stays declarative and\n * every builder emits an identical, spec-clean MSH.\n *\n * Zero runtime deps: pure functions over the raw positional tree.\n */\n\nimport { generateControlId } from \"./control-id.js\";\nimport { formatHl7Timestamp } from \"./format-timestamp.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { RawField, RawSegment } from \"../parser/types.js\";\n\n/**\n * The MSH envelope shared by every typed builder: the addressing + control\n * metadata that is independent of the message body. Mirrors `BuildMessageInit`\n * minus `type` (each builder derives MSH-9 from its own trigger).\n */\nexport interface MessageEnvelope {\n readonly sendingApp?: string;\n readonly sendingFacility?: string;\n readonly receivingApp?: string;\n readonly receivingFacility?: string;\n /** Auto-generated via `generateControlId()` when omitted. */\n readonly controlId?: string;\n /**\n * `Date` → HL7 `YYYYMMDDHHmmss` (UTC, seconds); a pre-formatted HL7 TS string\n * passes through verbatim. Defaults to `new Date()`.\n */\n readonly timestamp?: Date | string;\n /** Defaults to `\"2.5\"`. */\n readonly version?: string;\n /** Defaults to `\"P\"` (production). */\n readonly processingId?: string;\n}\n\n/**\n * A single plain-string field. Empty string → absent field (the HL7 wire\n * semantic: empty and omitted are indistinguishable between delimiters).\n * @internal\n */\nexport function scalarField(value: string | undefined): RawField {\n if (value === undefined || value === \"\") return { repetitions: [], isNull: false };\n return { repetitions: [{ components: [{ subcomponents: [value] }] }], isNull: false };\n}\n\n/**\n * An absent field (no content, not null).\n * @internal\n */\nexport function absentField(): RawField {\n return { repetitions: [], isNull: false };\n}\n\n/**\n * MSH-9 composite from a `^`-delimited type string (e.g. `\"ADT^A01\"`).\n * @internal\n */\nexport function typeField(typeString: string): RawField {\n const components = typeString.split(\"^\").map((p) => ({ subcomponents: [p] }));\n return { repetitions: [{ components }], isNull: false };\n}\n\n/** Resolve an envelope timestamp: `Date` → formatted, string → verbatim, omitted → now. */\nfunction resolveTimestamp(ts: Date | string | undefined): string {\n if (ts === undefined) return formatHl7Timestamp(new Date());\n if (typeof ts === \"string\") return ts;\n return formatHl7Timestamp(ts);\n}\n\n/**\n * Synthesise the MSH `RawSegment` (fields[0..11]) for a typed builder from an\n * {@link MessageEnvelope} and a `^`-delimited MSH-9 type string. Encoding\n * characters are always the HL7 default set; control id / timestamp default\n * exactly as `buildMessage` does, so the three builders emit identical MSH\n * shapes.\n * @internal\n */\nexport function buildMshSegment(type: string, envelope: MessageEnvelope): RawSegment {\n const enc = DEFAULT_ENCODING_CHARACTERS;\n const fields: RawField[] = [\n scalarField(enc.field), // fields[0] MSH-1 field separator placeholder\n scalarField(\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\"),\n ), // MSH-2 encoding characters\n scalarField(envelope.sendingApp), // MSH-3\n scalarField(envelope.sendingFacility), // MSH-4\n scalarField(envelope.receivingApp), // MSH-5\n scalarField(envelope.receivingFacility), // MSH-6\n scalarField(resolveTimestamp(envelope.timestamp)), // MSH-7\n absentField(), // MSH-8\n typeField(type), // MSH-9\n scalarField(envelope.controlId ?? generateControlId()), // MSH-10\n scalarField(envelope.processingId ?? \"P\"), // MSH-11\n scalarField(envelope.version ?? \"2.5\"), // MSH-12\n ];\n return { name: \"MSH\", fields };\n}\n\n/**\n * Assemble a non-MSH `RawSegment` from a sparse 1-indexed field map. Gaps\n * between populated positions become absent fields, so a caller can set (say)\n * PID-3, PID-5, and PID-7 without hand-listing the empty positions in between.\n * `fields[0]` (the name placeholder) is synthesised. An entry whose value is\n * `undefined` is skipped (treated as absent).\n * @internal\n */\nexport function assembleSegment(\n name: string,\n positions: ReadonlyMap<number, RawField | undefined>,\n): RawSegment {\n let max = 0;\n for (const [pos, field] of positions) {\n if (field !== undefined && pos > max) max = pos;\n }\n const fields: RawField[] = [absentField()]; // fields[0] name placeholder\n for (let i = 1; i <= max; i++) {\n fields.push(positions.get(i) ?? absentField());\n }\n return { name, fields };\n}\n","/**\n * `buildAdt`: author a spec-clean HL7 v2 **ADT** (admit/discharge/transfer)\n * message from typed inputs (roadmap Phase T). The conservative-emit mirror of\n * the read helpers (`msg.patient`, `msg.visit`): a caller supplies structured\n * values (an {@link XPN} name, {@link CX} identifiers, a {@link TS} birth date,\n * a {@link PL} location, …) and `buildAdt` assembles `MSH + EVN + PID + PV1`\n * with correct `^`/`&`/`~` structure via the HL7-R encode-safe path: never\n * hand-assembling delimiters, never injecting one.\n *\n * **Structurally complete + zero-warning.** The emitted message carries the\n * segment groups the parser's own structure net marks Required for the ADT\n * events it recognises (patient = PID, visit = PV1), so it re-parses with\n * **zero warnings** and `msg.structure.missingGroups` empty.\n *\n * **Never fabricate.** Only values the caller supplies are emitted; an omitted\n * optional field becomes an empty/absent field, never a defaulted clinical\n * value. `patient` is **required**: an ADT patient event with no patient is a\n * typed `TypeError`, not a guessed PID.\n *\n * Spec traceability: HL7 v2 Ch. 3 (ADT: MSH/EVN/PID/PV1), Ch. 2 datatypes.\n * Zero runtime deps.\n */\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { RawField, RawSegment } from \"../parser/types.js\";\nimport type { CX } from \"../model/types/cx.js\";\nimport type { PL } from \"../model/types/pl.js\";\nimport type { TS } from \"../model/types/ts.js\";\nimport type { XAD } from \"../model/types/xad.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\nimport type { XPN } from \"../model/types/xpn.js\";\nimport type { XTN } from \"../model/types/xtn.js\";\n\nimport {\n encodeComposite,\n encodeCompositeReps,\n type CompositeKind,\n type CompositeValueByKind,\n} from \"./encode-composite.js\";\nimport {\n assembleSegment,\n buildMshSegment,\n scalarField,\n type MessageEnvelope,\n} from \"./segment-fields.js\";\n\n/** Typed PID (patient identification) content for {@link buildAdt}. */\nexport interface AdtPatient {\n /** PID-1 Set ID. */\n readonly setId?: string;\n /** PID-3 Patient Identifier List: one or more CX identifiers (MRN, SSN, …). */\n readonly identifiers?: CX | readonly CX[];\n /** PID-5 Patient Name. */\n readonly name?: XPN | readonly XPN[];\n /** PID-6 Mother's Maiden Name. */\n readonly mothersMaidenName?: XPN;\n /** PID-7 Date/Time of Birth. */\n readonly birthDateTime?: TS | string;\n /** PID-8 Administrative Sex (e.g. `\"F\"`, `\"M\"`, `\"U\"`). */\n readonly administrativeSex?: string;\n /** PID-11 Patient Address: one or more XAD addresses. */\n readonly address?: XAD | readonly XAD[];\n /** PID-13 Phone Number - Home: one or more XTN telecoms. */\n readonly phoneHome?: XTN | readonly XTN[];\n /** PID-18 Patient Account Number. */\n readonly accountNumber?: CX;\n}\n\n/** Typed PV1 (patient visit) content for {@link buildAdt}. */\nexport interface AdtVisit {\n /** PV1-1 Set ID. */\n readonly setId?: string;\n /** PV1-2 Patient Class (e.g. `\"I\"` inpatient, `\"O\"` outpatient, `\"E\"` emergency). */\n readonly patientClass?: string;\n /** PV1-3 Assigned Patient Location. */\n readonly assignedLocation?: PL;\n /** PV1-7 Attending Doctor. */\n readonly attendingDoctor?: XCN | readonly XCN[];\n /** PV1-8 Referring Doctor. */\n readonly referringDoctor?: XCN | readonly XCN[];\n /** PV1-19 Visit Number. */\n readonly visitNumber?: CX;\n /** PV1-44 Admit Date/Time. */\n readonly admitDateTime?: TS | string;\n}\n\n/** Typed EVN (event type) content for {@link buildAdt}. */\nexport interface AdtEvent {\n /** EVN-2 Recorded Date/Time. */\n readonly recordedDateTime?: TS | string;\n /** EVN-6 Event Occurred. */\n readonly eventOccurred?: TS | string;\n}\n\n/** Input for {@link buildAdt}: the MSH envelope plus the typed segment bodies. */\nexport interface BuildAdtInit extends MessageEnvelope {\n /** PID content. **Required**: never fabricated. */\n readonly patient: AdtPatient;\n /** PV1 content. Optional; an (empty) PV1 is emitted regardless so the visit group is present. */\n readonly visit?: AdtVisit;\n /** EVN content (EVN-1 is the trigger event; EVN-2/6 optional). */\n readonly event?: AdtEvent;\n}\n\n/**\n * Encode a single composite or an array of them into a (possibly repeating)\n * field. `undefined` → absent field.\n * @internal\n */\nfunction repField<K extends CompositeKind>(\n kind: K,\n value: CompositeValueByKind[K] | readonly CompositeValueByKind[K][] | undefined,\n): RawField {\n if (value === undefined) return { repetitions: [], isNull: false };\n if (Array.isArray(value)) {\n return encodeCompositeReps(kind, value as readonly CompositeValueByKind[K][]);\n }\n return encodeComposite(kind, value as CompositeValueByKind[K]);\n}\n\n/**\n * Build a spec-clean ADT message for `event` (the MSH-9.2 trigger, e.g.\n * `\"A01\"`, `\"A04\"`, `\"A08\"`) from typed inputs.\n *\n * The result is a real {@link Hl7Message}: `msg.toString()` serialises it,\n * `parseHL7(msg.toString())` round-trips with zero warnings, and\n * `msg.patient` / `msg.visit` read back the values supplied.\n *\n * @param event - the ADT trigger event (MSH-9.2). Required, non-empty.\n * @param init - the MSH envelope + typed PID/PV1/EVN content (`patient` required).\n * @throws TypeError when `event` is empty or `init.patient` is absent.\n *\n * @example\n * ```ts\n * import { buildAdt, parseHL7 } from \"@cosyte/hl7\";\n * const msg = buildAdt(\"A01\", {\n * sendingApp: \"CLINIC\",\n * receivingApp: \"LAB\",\n * patient: {\n * identifiers: { idNumber: \"MRN001\", identifierTypeCode: \"MR\" },\n * name: { familyName: \"Test\", givenName: \"Ann\" },\n * birthDateTime: \"19880705\",\n * administrativeSex: \"F\",\n * },\n * visit: { patientClass: \"I\", assignedLocation: { pointOfCare: \"ICU\", room: \"1\", bed: \"A\" } },\n * });\n * const round = parseHL7(msg.toString());\n * round.warnings.length; // 0\n * round.patient?.familyName; // \"Test\"\n * round.structure.missingGroups; // []\n * ```\n */\nexport function buildAdt(event: string, init: BuildAdtInit): Hl7Message {\n if (typeof event !== \"string\" || event.trim().length === 0) {\n throw new TypeError(\n `buildAdt: \\`event\\` (the ADT trigger, e.g. \"A01\") is required and must be a ` +\n `non-empty string. Received: ${JSON.stringify(event)}.`,\n );\n }\n if (\n init === null ||\n (init as BuildAdtInit | undefined) === undefined ||\n init.patient === undefined\n ) {\n throw new TypeError(\n \"buildAdt: `patient` is required. An ADT patient event is never emitted with a \" +\n \"fabricated patient. Supply at least one identifier or a name.\",\n );\n }\n\n const enc = DEFAULT_ENCODING_CHARACTERS;\n const version = init.version ?? \"2.5\";\n\n const segments: RawSegment[] = [buildMshSegment(`ADT^${event}`, init)];\n\n // ── EVN ──────────────────────────────────────────────────────────────────\n // EVN-1 is the (caller-supplied) trigger event: not a fabricated value.\n const evn = init.event;\n segments.push(\n assembleSegment(\n \"EVN\",\n new Map<number, RawField | undefined>([\n [1, scalarField(event)],\n [\n 2,\n evn?.recordedDateTime !== undefined\n ? encodeComposite(\"TS\", evn.recordedDateTime)\n : undefined,\n ],\n [\n 6,\n evn?.eventOccurred !== undefined ? encodeComposite(\"TS\", evn.eventOccurred) : undefined,\n ],\n ]),\n ),\n );\n\n // ── PID ──────────────────────────────────────────────────────────────────\n const p = init.patient;\n segments.push(\n assembleSegment(\n \"PID\",\n new Map<number, RawField | undefined>([\n [1, p.setId !== undefined ? scalarField(p.setId) : undefined],\n [3, p.identifiers !== undefined ? repField(\"CX\", p.identifiers) : undefined],\n [5, p.name !== undefined ? repField(\"XPN\", p.name) : undefined],\n [\n 6,\n p.mothersMaidenName !== undefined\n ? encodeComposite(\"XPN\", p.mothersMaidenName)\n : undefined,\n ],\n [7, p.birthDateTime !== undefined ? encodeComposite(\"TS\", p.birthDateTime) : undefined],\n [8, p.administrativeSex !== undefined ? scalarField(p.administrativeSex) : undefined],\n [11, p.address !== undefined ? repField(\"XAD\", p.address) : undefined],\n [13, p.phoneHome !== undefined ? repField(\"XTN\", p.phoneHome) : undefined],\n [18, p.accountNumber !== undefined ? encodeComposite(\"CX\", p.accountNumber) : undefined],\n ]),\n ),\n );\n\n // ── PV1 ──────────────────────────────────────────────────────────────────\n // Always emitted so the ADT \"visit\" group is present (structure-complete),\n // even when the caller supplies no visit: an empty PV1 is the fail-safe,\n // never fabricated content.\n const v = init.visit;\n segments.push(\n assembleSegment(\n \"PV1\",\n new Map<number, RawField | undefined>([\n [1, v?.setId !== undefined ? scalarField(v.setId) : undefined],\n [2, v?.patientClass !== undefined ? scalarField(v.patientClass) : undefined],\n [\n 3,\n v?.assignedLocation !== undefined ? encodeComposite(\"PL\", v.assignedLocation) : undefined,\n ],\n [7, v?.attendingDoctor !== undefined ? repField(\"XCN\", v.attendingDoctor) : undefined],\n [8, v?.referringDoctor !== undefined ? repField(\"XCN\", v.referringDoctor) : undefined],\n [19, v?.visitNumber !== undefined ? encodeComposite(\"CX\", v.visitNumber) : undefined],\n [44, v?.admitDateTime !== undefined ? encodeComposite(\"TS\", v.admitDateTime) : undefined],\n ]),\n ),\n );\n\n return new Hl7Message({\n segments,\n encodingCharacters: enc,\n version,\n warnings: [],\n });\n}\n","/**\n * `buildOru`: author a spec-clean HL7 v2 **ORU^R01** (observation result)\n * message from typed inputs (roadmap Phase T). The conservative-emit mirror of\n * the read helpers (`msg.orders`, `msg.observations`): a caller supplies a\n * typed patient, an optional order (OBR), and one or more typed observations\n * (OBX), and `buildOru` assembles `MSH + PID + OBR + OBX…` with correct\n * `^`/`&`/`~` structure via the HL7-R encode-safe path.\n *\n * **Structurally complete + zero-warning.** The emitted message carries the\n * ORU^R01 result group the parser's structure net marks Required (OBR/OBX), so\n * it re-parses with **zero warnings** and `msg.structure.missingGroups` empty.\n *\n * **Never fabricate.** Only supplied values are emitted; omitted fields become\n * empty/absent. `patient` and at least one `observations` entry are\n * **required**: an ORU with no subject or no result is a typed `TypeError`,\n * not a guessed PID or a fabricated OBX.\n *\n * Spec traceability: HL7 v2 Ch. 7 (ORU: MSH/PID/OBR/OBX), Ch. 2 datatypes.\n * Zero runtime deps.\n */\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { RawField, RawSegment } from \"../parser/types.js\";\nimport type { CWE } from \"../model/types/cwe.js\";\nimport type { TS } from \"../model/types/ts.js\";\nimport type { XCN } from \"../model/types/xcn.js\";\n\nimport {\n encodeComposite,\n encodeCompositeReps,\n type CompositeKind,\n type CompositeValueByKind,\n} from \"./encode-composite.js\";\nimport type { AdtPatient } from \"./build-adt.js\";\nimport {\n assembleSegment,\n buildMshSegment,\n scalarField,\n type MessageEnvelope,\n} from \"./segment-fields.js\";\n\n/**\n * Typed PID content for {@link buildOru}. Reuses {@link AdtPatient}: the\n * patient-identification shape is identical across message families.\n */\nexport type OruPatient = AdtPatient;\n\n/** Typed OBR (observation request / order) content for {@link buildOru}. */\nexport interface OruOrder {\n /** OBR-1 Set ID. */\n readonly setId?: string;\n /** OBR-2 Placer Order Number. */\n readonly placerOrderNumber?: string;\n /** OBR-3 Filler Order Number. */\n readonly fillerOrderNumber?: string;\n /** OBR-4 Universal Service Identifier. */\n readonly universalServiceId?: CWE;\n /** OBR-7 Observation Date/Time. */\n readonly observationDateTime?: TS | string;\n /** OBR-16 Ordering Provider. */\n readonly orderingProvider?: XCN | readonly XCN[];\n /** OBR-25 Result Status (e.g. `\"F\"` final, `\"P\"` preliminary, `\"C\"` corrected). */\n readonly resultStatus?: string;\n}\n\n/** Typed OBX (observation / result) content for {@link buildOru}. */\nexport interface OruObservation {\n /** OBX-1 Set ID. */\n readonly setId?: string;\n /** OBX-2 Value Type (e.g. `\"NM\"`, `\"ST\"`, `\"CE\"`, `\"TX\"`). */\n readonly valueType?: string;\n /** OBX-3 Observation Identifier. */\n readonly identifier?: CWE;\n /** OBX-5 Observation Value (emitted verbatim: the caller owns its formatting). */\n readonly value?: string;\n /** OBX-6 Units. */\n readonly units?: CWE;\n /** OBX-7 References Range. */\n readonly referenceRange?: string;\n /** OBX-8 Abnormal Flags (e.g. `\"H\"`, `\"L\"`, `\"N\"`). */\n readonly abnormalFlags?: string;\n /** OBX-11 Observation Result Status (e.g. `\"F\"` final, `\"P\"` preliminary). */\n readonly observationResultStatus?: string;\n /** OBX-14 Date/Time of the Observation. */\n readonly observationDateTime?: TS | string;\n}\n\n/** Input for {@link buildOru}: the MSH envelope plus the typed segment bodies. */\nexport interface BuildOruInit extends MessageEnvelope {\n /** PID content. **Required**: never fabricated. */\n readonly patient: OruPatient;\n /** OBR content. Optional; an (empty) OBR is emitted regardless so the result group is well-formed. */\n readonly order?: OruOrder;\n /** OBX content. **Required, non-empty**: an ORU with no result is a typed error. */\n readonly observations: readonly OruObservation[];\n}\n\n/** @internal */\nfunction repField<K extends CompositeKind>(\n kind: K,\n value: CompositeValueByKind[K] | readonly CompositeValueByKind[K][] | undefined,\n): RawField {\n if (value === undefined) return { repetitions: [], isNull: false };\n if (Array.isArray(value)) {\n return encodeCompositeReps(kind, value as readonly CompositeValueByKind[K][]);\n }\n return encodeComposite(kind, value as CompositeValueByKind[K]);\n}\n\n/**\n * Build a spec-clean ORU^R01 observation-result message from typed inputs.\n *\n * The result is a real {@link Hl7Message}: `msg.toString()` serialises it,\n * `parseHL7(msg.toString())` round-trips with zero warnings, and\n * `msg.observations()` reads back the results supplied.\n *\n * @param init - the MSH envelope + typed PID/OBR/OBX content. `patient` and a\n * non-empty `observations` list are required.\n * @throws TypeError when `patient` is absent or `observations` is empty.\n *\n * @example\n * ```ts\n * import { buildOru, parseHL7 } from \"@cosyte/hl7\";\n * const msg = buildOru({\n * sendingApp: \"LAB\",\n * receivingApp: \"EHR\",\n * patient: { identifiers: { idNumber: \"MRN001\", identifierTypeCode: \"MR\" },\n * name: { familyName: \"Test\", givenName: \"Ann\" } },\n * order: { universalServiceId: { identifier: \"CBC\", text: \"Complete Blood Count\", nameOfCodingSystem: \"L\" },\n * resultStatus: \"F\" },\n * observations: [\n * { setId: \"1\", valueType: \"NM\",\n * identifier: { identifier: \"WBC\", text: \"White Blood Cells\", nameOfCodingSystem: \"LN\" },\n * value: \"7.2\", units: { identifier: \"10*3/uL\" }, observationResultStatus: \"F\" },\n * ],\n * });\n * const round = parseHL7(msg.toString());\n * round.warnings.length; // 0\n * round.observations()[0]?.value; // \"7.2\"\n * ```\n */\nexport function buildOru(init: BuildOruInit): Hl7Message {\n if (\n init === null ||\n (init as BuildOruInit | undefined) === undefined ||\n init.patient === undefined\n ) {\n throw new TypeError(\n \"buildOru: `patient` is required. An ORU is never emitted with a fabricated subject.\",\n );\n }\n // Note: intentionally NOT `Array.isArray`: that narrows a `readonly T[]` to\n // `any[]` and would poison `obs` in the loop below to `any`. An\n // undefined-or-empty check keeps the element type.\n if (\n (init.observations as readonly OruObservation[] | undefined) === undefined ||\n init.observations.length === 0\n ) {\n throw new TypeError(\n \"buildOru: at least one `observations` entry (OBX) is required. An ORU with no \" +\n \"result is a typed error, never a fabricated observation.\",\n );\n }\n\n const enc = DEFAULT_ENCODING_CHARACTERS;\n const version = init.version ?? \"2.5\";\n\n const segments: RawSegment[] = [buildMshSegment(\"ORU^R01\", init)];\n\n // ── PID ──────────────────────────────────────────────────────────────────\n const p = init.patient;\n segments.push(\n assembleSegment(\n \"PID\",\n new Map<number, RawField | undefined>([\n [1, p.setId !== undefined ? scalarField(p.setId) : undefined],\n [3, p.identifiers !== undefined ? repField(\"CX\", p.identifiers) : undefined],\n [5, p.name !== undefined ? repField(\"XPN\", p.name) : undefined],\n [\n 6,\n p.mothersMaidenName !== undefined\n ? encodeComposite(\"XPN\", p.mothersMaidenName)\n : undefined,\n ],\n [7, p.birthDateTime !== undefined ? encodeComposite(\"TS\", p.birthDateTime) : undefined],\n [8, p.administrativeSex !== undefined ? scalarField(p.administrativeSex) : undefined],\n [11, p.address !== undefined ? repField(\"XAD\", p.address) : undefined],\n [13, p.phoneHome !== undefined ? repField(\"XTN\", p.phoneHome) : undefined],\n [18, p.accountNumber !== undefined ? encodeComposite(\"CX\", p.accountNumber) : undefined],\n ]),\n ),\n );\n\n // ── OBR ──────────────────────────────────────────────────────────────────\n // One OBR groups the OBX result children. Always emitted (empty when no order\n // supplied) so the result group is well-formed; never fabricated content.\n const o = init.order;\n segments.push(\n assembleSegment(\n \"OBR\",\n new Map<number, RawField | undefined>([\n [1, o?.setId !== undefined ? scalarField(o.setId) : undefined],\n [2, o?.placerOrderNumber !== undefined ? scalarField(o.placerOrderNumber) : undefined],\n [3, o?.fillerOrderNumber !== undefined ? scalarField(o.fillerOrderNumber) : undefined],\n [\n 4,\n o?.universalServiceId !== undefined\n ? encodeComposite(\"CWE\", o.universalServiceId)\n : undefined,\n ],\n [\n 7,\n o?.observationDateTime !== undefined\n ? encodeComposite(\"TS\", o.observationDateTime)\n : undefined,\n ],\n [16, o?.orderingProvider !== undefined ? repField(\"XCN\", o.orderingProvider) : undefined],\n [25, o?.resultStatus !== undefined ? scalarField(o.resultStatus) : undefined],\n ]),\n ),\n );\n\n // ── OBX (one per observation) ──────────────────────────────────────────────\n for (const obs of init.observations) {\n segments.push(\n assembleSegment(\n \"OBX\",\n new Map<number, RawField | undefined>([\n [1, obs.setId !== undefined ? scalarField(obs.setId) : undefined],\n [2, obs.valueType !== undefined ? scalarField(obs.valueType) : undefined],\n [3, obs.identifier !== undefined ? encodeComposite(\"CWE\", obs.identifier) : undefined],\n [5, obs.value !== undefined ? scalarField(obs.value) : undefined],\n [6, obs.units !== undefined ? encodeComposite(\"CWE\", obs.units) : undefined],\n [7, obs.referenceRange !== undefined ? scalarField(obs.referenceRange) : undefined],\n [8, obs.abnormalFlags !== undefined ? scalarField(obs.abnormalFlags) : undefined],\n [\n 11,\n obs.observationResultStatus !== undefined\n ? scalarField(obs.observationResultStatus)\n : undefined,\n ],\n [\n 14,\n obs.observationDateTime !== undefined\n ? encodeComposite(\"TS\", obs.observationDateTime)\n : undefined,\n ],\n ]),\n ),\n );\n }\n\n return new Hl7Message({\n segments,\n encodingCharacters: enc,\n version,\n warnings: [],\n });\n}\n","/**\n * Frozen HL7 control-vocabulary tables for ACK generation (Phase C). These\n * are read-only enums sourced from the HL7 v2 standard: `@cosyte/hl7` is the\n * single owner of this vocabulary; siblings (notably `@cosyte/mllp`) consume\n * `buildAck` rather than re-declaring these codes.\n *\n * Provenance (re-verify before editing: HL7 tables move):\n * - **Table 0008** Acknowledgment code: https://terminology.hl7.org/CodeSystem-v2-0008.html\n * - **Table 0357** Message error condition codes: https://terminology.hl7.org/CodeSystem-v2-0357.html\n * - **Table 0516** Error severity: HL7 v2 Chapter 2 §2.14.5 (ERR-4)\n * - **Table 0155** Accept/application acknowledgment conditions (MSH-15/16),\n * HL7 v2 Chapter 2 §2.14.9.15–16\n *\n * Zero runtime deps.\n */\n\n/**\n * HL7 Table 0008: Acknowledgment code (MSA-1). The two acknowledgment\n * **vocabularies**:\n * - **original** mode: `AA` Application Accept · `AE` Application Error ·\n * `AR` Application Reject.\n * - **enhanced** mode accept-level: `CA` Commit Accept · `CE` Commit Error ·\n * `CR` Commit Reject (the application-level response in enhanced mode reuses\n * `AA`/`AE`/`AR`).\n *\n * @example\n * ```ts\n * import { ACK_CODES } from \"@cosyte/hl7\";\n * ACK_CODES.AA; // \"AA\"\n * ```\n */\nexport const ACK_CODES = {\n AA: \"AA\",\n AE: \"AE\",\n AR: \"AR\",\n CA: \"CA\",\n CE: \"CE\",\n CR: \"CR\",\n} as const;\n\n/**\n * Acknowledgment code union (HL7 Table 0008). Narrow on this to know whether a\n * disposition is accept (`AA`/`CA`), error (`AE`/`CE`), or reject (`AR`/`CR`).\n */\nexport type AckCode = (typeof ACK_CODES)[keyof typeof ACK_CODES];\n\n/** The positive-accept codes: the ones the fail-safe refuses to fabricate. */\nconst POSITIVE_ACK_CODES: ReadonlySet<string> = new Set([ACK_CODES.AA, ACK_CODES.CA]);\n/** The error codes (message received, processing problem). */\nconst ERROR_ACK_CODES: ReadonlySet<string> = new Set([ACK_CODES.AE, ACK_CODES.CE]);\n/** The reject codes (message refused). */\nconst REJECT_ACK_CODES: ReadonlySet<string> = new Set([ACK_CODES.AR, ACK_CODES.CR]);\n\n/**\n * True iff `code` is a positive accept (`AA`/`CA`). Unknown/absent → false.\n *\n * @example\n * ```ts\n * isPositiveAck(\"AA\"); // true\n * isPositiveAck(\"AE\"); // false\n * ```\n */\nexport function isPositiveAck(code: string | undefined): boolean {\n return code !== undefined && POSITIVE_ACK_CODES.has(code);\n}\n\n/**\n * Downgrade a positive acknowledgment code to its matching error code,\n * `AA` → `AE` (original mode), `CA` → `CE` (enhanced mode). Every other code\n * passes through unchanged.\n *\n * This is the **single upstream source of truth** for the fail-safe downgrade\n * pair: `buildAck` applies it when the inbound carries no MSH-10 correlation\n * id, and `@cosyte/mllp`'s `ack-from-hl7` adapter applies it when the inbound\n * cannot be parsed at all: neither ever fabricates an unverifiable positive\n * acknowledgment, and neither carries its own copy of the mapping.\n *\n * @example\n * ```ts\n * import { downgradePositiveAck } from \"@cosyte/hl7\";\n * downgradePositiveAck(\"AA\"); // \"AE\"\n * downgradePositiveAck(\"CA\"); // \"CE\"\n * downgradePositiveAck(\"AR\"); // \"AR\" (unchanged)\n * ```\n */\nexport function downgradePositiveAck(code: AckCode): AckCode {\n if (code === ACK_CODES.AA) return ACK_CODES.AE;\n if (code === ACK_CODES.CA) return ACK_CODES.CE;\n return code;\n}\n\n/**\n * True iff `code` is an error acknowledgment (`AE`/`CE`). Unknown/absent → false.\n *\n * @example\n * ```ts\n * isErrorAck(\"CE\"); // true\n * ```\n */\nexport function isErrorAck(code: string | undefined): boolean {\n return code !== undefined && ERROR_ACK_CODES.has(code);\n}\n\n/**\n * True iff `code` is a reject acknowledgment (`AR`/`CR`). Unknown/absent → false.\n *\n * @example\n * ```ts\n * isRejectAck(\"AR\"); // true\n * ```\n */\nexport function isRejectAck(code: string | undefined): boolean {\n return code !== undefined && REJECT_ACK_CODES.has(code);\n}\n\n/**\n * True iff `code` is one of the six known Table 0008 codes.\n *\n * @example\n * ```ts\n * isKnownAckCode(\"AA\"); // true\n * isKnownAckCode(\"ZZ\"); // false\n * ```\n */\nexport function isKnownAckCode(code: string): code is AckCode {\n return code in ACK_CODES;\n}\n\n/**\n * HL7 Table 0516: Error severity (ERR-4). A v2.5+ construct (ERR was\n * structured differently in v2.3.1).\n *\n * @example\n * ```ts\n * import { ERR_SEVERITIES } from \"@cosyte/hl7\";\n * ERR_SEVERITIES.E; // \"E\" (Error)\n * ```\n */\nexport const ERR_SEVERITIES = {\n /** Information. */\n I: \"I\",\n /** Warning. */\n W: \"W\",\n /** Error. */\n E: \"E\",\n} as const;\n\n/** Error-severity union (HL7 Table 0516, ERR-4). */\nexport type ErrSeverity = (typeof ERR_SEVERITIES)[keyof typeof ERR_SEVERITIES];\n\n/**\n * HL7 Table 0357: Message error condition codes (ERR-3.1 → ERR-3.2 text).\n * Frozen read-only map of `code → standard display text`. The code system\n * name emitted in ERR-3.3 is {@link ERR_CONDITION_CODE_SYSTEM}.\n *\n * Codes `104` (value too long) and `105` (table value not found) are v2.7+\n * additions; the rest are present from v2.5. `buildAck` emits whatever code it\n * is told (it never invents a condition) and looks up the display text here.\n *\n * @example\n * ```ts\n * import { ERR_CONDITION_CODES } from \"@cosyte/hl7\";\n * ERR_CONDITION_CODES[\"101\"]; // \"Required field missing\"\n * ```\n */\nexport const ERR_CONDITION_CODES: Readonly<Record<string, string>> = Object.freeze({\n \"0\": \"Message accepted\",\n \"100\": \"Segment sequence error\",\n \"101\": \"Required field missing\",\n \"102\": \"Data type error\",\n \"103\": \"Table value not found\",\n \"104\": \"Value too long\",\n \"105\": \"Table value not found\",\n \"200\": \"Unsupported message type\",\n \"201\": \"Unsupported event code\",\n \"202\": \"Unsupported processing id\",\n \"203\": \"Unsupported version id\",\n \"204\": \"Unknown key identifier\",\n \"205\": \"Duplicate key identifier\",\n \"206\": \"Application record locked\",\n \"207\": \"Application internal error\",\n});\n\n/** Code-system name emitted in ERR-3.3 for Table 0357 condition codes. */\nexport const ERR_CONDITION_CODE_SYSTEM = \"HL70357\";\n\n/**\n * HL7 Table 0155: Accept/application acknowledgment conditions (MSH-15 /\n * MSH-16): `AL` Always · `NE` Never · `ER` Error/reject conditions only ·\n * `SU` Successful completion only. Exposed read-only for adapters that\n * surface the inbound sender's stated acknowledgment expectations.\n *\n * @example\n * ```ts\n * import { ACK_CONDITIONS } from \"@cosyte/hl7\";\n * ACK_CONDITIONS.AL; // \"AL\" (Always)\n * ```\n */\nexport const ACK_CONDITIONS = {\n AL: \"AL\",\n NE: \"NE\",\n ER: \"ER\",\n SU: \"SU\",\n} as const;\n\n/** Accept/application acknowledgment condition union (HL7 Table 0155). */\nexport type AckCondition = (typeof ACK_CONDITIONS)[keyof typeof ACK_CONDITIONS];\n\n/**\n * The two HL7 acknowledgment modes. **original** = both MSH-15 and MSH-16 are\n * absent/null; **enhanced** = either is present (HL7 v2 Chapter 2 §2.9).\n */\nexport type AckMode = \"original\" | \"enhanced\";\n","/**\n * `buildAck`: generate a spec-clean HL7 v2 acknowledgment (ACK) message from\n * an inbound message (Phase C). The boundary with `@cosyte/mllp` is resolved\n * (hl7 roadmap §10.1): **hl7 owns ACK *content*** (this file + the control\n * tables); mllp owns *policy/timing* (the commit contract) and *framing*.\n *\n * `buildAck` is **mechanical**: it builds the disposition it is *told* via\n * `options.code`; it never decides accept-vs-reject. The one safety override is\n * the fail-safe below: it refuses to fabricate a positive `AA`/`CA` for an\n * inbound message that carries no MSH-10 correlation id.\n *\n * Spec traceability: HL7 v2 Chapter 2 §2.9 (ack model), §2.14.8 (MSA),\n * §2.14.5 (ERR), §2.14.9.15–16 (MSH-15/16). Tables 0008 / 0357 / 0516 / 0155\n * live in `ack-tables.ts`.\n *\n * Zero runtime deps.\n */\n\nimport { Hl7Message } from \"../model/message.js\";\nimport { DEFAULT_ENCODING_CHARACTERS } from \"../parser/delimiters.js\";\nimport type { EncodingCharacters, RawField, RawSegment } from \"../parser/types.js\";\nimport { ackNoCorrelationId } from \"../parser/warnings.js\";\n\nimport {\n downgradePositiveAck,\n ERR_CONDITION_CODES,\n ERR_CONDITION_CODE_SYSTEM,\n ERR_SEVERITIES,\n isKnownAckCode,\n isPositiveAck,\n type AckCode,\n type AckMode,\n type ErrSeverity,\n} from \"./ack-tables.js\";\nimport { generateControlId } from \"./control-id.js\";\nimport { formatHl7Timestamp } from \"./format-timestamp.js\";\n\n/**\n * One ERR segment's worth of error detail for `buildAck`. Carries **codes and\n * locations only: never echoed PHI values** (the phi-redaction-review gate\n * binds this contract).\n *\n * @example\n * ```ts\n * import { buildAck } from \"@cosyte/hl7\";\n * const ack = buildAck(inbound, {\n * code: \"AE\",\n * error: { conditionCode: \"101\", severity: \"E\", location: \"PID^1^5\" },\n * });\n * ```\n */\nexport interface AckErrorDetail {\n /**\n * HL7 Table 0357 message error condition code (ERR-3.1). Defaults to `\"207\"`\n * (Application internal error). The standard display text is looked up from\n * Table 0357 and emitted in ERR-3.2; unknown codes emit with empty text\n * (the code is preserved verbatim: never dropped).\n */\n readonly conditionCode?: string;\n /** HL7 Table 0516 severity (ERR-4). Defaults to `\"E\"` (Error). */\n readonly severity?: ErrSeverity;\n /**\n * Error location (ERR-2, an HL7 ERL). A structural path such as `\"PID^1^5\"`\n * (segment id ^ segment sequence ^ field position). **Must not contain a\n * patient data value**: locations point at *where*, never *what*.\n */\n readonly location?: string;\n}\n\n/**\n * Options for {@link buildAck}.\n *\n * @example\n * ```ts\n * buildAck(inbound, { code: \"AA\" }); // bare accept\n * buildAck(inbound, { code: \"AR\", error: { conditionCode: \"200\" } });\n * ```\n */\nexport interface BuildAckOptions {\n /**\n * The acknowledgment disposition to emit in MSA-1 (HL7 Table 0008). One of\n * `AA`/`AE`/`AR` (original) or `CA`/`CE`/`CR` (enhanced accept-level).\n * Required: `buildAck` builds the disposition it is told. An unknown code\n * is a programming error and throws `TypeError`.\n */\n readonly code: AckCode;\n /**\n * Optional error detail. A single {@link AckErrorDetail} or an array → one\n * ERR segment each. Typically supplied for `AE`/`AR`/`CE`/`CR`.\n */\n readonly error?: AckErrorDetail | readonly AckErrorDetail[];\n /**\n * Optional explicit acknowledgment mode. When omitted it is derived from the\n * inbound MSH-15/16 via {@link detectAckMode}. `buildAck` emits `code`\n * verbatim regardless of mode: this field is advisory metadata for adapters\n * (e.g. `@cosyte/mllp`'s commit-policy layer) that need the detected mode.\n */\n readonly mode?: AckMode;\n}\n\n/**\n * Detect the HL7 acknowledgment mode of an inbound message from MSH-15 (accept\n * acknowledgment type) and MSH-16 (application acknowledgment type), per HL7 v2\n * Chapter 2 §2.9: **original** when *both* are absent/empty; **enhanced** when\n * *either* is present. This split is spec-exact (unlike the disposition mapping,\n * which has no single correct model: see the package README).\n *\n * @example\n * ```ts\n * import { detectAckMode, parseHL7 } from \"@cosyte/hl7\";\n * detectAckMode(parseHL7(raw)); // \"original\" | \"enhanced\"\n * ```\n */\nexport function detectAckMode(inbound: Hl7Message): AckMode {\n const acceptType = inbound.get(\"MSH.15\");\n const appType = inbound.get(\"MSH.16\");\n const hasAccept = acceptType !== undefined && acceptType !== \"\";\n const hasApp = appType !== undefined && appType !== \"\";\n return hasAccept || hasApp ? \"enhanced\" : \"original\";\n}\n\n/**\n * Build a spec-clean ACK (`MSH` + `MSA` [+ `ERR`…]) responding to `inbound`.\n *\n * Behavior:\n * - **MSH**: sender/receiver are swapped (inbound MSH-5/6 → ACK MSH-3/4;\n * inbound MSH-3/4 → ACK MSH-5/6); MSH-7 is the current UTC time; MSH-9 is\n * `ACK` (with the inbound trigger event echoed as `ACK^<trigger>^ACK` when\n * present); MSH-10 is a freshly generated control id; MSH-11 (processing id)\n * and MSH-12 (version) echo the inbound values.\n * - **MSA**: MSA-1 = `code`; **MSA-2 echoes the full inbound MSH-10 field**\n * (the raw field structure is carried over whole: a vendor-quirk id like\n * `ID^X` is never truncated to its first component). The echo carries the\n * inbound field's escape-fidelity overlay (HL7-ESC), so an id bearing a hex\n * escape (`ID\\X41\\Q`) or a preserved escape (`\\H\\`) echoes **byte-verbatim**,\n * not canonicalized: exactly the bytes the sender put on the wire, which is\n * what MSA-2 correlation compares. The only structural transform is\n * trailing-empty canonicalization (D-02). (A sender that used *custom*\n * encoding characters is **re-delimited spec-cleanly**: the overlay carries\n * the sender's raw bytes in the sender's alphabet, so echoing them verbatim\n * under the ACK's default alphabet would corrupt the field's structure and\n * break correlation: the overlay is therefore bypassed and the decoded id is\n * re-escaped under default, which re-parses back to the same control id.\n * Default-delimiter senders, the norm, keep the byte-exact overlay echo.)\n * - **ERR**: one segment per supplied {@link AckErrorDetail}: ERR-2 location\n * (when given), ERR-3 the Table 0357 condition code as a CWE\n * (`code^text^HL70357`), ERR-4 the Table 0516 severity.\n *\n * **Fail-safe (roadmap §Phase C).** If the inbound message has no MSH-10, the\n * ACK cannot be correlated. `buildAck` then leaves MSA-2 empty and, if a\n * positive accept (`AA`/`CA`) was requested, **downgrades it** to the matching\n * error code (`AE`/`CE`): it never fabricates an unverifiable positive ACK.\n * The returned message carries an `ACK_NO_CORRELATION_ID` warning. (This is the\n * inbound-side complement to `@cosyte/mllp`'s \"no commit ⇒ never AA\".)\n *\n * Pure aside from the generated control id + timestamp; never throws except on\n * a programming error (`inbound` not an `Hl7Message`, or an unknown `code`).\n *\n * @example\n * ```ts\n * import { buildAck, parseHL7 } from \"@cosyte/hl7\";\n * const inbound = parseHL7(raw);\n * const ack = buildAck(inbound, { code: \"AA\" });\n * console.log(ack.toString()); // MSH|...\\rMSA|AA|<inbound MSH-10>\n * parseHL7(ack.toString()).meta.type; // \"ACK\" (round-trips clean)\n * ```\n */\nexport function buildAck(inbound: Hl7Message, options: BuildAckOptions): Hl7Message {\n if (!(inbound instanceof Hl7Message)) {\n throw new TypeError(\"buildAck: `inbound` must be an Hl7Message (from parseHL7).\");\n }\n if (typeof options.code !== \"string\" || !isKnownAckCode(options.code)) {\n throw new TypeError(\n `buildAck: \\`code\\` must be a known HL7 Table 0008 acknowledgment code ` +\n `(AA/AE/AR/CA/CE/CR). Received: ${JSON.stringify(options.code)}.`,\n );\n }\n\n const enc = DEFAULT_ENCODING_CHARACTERS;\n const meta = inbound.meta;\n\n // Swap the addressing HDs by ALIASING the inbound RAW field objects (not\n // the component-1-only `meta` scalars), so multi-component HDs like\n // `APP^DNS^ISO` survive into the reply intact rather than being truncated.\n // Sharing by reference is safe because every Hl7Message mutation method\n // (setField et al.) is copy-on-write leaf-to-root: neither message can\n // corrupt the other through the shared subtree.\n const msh = inbound.segments(\"MSH\")[0];\n const inboundMsh = (n: number): RawField => msh?.field(n).raw ?? absentField();\n\n // Correlation: MSA-2 echoes the inbound RAW MSH-10 field **verbatim**,\n // not the component-1-only `meta.controlId` scalar. A vendor-quirk control\n // id carrying an unescaped delimiter (`ID^X`) must survive into MSA-2\n // byte-for-byte, or a sender correlating on the raw MSH-10 bytes will\n // never match the ACK (HL7 v2 §2.9.2.2: a mismatch is a correlation\n // failure). Absent/empty → fail-safe path.\n //\n // Escape-fidelity overlay caveat (HL7-ESC): the overlay carries the inbound\n // MSH-10's original wire bytes in the SENDER's delimiter alphabet. This ACK\n // emits with DEFAULT encoding characters, so emitting those bytes verbatim is\n // only correct when the inbound used the default alphabet too: otherwise a\n // raw byte that is a delimiter/escape under DEFAULT (but was plain data or a\n // different escape for the sender) would re-parse into a corrupted, truncated\n // MSA-2 and BREAK correlation. So for a custom-delimiter sender we drop the\n // overlay and re-escape the DECODED value under default (spec-clean, and it\n // re-parses back to the same decoded control id: correlation-correct). A\n // default-delimiter sender (the norm) keeps the overlay and echoes byte-exact.\n const sameEnc = encodingsEqual(inbound.encodingCharacters, enc);\n const rawControlId = sameEnc ? inboundMsh(10) : stripEscapeOverlay(inboundMsh(10));\n const hasCorrelation = rawFieldHasContent(rawControlId);\n\n // Resolve the emitted disposition, applying the no-correlation fail-safe.\n const emittedCode: string = hasCorrelation\n ? options.code\n : isPositiveAck(options.code)\n ? downgradePositiveAck(options.code)\n : options.code;\n\n // ── MSH ────────────────────────────────────────────────────────────────\n const ackType = meta.triggerEvent !== undefined ? `ACK^${meta.triggerEvent}^ACK` : \"ACK\";\n const version = meta.version ?? \"2.5\";\n const processingId = meta.processingId ?? \"P\";\n\n const mshFields: RawField[] = [\n scalarField(enc.field),\n scalarField(\n enc.component + enc.repetition + enc.escape + enc.subcomponent + (enc.truncation ?? \"\"),\n ),\n inboundMsh(5), // MSH-3 sendingApp = inbound MSH-5 (receivingApp)\n inboundMsh(6), // MSH-4 sendingFacility = inbound MSH-6 (receivingFacility)\n inboundMsh(3), // MSH-5 receivingApp = inbound MSH-3 (sendingApp)\n inboundMsh(4), // MSH-6 receivingFacility = inbound MSH-4 (sendingFacility)\n scalarField(formatHl7Timestamp(new Date())), // MSH-7\n absentField(), // MSH-8\n compositeField(ackType), // MSH-9\n scalarField(generateControlId()), // MSH-10\n scalarField(processingId), // MSH-11\n scalarField(version), // MSH-12\n ];\n\n const segments: RawSegment[] = [{ name: \"MSH\", fields: mshFields }];\n\n // ── MSA ────────────────────────────────────────────────────────────────\n // MSA-1 = disposition, MSA-2 = the raw inbound MSH-10 field copied\n // verbatim (empty under the fail-safe).\n segments.push({\n name: \"MSA\",\n fields: [\n absentField(),\n scalarField(emittedCode),\n hasCorrelation ? rawControlId : absentField(),\n ],\n });\n\n // ── ERR (one per supplied detail) ────────────────────────────────────────\n for (const detail of normalizeErrors(options.error)) {\n segments.push(buildErrSegment(detail));\n }\n\n const warnings = hasCorrelation ? [] : [ackNoCorrelationId({ segmentIndex: 0 })];\n\n return new Hl7Message({\n segments,\n encodingCharacters: enc,\n version,\n warnings,\n });\n}\n\n/** Normalize the `error` option to a (possibly empty) array. @internal */\nfunction normalizeErrors(\n error: AckErrorDetail | readonly AckErrorDetail[] | undefined,\n): readonly AckErrorDetail[] {\n if (error === undefined) return [];\n return isErrorArray(error) ? error : [error];\n}\n\n/**\n * Type guard narrowing the `error` union to the array branch. A user-defined\n * guard is needed because `Array.isArray` does not subtract `readonly T[]`\n * from a union on its own.\n * @internal\n */\nfunction isErrorArray(\n error: AckErrorDetail | readonly AckErrorDetail[],\n): error is readonly AckErrorDetail[] {\n return Array.isArray(error);\n}\n\n/**\n * Build one ERR `RawSegment` from an {@link AckErrorDetail}. ERR-3 is the\n * Table 0357 condition code as a CWE (`code^text^HL70357`); ERR-4 is the\n * Table 0516 severity. ERR-1 is left absent (deprecated v2.4 / withdrawn v2.7);\n * ERR-2 carries the optional location.\n * @internal\n */\nfunction buildErrSegment(detail: AckErrorDetail): RawSegment {\n const conditionCode = detail.conditionCode ?? \"207\";\n const severity: string = detail.severity ?? ERR_SEVERITIES.E;\n const text = ERR_CONDITION_CODES[conditionCode] ?? \"\";\n\n // ERR-3 CWE: identifier ^ text ^ name-of-coding-system.\n const err3: RawField = {\n repetitions: [\n {\n components: [\n { subcomponents: [conditionCode] },\n { subcomponents: [text] },\n { subcomponents: [ERR_CONDITION_CODE_SYSTEM] },\n ],\n },\n ],\n isNull: false,\n };\n\n return {\n name: \"ERR\",\n fields: [\n absentField(), // fields[0]: segment-name/separator placeholder slot\n absentField(), // ERR-1 (deprecated v2.4 / withdrawn v2.7)\n detail.location !== undefined ? compositeField(detail.location) : absentField(), // ERR-2 (ERL)\n err3, // ERR-3\n scalarField(severity), // ERR-4\n ],\n };\n}\n\n/**\n * Single plain-string field (empty → absent, matching wire semantics).\n * @internal\n */\nfunction scalarField(value: string): RawField {\n if (value === \"\") return { repetitions: [], isNull: false };\n return { repetitions: [{ components: [{ subcomponents: [value] }] }], isNull: false };\n}\n\n/** Absent field (no content, not null). @internal */\nfunction absentField(): RawField {\n return { repetitions: [], isNull: false };\n}\n\n/**\n * True iff two encoding-character sets are identical across every delimiter\n * (and the optional v2.7+ truncation char). Used to decide whether the inbound\n * MSH-10's escape-fidelity overlay (captured in the sender's alphabet) is safe\n * to echo verbatim under the ACK's DEFAULT alphabet.\n * @internal\n */\nfunction encodingsEqual(a: EncodingCharacters, b: EncodingCharacters): boolean {\n return (\n a.field === b.field &&\n a.component === b.component &&\n a.repetition === b.repetition &&\n a.escape === b.escape &&\n a.subcomponent === b.subcomponent &&\n a.truncation === b.truncation\n );\n}\n\n/**\n * Return a copy of `field` with the HL7-ESC `rawSubcomponents` overlay dropped\n * from every component, so `emitField` re-escapes the DECODED value instead of\n * emitting the sender's raw wire bytes verbatim. Used when the ACK's encoding\n * differs from the inbound's: see the correlation caveat in {@link buildAck}.\n * Returns the field unchanged when it carries no overlay (the common case), so\n * a default-delimiter inbound is untouched.\n * @internal\n */\nfunction stripEscapeOverlay(field: RawField): RawField {\n const hasOverlay = field.repetitions.some((rep) =>\n rep.components.some((comp) => comp.rawSubcomponents !== undefined),\n );\n if (!hasOverlay) return field;\n return {\n repetitions: field.repetitions.map((rep) => ({\n components: rep.components.map((comp) => ({ subcomponents: comp.subcomponents })),\n })),\n isNull: field.isNull,\n };\n}\n\n/**\n * True iff the raw field carries any content at all: at least one non-empty\n * subcomponent in any component of any repetition. Drives the correlation\n * check on the raw MSH-10: a quirky `^X` still correlates (the verbatim echo\n * preserves it), while a genuinely empty/absent field triggers the fail-safe.\n * @internal\n */\nfunction rawFieldHasContent(field: RawField): boolean {\n return field.repetitions.some((rep) =>\n rep.components.some((comp) => comp.subcomponents.some((sub) => sub !== \"\")),\n );\n}\n\n/**\n * MSH-9 composite from a `^`-delimited type string (`ACK^A01^ACK`).\n * @internal\n */\nfunction compositeField(typeString: string): RawField {\n const components = typeString.split(\"^\").map((p) => ({ subcomponents: [p] }));\n return { repetitions: [{ components }], isNull: false };\n}\n","/**\n * `interpretAck`: read-side helper that interprets an inbound HL7 v2\n * acknowledgment (ACK) message into a typed {@link Acknowledgment} view\n * (Phase C). The mechanical inverse of `buildAck`: it reads MSA-1 (code),\n * MSA-2 (the correlated control id), and every ERR segment.\n *\n * Fail-safe: an absent or unrecognized MSA-1 yields `accepted: false`: the\n * interpreter NEVER reports an acknowledgment as accepted on ambiguous input.\n *\n * Spec traceability: HL7 v2 Chapter 2 §2.14.8 (MSA), §2.14.5 (ERR). Codes are\n * surfaced verbatim (Table 0008 / 0357 / 0516): no validation or lookup.\n *\n * Zero runtime deps.\n */\n\nimport { isErrorAck, isPositiveAck, isRejectAck } from \"../builder/ack-tables.js\";\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { Segment } from \"../model/segment.js\";\n\n/**\n * One ERR segment interpreted from an ACK. All fields are surfaced verbatim\n * (no table lookup) and OMITTED when the underlying component is absent\n * (exactOptionalPropertyTypes). Codes/locations only: never PHI.\n */\nexport interface AckErrorEntry {\n /** ERR-3.1: HL7 Table 0357 condition code. */\n readonly conditionCode?: string;\n /** ERR-3.2: condition code display text. */\n readonly conditionText?: string;\n /** ERR-3.3: condition code system name (e.g. `HL70357`). */\n readonly conditionCodeSystem?: string;\n /** ERR-4: HL7 Table 0516 severity (`I`/`W`/`E`). */\n readonly severity?: string;\n /** ERR-2: error location (an HL7 ERL), surfaced verbatim. */\n readonly location?: string;\n}\n\n/**\n * Typed view of an inbound ACK. `accepted` / `error` / `rejected` are derived\n * from MSA-1 against HL7 Table 0008 and are **mutually exclusive**; all three\n * are `false` when MSA-1 is absent or not a recognized code (fail-safe).\n *\n * @example\n * ```ts\n * import { interpretAck, parseHL7 } from \"@cosyte/hl7\";\n * const ack = interpretAck(parseHL7(rawAck));\n * if (ack.accepted) {\n * // safe to consider the message acknowledged\n * } else if (ack.rejected) {\n * for (const e of ack.errors) console.error(e.conditionCode, e.severity);\n * }\n * ```\n */\nexport interface Acknowledgment {\n /** MSA-1 acknowledgment code (HL7 Table 0008), verbatim. Omitted when absent. */\n readonly code?: string;\n /**\n * MSA-2 message control id (the correlated inbound MSH-10), surfaced as the\n * field's **canonical wire text** (`Field.text`): the whole field,\n * delimiters included, never truncated to the first component. Note this is\n * the *re-escaped* form: a properly-escaped id arrives as its wire bytes\n * (`ID\\S\\X`), and an HL7 explicit-null MSA-2 surfaces as the literal\n * two-character `\"\"`. Omitted when absent/empty.\n */\n readonly controlId?: string;\n /** True iff MSA-1 is a positive accept (`AA`/`CA`). */\n readonly accepted: boolean;\n /** True iff MSA-1 is an error acknowledgment (`AE`/`CE`). */\n readonly error: boolean;\n /** True iff MSA-1 is a reject acknowledgment (`AR`/`CR`). */\n readonly rejected: boolean;\n /** Every ERR segment in document order ( `[]` when none ). */\n readonly errors: readonly AckErrorEntry[];\n}\n\n/**\n * Interpret an `Hl7Message` as an acknowledgment. Never throws; a message with\n * no MSA segment yields an all-`false`, empty-`errors` view. The result is\n * deeply frozen.\n *\n * @example\n * ```ts\n * import { interpretAck, parseHL7 } from \"@cosyte/hl7\";\n * const view = interpretAck(parseHL7(\"MSH|^~\\\\&|...\\rMSA|AA|MSG001\"));\n * view.accepted; // true\n * view.controlId; // \"MSG001\"\n * ```\n */\nexport function interpretAck(msg: Hl7Message): Acknowledgment {\n const msa = msg.segments(\"MSA\")[0];\n let code: string | undefined;\n let controlId: string | undefined;\n if (msa !== undefined) {\n const codeValue = msa.field(1).value;\n if (codeValue !== \"\") code = codeValue;\n // MSA-2 is surfaced as the field's VERBATIM wire text (`Field.text`), not\n // the component-1-only `.value`: the correlation id must compare\n // byte-for-byte against the raw MSH-10 the sender transmitted, even when\n // a vendor-quirk id carries an unescaped delimiter (`ID^X`).\n const controlIdValue = msa.field(2).text;\n if (controlIdValue !== \"\") controlId = controlIdValue;\n }\n\n const errors: AckErrorEntry[] = [];\n for (const err of msg.segments(\"ERR\")) {\n errors.push(interpretErr(err));\n }\n\n const out: Acknowledgment = {\n ...(code !== undefined ? { code } : {}),\n ...(controlId !== undefined ? { controlId } : {}),\n accepted: isPositiveAck(code),\n error: isErrorAck(code),\n rejected: isRejectAck(code),\n errors: Object.freeze(errors),\n };\n return Object.freeze(out);\n}\n\n/** Interpret one ERR segment into an {@link AckErrorEntry}. @internal */\nfunction interpretErr(err: Segment): AckErrorEntry {\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const out: Mutable<AckErrorEntry> = {};\n\n // ERR-2 is an ERL (Error Location) composite: `segment ^ sequence ^ field\n // position ^ …`. Surface it verbatim by re-joining its components with the\n // component separator (`.value` would yield only the first component). ERL\n // components are delimiter-free structural tokens, so no unescaping is owed.\n const location = readErl(err);\n if (location !== undefined) out.location = location;\n\n const condition = err.field(3).asCwe();\n if (condition.identifier !== undefined) out.conditionCode = condition.identifier;\n if (condition.text !== undefined) out.conditionText = condition.text;\n if (condition.nameOfCodingSystem !== undefined) {\n out.conditionCodeSystem = condition.nameOfCodingSystem;\n }\n\n const severity = err.field(4).value;\n if (severity !== \"\") out.severity = severity;\n\n return Object.freeze(out);\n}\n\n/**\n * Re-join an ERR-2 ERL composite (`PID^1^5`) from its components. Returns\n * `undefined` when the field is absent or carries no content. @internal\n */\nfunction readErl(err: Segment): string | undefined {\n const rep = err.field(2).repetitions[0];\n if (rep === undefined) return undefined;\n const joined = rep.components.map((c) => c.subcomponents[0] ?? \"\").join(\"^\");\n return joined === \"\" ? undefined : joined;\n}\n","/**\n * Build the multi-line `describe()` output per Plan 06-01 D-04. Omits\n * lines for absent fields (exactOptionalPropertyTypes idiom: mirrors\n * `src/helpers/meta.ts::buildMeta`); lineage rendered as `a → b → c`\n * when more than one name is present.\n *\n * Guaranteed non-empty and always starts with `Profile '<name>'` so the\n * PROF-05 \"contains the profile name\" contract is observable regardless\n * of which lines are omitted.\n *\n * @internal\n */\n\nimport type { Profile } from \"../parser/types.js\";\n\n/**\n * Format a `Profile` as a multi-line human-readable description. Always\n * starts with `Profile '<name>'`: see module-level JSDoc for the full\n * line-per-field layout.\n *\n * @internal\n */\nexport function buildDescribe(p: Profile): string {\n const lines: string[] = [`Profile '${p.name}'`];\n if (p.description !== undefined) {\n lines.push(` description: ${p.description}`);\n }\n const lineage = p.lineage ?? [p.name];\n lines.push(` lineage: ${lineage.join(\" → \")}`);\n if (p.customSegments !== undefined) {\n const keys = Object.keys(p.customSegments);\n lines.push(\n ` customSegments: ${String(keys.length)}` + (keys.length > 0 ? ` (${keys.join(\", \")})` : \"\"),\n );\n }\n if (p.dateFormats !== undefined && p.dateFormats.length > 0) {\n lines.push(` dateFormats: ${String(p.dateFormats.length)}`);\n }\n if (p.onWarning !== undefined) {\n lines.push(\" onWarning: registered\");\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Pure merge helpers consumed by `defineProfile()` when `opts.extends` is\n * supplied. Every helper takes a `readonly parents[]` + a self value and\n * returns the merged result; none mutate input. Implements D-03 (lineage),\n * D-09 (scalar last-wins), D-10 (dateFormats concat+dedupe), D-11\n * (customSegments deep-merge), D-12 (onWarning chain composition).\n *\n * Zero runtime deps. A local `Set` is used for first-occurrence dedup\n * tracking across lineage + dateFormats helpers; `mergeCustomSegments`\n * uses a position-indexed `Map` accumulator so later layers overwrite\n * same-position entries while non-colliding positions survive additively.\n *\n * Post-merge re-validation (D-05 Z-only; D-06 duplicate-name defense-in-\n * depth) is the CALLER's responsibility: these helpers are pure reducers.\n *\n * @internal\n */\n\nimport type { CustomSegmentDefinition, OnWarningCallback, Profile } from \"../parser/types.js\";\n\n/**\n * Normalise the `extends` input to a readonly array. Accepts either a\n * single `Profile` or an array; returns `[]` for `undefined` so callers\n * can treat \"no parents\" identically to \"zero parents\".\n *\n * @internal\n */\nexport function normaliseParents(\n ext: Profile | readonly Profile[] | undefined,\n): readonly Profile[] {\n if (ext === undefined) return [];\n if (Array.isArray(ext)) return ext as readonly Profile[];\n return [ext as Profile];\n}\n\n/**\n * Compute lineage per D-03: flatten parent lineages (or `[parent.name]`\n * when a parent has no lineage), append `selfName`, dedupe preserving\n * first occurrence.\n *\n * @internal\n */\nexport function mergeLineage(parents: readonly Profile[], selfName: string): readonly string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const p of parents) {\n const parentLineage = p.lineage ?? [p.name];\n for (const n of parentLineage) {\n if (!seen.has(n)) {\n seen.add(n);\n out.push(n);\n }\n }\n }\n if (!seen.has(selfName)) out.push(selfName);\n return Object.freeze(out);\n}\n\n/**\n * Merge dateFormats per D-10: concat parents (in order) then child,\n * dedupe preserving first occurrence. Parent formats come first so\n * they're tried FIRST by the TOL-08 cascade (compatible with the\n * \"parent behavior, then child specialization\" layering).\n *\n * @internal\n */\nexport function mergeDateFormats(\n parents: readonly Profile[],\n selfFormats: readonly string[],\n): readonly string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const p of parents) {\n for (const f of p.dateFormats ?? []) {\n if (!seen.has(f)) {\n seen.add(f);\n out.push(f);\n }\n }\n }\n for (const f of selfFormats) {\n if (!seen.has(f)) {\n seen.add(f);\n out.push(f);\n }\n }\n return Object.freeze(out);\n}\n\n/**\n * Merge customSegments per D-11: deep-merge by segment name, then by\n * field position. Fields with distinct positions merge additively; child\n * wins on position conflict. Iteration order is: every parent in order\n * (left-to-right), then self. The child's fields map REPLACES any prior\n * entries whose position collides, but preserves parent entries at\n * non-colliding positions within the same Z-segment.\n *\n * Post-merge re-validation (D-05, D-06) is the CALLER's responsibility,\n * this helper is a pure reducer.\n *\n * @internal\n */\nexport function mergeCustomSegments(\n parents: readonly Profile[],\n selfMap: Readonly<Record<string, CustomSegmentDefinition>>,\n): Readonly<Record<string, CustomSegmentDefinition>> {\n // Accumulate per-segment: position → field-name. Child overrides\n // position collisions; parent position entries at non-colliding\n // positions survive.\n const acc = new Map<string, Map<number, string>>();\n const layer = (map: Readonly<Record<string, CustomSegmentDefinition>> | undefined): void => {\n if (map === undefined) return;\n for (const segName of Object.keys(map)) {\n const entry = map[segName];\n if (entry === undefined) continue;\n let byPos = acc.get(segName);\n if (byPos === undefined) {\n byPos = new Map();\n acc.set(segName, byPos);\n }\n for (const fieldName of Object.keys(entry.fields)) {\n const pos = entry.fields[fieldName];\n if (pos === undefined) continue;\n byPos.set(pos, fieldName); // later layers overwrite earlier\n }\n }\n };\n for (const p of parents) {\n layer(p.customSegments);\n }\n layer(selfMap);\n\n const out: Record<string, CustomSegmentDefinition> = {};\n for (const [segName, byPos] of acc.entries()) {\n const fields: Record<string, number> = {};\n for (const [pos, fieldName] of byPos.entries()) {\n fields[fieldName] = pos;\n }\n out[segName] = Object.freeze({\n fields: Object.freeze(fields),\n });\n }\n return Object.freeze(out);\n}\n\n/**\n * Merge a scalar option per D-09: child value wins when explicitly\n * provided; otherwise the LAST parent with a non-undefined value.\n * Works for `description` today; signature is a generic-keyed shape so\n * future scalars reuse the same helper without rewrites.\n *\n * @internal\n */\nexport function mergeScalar<K extends keyof Profile>(\n parents: readonly Profile[],\n selfValue: Profile[K] | undefined,\n key: K,\n): Profile[K] | undefined {\n if (selfValue !== undefined) return selfValue;\n for (let i = parents.length - 1; i >= 0; i--) {\n const p = parents[i];\n if (p === undefined) continue;\n const v = p[key];\n if (v !== undefined) return v;\n }\n return undefined;\n}\n\n/**\n * Compose an onWarning chain per D-12: invoke every non-undefined\n * handler from parents (in order) then self. Each handler's throws are\n * silently swallowed so a noisy profile cannot break downstream\n * handlers. Returns `undefined` when no handlers are supplied anywhere\n * in the lineage (so `Profile.onWarning` stays optional).\n *\n * @internal\n */\nexport function composeOnWarning(\n handlers: readonly (OnWarningCallback | undefined)[],\n): OnWarningCallback | undefined {\n const concrete = handlers.filter((h): h is OnWarningCallback => h !== undefined);\n if (concrete.length === 0) return undefined;\n return (w) => {\n for (const h of concrete) {\n try {\n h(w);\n } catch {\n /* D-12 silent swallow */\n }\n }\n };\n}\n","/**\n * Validation helpers for `defineProfile()`. Implements the Plan 06-01\n * D-05..D-08 throw paths.\n *\n * Every validator returns `void` on success and throws\n * `ProfileDefinitionError` on failure. The name validator (subject of\n * D-01 fail-fast) is split from the full options validator so\n * `defineProfile()` can call it FIRST and pass `opts.name` to every\n * subsequent throw site.\n *\n * Zero runtime deps: inlined Levenshtein (~15 LoC) + regex + token match.\n *\n * @internal\n */\n\nimport { SUPPORTED_DATE_TOKENS } from \"../parser/dates.js\";\nimport { ProfileDefinitionError } from \"../parser/errors.js\";\nimport type { CustomSegmentDefinition } from \"../parser/types.js\";\n\nimport type { DefineProfileOptions } from \"./define.js\";\n\n/**\n * Z-segment shape: `Z` + 2 uppercase alphanumerics (D-05). Mirrors the\n * `SEGMENT_NAME_RE` convention used in `src/model/message.ts` for\n * addSegment validation: Z-segments are the allowed v1 overlay set.\n *\n * @internal\n */\nconst Z_SEGMENT_RE = /^Z[A-Z0-9]{2}$/u;\n\n/**\n * Known top-level option keys accepted by `defineProfile()` (D-07). Any\n * key outside this list triggers a `ProfileDefinitionError` with an\n * optional Levenshtein-based \"did you mean?\" hint.\n *\n * @internal\n */\nconst KNOWN_OPTION_KEYS: readonly string[] = [\n \"name\",\n \"description\",\n \"dateFormats\",\n \"customSegments\",\n \"onWarning\",\n \"extends\",\n];\n\n/**\n * Regex that matches any of the supported date-format tokens. Used by\n * `validateDateFormats` (D-08) to confirm each user-supplied format string\n * contains at least one recognised token: empty strings and dead formats\n * (`\"YYY/MM\"`, `\"foo\"`) fail fast.\n *\n * @internal\n */\nconst TOKEN_MATCH_RE = new RegExp(`(${SUPPORTED_DATE_TOKENS.join(\"|\")})`, \"u\");\n\n/**\n * Iterative DP Levenshtein distance (edit distance) between two strings.\n * Used by `validateOptionKeys` to generate \"did you mean?\" hints. Zero\n * runtime deps per D-33; kept ≤ 15 LoC excluding the signature.\n *\n * @internal\n */\nfunction levenshtein(a: string, b: string): number {\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n let prev: number[] = [];\n for (let j = 0; j <= b.length; j++) prev.push(j);\n for (let i = 1; i <= a.length; i++) {\n const curr: number[] = [i];\n for (let j = 1; j <= b.length; j++) {\n const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;\n curr.push(Math.min((prev[j] ?? 0) + 1, (curr[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + cost));\n }\n prev = curr;\n }\n return prev[b.length] ?? 0;\n}\n\n/**\n * Validate the profile NAME (D-01 fail-fast). Throws on null/undefined\n * opts, non-string name, empty name, whitespace-only name. Separate from\n * the full options validator so callers can trust `opts.name` by the time\n * downstream throws fire.\n *\n * @internal\n */\nexport function validateProfileName(opts: DefineProfileOptions): void {\n if (opts === null || opts === undefined) {\n throw new ProfileDefinitionError(\n \"defineProfile: options is required and must be an object. \" + `Received: ${String(opts)}.`,\n );\n }\n if (typeof opts.name !== \"string\") {\n throw new ProfileDefinitionError(\n \"defineProfile: 'name' is required and must be a non-empty string. \" +\n `Received: ${JSON.stringify((opts as { name?: unknown }).name)}.`,\n );\n }\n if (opts.name.trim().length === 0) {\n throw new ProfileDefinitionError(\n \"defineProfile: 'name' is required and must be a non-empty string. \" +\n `Received: ${JSON.stringify(opts.name)}.`,\n opts.name,\n );\n }\n}\n\n/**\n * Validate TOP-LEVEL option keys (D-07). Throws on any unknown key with a\n * Levenshtein-based \"did you mean?\" hint when distance ≤ 2 from a known\n * key.\n *\n * @internal\n */\nexport function validateOptionKeys(opts: DefineProfileOptions): void {\n for (const key of Object.keys(opts)) {\n if (KNOWN_OPTION_KEYS.includes(key)) continue;\n let hint: string | undefined;\n for (const known of KNOWN_OPTION_KEYS) {\n if (levenshtein(key, known) <= 2) {\n hint = known;\n break;\n }\n }\n throw new ProfileDefinitionError(\n `Profile '${opts.name}' has unknown option key '${key}'. ` +\n (hint !== undefined ? `Did you mean '${hint}'? ` : \"\") +\n `Known keys: ${KNOWN_OPTION_KEYS.join(\", \")}.`,\n opts.name,\n );\n }\n}\n\n/**\n * Validate a pre-merge customSegments map (D-05): every key MUST be a\n * Z-segment matching `/^Z[A-Z0-9]{2}$/u`, and every field position MUST\n * be a positive integer. Duplicate field-name detection (D-06) is\n * deferred to post-merge validation in Plan 02; for Plan 01's\n * single-profile path, object-literal syntax already rules out literal\n * duplicate keys so a simple presence check is sufficient here.\n *\n * @internal\n */\nexport function validateCustomSegments(\n map: Readonly<Record<string, CustomSegmentDefinition>>,\n profileName: string,\n): void {\n for (const key of Object.keys(map)) {\n if (!Z_SEGMENT_RE.test(key)) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' declares customSegments for '${key}': only Z-segments ` +\n `(Z[A-Z0-9]{2}) are allowed in v1. Typed overlays are a v2 feature.`,\n profileName,\n );\n }\n const entry = map[key];\n if (\n entry === undefined ||\n entry === null ||\n typeof entry.fields !== \"object\" ||\n entry.fields === null\n ) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' customSegments['${key}'] must be an object with a 'fields' map.`,\n profileName,\n );\n }\n for (const fieldName of Object.keys(entry.fields)) {\n const pos = entry.fields[fieldName];\n if (typeof pos !== \"number\" || !Number.isInteger(pos) || pos < 1) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' customSegments['${key}'].fields['${fieldName}'] ` +\n `must be a positive integer (1-indexed). Received: ${JSON.stringify(pos)}.`,\n profileName,\n );\n }\n }\n }\n}\n\n/**\n * Validate date-format strings (D-08): each MUST contain at least one\n * supported token from `SUPPORTED_DATE_TOKENS`. Catches typos like\n * `\"YYY/MM\"` (missing a `Y`) and empty strings before they reach the\n * parser's timestamp cascade.\n *\n * @internal\n */\nexport function validateDateFormats(formats: readonly string[], profileName: string): void {\n for (let i = 0; i < formats.length; i++) {\n const f = formats[i] ?? \"\";\n if (!TOKEN_MATCH_RE.test(f)) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' dateFormats[${String(i)}] = ${JSON.stringify(f)} is malformed: ` +\n `must contain at least one of ${SUPPORTED_DATE_TOKENS.join(\"/\")}.`,\n profileName,\n );\n }\n }\n}\n\n/**\n * Post-merge D-06 DEFENSE-IN-DEPTH check: within a single segment, the\n * SAME field name MUST NOT resolve to DIFFERENT positions. Cross-\n * position aliasing (two names, same position) is allowed: that's\n * intentional convenience.\n *\n * **Runtime observation:** Given the current `mergeCustomSegments`\n * strategy (accumulator keyed by position, where later layers overwrite\n * same-position entries), a name cannot survive at two positions: if a\n * parent has `{ a: 3 }` and a child has `{ a: 5 }`, the accumulator\n * produces `{ 3: \"a\", 5: \"a\" }` which lowers to `{ a: 5 }` (the second\n * assignment wins inside the final `Record`). If a parent has\n * `{ a: 3, b: 3 }` (two names at the same position: legal) and the\n * child has `{ a: 5 }`, the accumulator produces `{ 3: \"b\", 5: \"a\" }` →\n * output `{ a: 5, b: 3 }`; `a` maps to ONE position (5), no violation.\n * Therefore this validator never fires under the present strategy.\n *\n * It stays as code-level defense-in-depth because (a) it is cheap\n * (O(N) over fields of the merged map) and (b) if a future contributor\n * changes `mergeCustomSegments` to a name-keyed accumulator (e.g. to\n * preserve \"last write per name\" semantics that could allow a name to\n * remain at two positions), this validator becomes reachable and\n * catches the bug before the profile ships. The test suite asserts\n * the validator's presence and contract; it intentionally does NOT\n * assert that `defineProfile` throws through the current merge path for\n * a duplicate-name-different-position case, because that case is\n * unreachable today.\n *\n * @internal\n */\nexport function validateUniqueFieldNames(\n map: Readonly<Record<string, CustomSegmentDefinition>>,\n profileName: string,\n): void {\n for (const segName of Object.keys(map)) {\n const entry = map[segName];\n if (entry === undefined) continue;\n const positionsByName = new Map<string, number>();\n for (const fieldName of Object.keys(entry.fields)) {\n const pos = entry.fields[fieldName];\n if (pos === undefined) continue;\n const prior = positionsByName.get(fieldName);\n if (prior !== undefined && prior !== pos) {\n throw new ProfileDefinitionError(\n `Profile '${profileName}' customSegments['${segName}']: field name '${fieldName}' ` +\n `maps to BOTH position ${String(prior)} AND position ${String(pos)} after extends merge. ` +\n `Each field name within a segment must map to exactly one position.`,\n profileName,\n );\n }\n positionsByName.set(fieldName, pos);\n }\n }\n}\n","/**\n * `defineProfile()`: public factory for building `Profile` objects with\n * validation + `describe()` attached (PROF-01, PROF-04, PROF-05).\n *\n * Wave 1 (Plan 06-01) ships the single-profile (no-extends) path;\n * Wave 2 (Plan 06-02) fills in `extends` + merge semantics by extending\n * this factory's body. For Wave 1, `opts.extends` is ACCEPTED but\n * IGNORED, resulting in `lineage === [opts.name]` regardless.\n *\n * Zero runtime deps. Matches CLAUDE.md engineering guardrails: no `any`,\n * JSDoc `@example` on every public export, immutability at the return\n * boundary via `Object.freeze`, short testable helpers split across\n * `validate.ts` + `describe.ts`.\n *\n * Type ownership: `CustomSegmentDefinition` is declared CANONICALLY in\n * `src/parser/types.ts` (alongside `Profile`) and re-exported from THIS\n * module so `@cosyte/hl7` consumers can reach it via either entry\n * point. Single source of truth; no circular type imports.\n */\n\nimport type { CustomSegmentDefinition, OnWarningCallback, Profile } from \"../parser/types.js\";\n\nimport { buildDescribe } from \"./describe.js\";\nimport {\n composeOnWarning,\n mergeCustomSegments,\n mergeDateFormats,\n mergeLineage,\n mergeScalar,\n normaliseParents,\n} from \"./merge.js\";\nimport {\n validateCustomSegments,\n validateDateFormats,\n validateOptionKeys,\n validateProfileName,\n validateUniqueFieldNames,\n} from \"./validate.js\";\n\n/**\n * Re-export of the canonical `CustomSegmentDefinition` type (declared in\n * `src/parser/types.ts`) so profile authors importing from the profile\n * module get the same type identity as those importing from the package\n * barrel. Profile authors annotate Z-segment declarations with this type.\n *\n * @example\n * ```ts\n * import type { CustomSegmentDefinition } from \"@cosyte/hl7\";\n * const zdp: CustomSegmentDefinition = {\n * fields: { departmentCode: 3, departmentName: 4 },\n * };\n * ```\n */\nexport type { CustomSegmentDefinition } from \"../parser/types.js\";\n\n/**\n * Options accepted by `defineProfile()` (D-02). Mirrors the locked\n * `Profile` shape plus the `extends` input key. Every field except\n * `name` is optional.\n *\n * @example\n * ```ts\n * import { defineProfile, type DefineProfileOptions } from \"@cosyte/hl7\";\n * const opts: DefineProfileOptions = {\n * name: \"my-lab\",\n * dateFormats: [\"MM/DD/YYYY\"],\n * customSegments: { ZLB: { fields: { noteText: 3 } } },\n * };\n * const profile = defineProfile(opts);\n * ```\n */\nexport interface DefineProfileOptions {\n readonly name: string;\n readonly description?: string;\n readonly dateFormats?: readonly string[];\n readonly customSegments?: Readonly<Record<string, CustomSegmentDefinition>>;\n readonly onWarning?: OnWarningCallback;\n readonly extends?: Profile | readonly Profile[];\n}\n\n/**\n * Build a readonly `Profile` from a validated options object. Invalid\n * input throws `ProfileDefinitionError` with an actionable message\n * (PROF-02): bad Z-segment names (D-05), malformed date formats (D-08),\n * unknown top-level keys with typo hints (D-07), and missing/empty\n * name.\n *\n * Wave 1 (Plan 06-01) ships the no-extends path: `opts.extends` is\n * ACCEPTED but IGNORED, resulting in `lineage === [opts.name]`\n * regardless. Wave 2 (Plan 06-02) adds full lineage computation + merge\n * semantics.\n *\n * @example\n * ```ts\n * import { defineProfile } from \"@cosyte/hl7\";\n * const epic = defineProfile({\n * name: \"epic\",\n * description: \"Epic-specific quirks and ADT date formats\",\n * dateFormats: [\"MM/DD/YYYY HH:mm:ss\", \"MM/DD/YYYY\"],\n * customSegments: {\n * ZDP: { fields: { departmentCode: 3, departmentName: 4 } },\n * ZRS: { fields: { resultStatus: 1, statusDateTime: 2 } },\n * },\n * });\n * console.log(epic.name); // \"epic\"\n * console.log(epic.lineage); // [\"epic\"]\n * console.log(epic.describe?.());\n * ```\n */\nexport function defineProfile(opts: DefineProfileOptions): Profile {\n // D-01 fail-fast: name validation FIRST so downstream throws can\n // include `opts.name` as the second `ProfileDefinitionError` ctor arg.\n validateProfileName(opts);\n validateOptionKeys(opts);\n\n // Pre-merge: validate self-declared customSegments + dateFormats in\n // isolation so errors surface with the offending profile's own name\n // (not \"after merge\": a user hitting D-05 should see their own\n // profile flagged, not the composed lineage).\n const selfCustomSegments = opts.customSegments ?? {};\n validateCustomSegments(selfCustomSegments, opts.name);\n const selfDateFormats = opts.dateFormats ?? [];\n validateDateFormats(selfDateFormats, opts.name);\n\n // D-03 + D-09..D-12: full merge. Plan 06-02 replaces the Wave-1\n // lineage stub with this block.\n const parents = normaliseParents(opts.extends);\n const lineage = mergeLineage(parents, opts.name);\n const dateFormats = mergeDateFormats(parents, selfDateFormats);\n const customSegments = mergeCustomSegments(parents, selfCustomSegments);\n const description = mergeScalar(parents, opts.description, \"description\");\n const onWarning = composeOnWarning([...parents.map((p) => p.onWarning), opts.onWarning]);\n\n // Post-merge re-validation. `validateCustomSegments` catches the D-05\n // rogue-parent scenario (a hand-crafted Profile bypassing\n // defineProfile whose customSegments contains a non-Z key).\n // `validateUniqueFieldNames` is installed as DEFENSE-IN-DEPTH: it is\n // unreachable via the present mergeCustomSegments strategy (position-\n // indexed accumulator collapses same-name-different-position cases\n // to a single entry) but guards against future merge-strategy\n // changes. Both validators are O(N) over the merged map and run once\n // per defineProfile call.\n validateCustomSegments(customSegments, opts.name);\n validateUniqueFieldNames(customSegments, opts.name);\n\n // Assemble the frozen Profile. exactOptionalPropertyTypes discipline:\n // conditionally assign optional fields rather than writing\n // `description: undefined`. Mirrors `src/helpers/meta.ts::buildMeta`\n // lines 38-73: the consistent pattern across the codebase.\n type Mutable<T> = { -readonly [K in keyof T]?: T[K] };\n const profile: Mutable<Profile> = {\n name: opts.name,\n lineage,\n customSegments,\n dateFormats,\n };\n if (description !== undefined) profile.description = description;\n if (onWarning !== undefined) profile.onWarning = onWarning;\n\n // D-04: `describe()` attached as a method: closes over the assembled\n // profile object so calling `.describe()` always reflects the\n // fully-assembled state (not a half-built intermediate).\n const finalised: Profile = profile as Profile;\n profile.describe = (): string => buildDescribe(finalised);\n\n // W5 boundary-freeze: top-level only. Inner `customSegments` /\n // `lineage` / `dateFormats` stay `readonly` at the type level but\n // mutable at runtime per D-30 cost doctrine (matches Phase 5\n // `src/serialize/to-json.ts:139`).\n return Object.freeze(profile) as Profile;\n}\n","/**\n * athenahealth Interop API HL7 quirks. Ships US-short-date format\n * (`MM/DD/YYYY`) commonly used in athena ADT outbound. One Z-segment:\n * `ZCA` (care team membership). BIP-04.\n *\n * The AM/PM meridian variant (`MM/DD/YYYY HH:mm AM/PM`) is intentionally\n * NOT shipped: the library's format-token set does not include AM/PM\n * (`SUPPORTED_DATE_TOKENS` = YYYY/MM/DD/HH/mm/ss/SSSS). Consumers needing\n * meridian support can extend this profile or supply their own format\n * handler.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.athena);\n * const zca = msg.allSegments().find((s) => s.type === \"ZCA\");\n * console.log(zca?.get(\"providerName\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in athenahealth Interop profile (BIP-04). See file header for\n * rationale; use via `parseHL7(raw, profiles.athena)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.athena);\n * ```\n */\nexport const athena = defineProfile({\n name: \"athena\",\n description: \"athenahealth Interop: US-short-date format and care-team Z-segment\",\n dateFormats: [\"MM/DD/YYYY\"],\n customSegments: {\n ZCA: { fields: { careTeamRole: 3, providerId: 5, providerName: 6 } },\n },\n});\n","/**\n * Cerner Millennium HL7 quirks. Ships ISO-8601-with-T format\n * (`YYYY-MM-DDTHH:mm:ss`) plus ISO-date-only (`YYYY-MM-DD`), observed\n * across Millennium's native outbound feeds. Z-segments: `ZDS`\n * (discharge summary text) and `ZCO` (comment overflow for long fields).\n * BIP-02.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.cerner);\n * const zds = msg.allSegments().find((s) => s.type === \"ZDS\");\n * console.log(zds?.get(\"summaryText\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Cerner Millennium profile (BIP-02). See file header for\n * rationale; use via `parseHL7(raw, profiles.cerner)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.cerner);\n * ```\n */\nexport const cerner = defineProfile({\n name: \"cerner\",\n description: \"Cerner Millennium: ISO-style timestamps and common Z-segments\",\n dateFormats: [\"YYYY-MM-DDTHH:mm:ss\", \"YYYY-MM-DD\"],\n customSegments: {\n ZDS: { fields: { summaryText: 3 } },\n ZCO: { fields: { commentText: 3, continuationFlag: 5 } },\n },\n});\n","/**\n * Epic Bridges Interconnect HL7 quirks. Ships non-HL7 date formats\n * (`MM/DD/YYYY HH:mm:ss`, `MM/DD/YYYY`) commonly seen in ADT outbound\n * feeds, plus two Z-segments: `ZDP` (department context) and `ZRS`\n * (result status). BIP-01.\n *\n * Authored from the public `defineProfile()` API: zero privileged\n * internal coupling. Consumers extend this profile via\n * `defineProfile({ name: '...', extends: profiles.epic, ... })`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.epic);\n * const zdp = msg.allSegments().find((s) => s.type === \"ZDP\");\n * console.log(zdp?.get(\"departmentCode\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Epic Bridges Interconnect profile (BIP-01). See file header\n * for rationale; use via `parseHL7(raw, profiles.epic)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.epic);\n * ```\n */\nexport const epic = defineProfile({\n name: \"epic\",\n description: \"Epic Bridges Interconnect: ADT-style date formats and common Z-segments\",\n dateFormats: [\"MM/DD/YYYY HH:mm:ss\", \"MM/DD/YYYY\"],\n customSegments: {\n ZDP: { fields: { departmentCode: 3, departmentName: 4 } },\n ZRS: { fields: { resultStatus: 1, statusDateTime: 2 } },\n },\n});\n","/**\n * Generic reference-laboratory shape (LabCorp / Quest-style). Ships two\n * non-HL7 date formats: `YYYYMMDD HHmm` (ASTM-era space-separated) and\n * `YYYY-MM-DD` (ISO date-only). Two Z-segments: `ZLB` (lab-override\n * flags) and `ZNT` (lab note). BIP-05.\n *\n * The canonical HL7 format `YYYYMMDDHHmmss` is NOT shipped here: it's\n * already the parser's primary (zero-warning) match for TS/DTM.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.genericLab);\n * const znt = msg.allSegments().find((s) => s.type === \"ZNT\");\n * console.log(znt?.get(\"noteText\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in generic reference-laboratory profile (BIP-05). See file\n * header for rationale; use via `parseHL7(raw, profiles.genericLab)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.genericLab);\n * ```\n */\nexport const genericLab = defineProfile({\n name: \"genericLab\",\n description: \"Generic reference-laboratory: ASTM-era + ISO-date formats + lab Z-segments\",\n dateFormats: [\"YYYYMMDD HHmm\", \"YYYY-MM-DD\"],\n customSegments: {\n ZLB: { fields: { specimenOverride: 3, methodOverride: 5 } },\n ZNT: { fields: { noteText: 3 } },\n },\n});\n","/**\n * MEDITECH (MAGIC / 6.x / Expanse) HL7 quirks. Ships minute-precision\n * timestamps (`YYYYMMDDHHMM`, no seconds) and two DFT charge-capture\n * Z-segments: `ZF1` (provider-encounter copay data) and `ZF2`\n * (encounter-procedure data). BIP-03.\n *\n * Grounded in **publicly downloadable** MEDITECH interface specifications\n * (ADR 0018: public specs count as real artifacts), not invented:\n *\n * - The **minute-precision** date/time format is confirmed by *two*\n * public MEDITECH specs: \"MEDITECH Admissions and Registration to Other\n * Vendor Ancillary\" (Version 2.4, © 2021 Medical Information Technology,\n * Inc.) (\"Date and Time in Admissions. Format is YYYYMMDDHHMM\") and\n * \"MEDITECH Ancillary Charges (LAB/PHA/ITS/IDM)\" (Version 2.1, © 2021),\n * whose MSH-7 is length **12** (= `YYYYMMDDHHMM`) and whose EVN-2/PID-7\n * are documented \"Format is YYYYMMDDHHMM\". Minute precision is\n * HL7-conformant (TS/DTM permit variable precision), so declaring it here\n * is not about accepting an illegal value: it records MEDITECH's\n * characteristic no-seconds convention so date resolution across a\n * MEDITECH feed is explicit rather than incidental.\n * - `ZF1` and `ZF2` are the DFT (charge) Z-segments defined verbatim in\n * the Ancillary Charges spec (Version 2.1): `ZF1` = \"PROVIDER ENCOUNTER\n * COPAY DATA\" (ZF1-1 PROVIDER ENCOUNTER, ZF1-2 MIS SERVICE GROUP, ZF1-3\n * SERVICE GROUP COPAY, ZF1-4 VISIT COPAY, ZF1-5 COPAY MINIMUM, ZF1-6\n * COPAY MAXIMUM); `ZF2` = \"ENCOUNTER PROCEDURE DATA\" (ZF2-1 SET ID, ZF2-2\n * PROVIDER ENCOUNTER, ZF2-3 ENCOUNTER DATE, ZF2-4 ENCOUNTER PROCEDURE,\n * ZF2-5 ENCOUNTER PROCEDURE QUANTITY, ZF2-6 ENCOUNTER PROCEDURE CHARGE,\n * ZF2-7 PRV PROCEDURE AMOUNT PAID, ZF2-8 PRV PROCEDURE AMOUNT DUE).\n *\n * (This replaced an earlier `ZVI` \"visit info\" segment that was a\n * community-sourced prior with no citable public grounding: HL7-I\n * re-grounding, ADR 0018. Field positions here are transcribed directly\n * from the spec's segment tables.)\n *\n * Authored from the public `defineProfile()` API: zero privileged\n * internal coupling. Consumers extend this profile via\n * `defineProfile({ name: '...', extends: profiles.meditech, ... })`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.meditech);\n * const zf1 = msg.allSegments().find((s) => s.type === \"ZF1\");\n * console.log(zf1?.get(\"visitCopay\")?.value);\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in MEDITECH MAGIC/6.x/Expanse profile (BIP-03). See file header for\n * rationale and spec citations; use via `parseHL7(raw, profiles.meditech)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.meditech);\n * ```\n */\nexport const meditech = defineProfile({\n name: \"meditech\",\n description:\n \"MEDITECH MAGIC/6.x/Expanse: minute-precision timestamps and DFT charge Z-segments (ZF1/ZF2)\",\n dateFormats: [\"YYYYMMDDHHmm\"],\n customSegments: {\n ZF1: {\n fields: {\n providerEncounter: 1,\n misServiceGroup: 2,\n serviceGroupCopay: 3,\n visitCopay: 4,\n copayMinimum: 5,\n copayMaximum: 6,\n },\n },\n ZF2: {\n fields: {\n setId: 1,\n providerEncounter: 2,\n encounterDate: 3,\n encounterProcedure: 4,\n encounterProcedureQuantity: 5,\n encounterProcedureCharge: 6,\n prvProcedureAmountPaid: 7,\n prvProcedureAmountDue: 8,\n },\n },\n },\n});\n","/**\n * Philips Vue PACS (\"IS Link\") imaging HL7 interface quirks. The Vue PACS\n * IS Link component receives RIS-side ORM/ADT feeds and carries its\n * PACS-specific data in six custom Z-segments the HL7 standard does not\n * define: one per *filler role*:\n *\n * - **`ZDS`**: Order Filler: the DICOM **Study Instance UID** (field 1,\n * first component), the RIS↔PACS bridge (as in the IHE Radiology TF and\n * the `visage` profile); IS Link uses it to update the accession number.\n * - **`ZLK`**: Order Filler: study/order **linking** ids (external\n * workitem id, order link id) that group studies and orders.\n * - **`ZAO`**: Order Filler: order **additional details** (a base64 XML\n * key/value blob) plus modality, body part, transfer/acquisition status,\n * technician + radiologist names/ids, and vendor \"custom\" string/number/\n * date slots.\n * - **`ZEB`**: Patient Filler: an **encrypted** patient-info blob (base64).\n * - **`ZAP`**: Patient Filler: patient **additional details** (base64 XML)\n * plus patient \"custom\" string/number/date slots.\n * - **`ZAV`**: Visit Filler: visit **additional details** (base64 XML).\n *\n * Grounded in the public **Vue PACS 12.2.8 HL7 Interface Specifications**\n * (Philips, document HA1669 Rev A), §§5.11–5.16: a publicly downloadable\n * vendor interface spec, not an invented quirk (ADR 0018). The spec's\n * `TS` timestamps are the HL7-native `YYYYMMDDHHMMSS` form (§2.6), so this\n * profile declares **no** custom `dateFormats`: only the Z-segments.\n *\n * Field positions are transcribed verbatim from the spec's segment tables,\n * including two of its own gaps/quirks: `ZAO` has **no field 7** (the table\n * jumps 6 → 8) and `ZAP` has **no field 2** (jumps 1 → 3); the three\n * `ZAO`/`ZAP` \"Custom Date\" rows are all printed \"…Date 1\" in the spec (a\n * transcription slip) but sit at consecutive positions, so they are named\n * `…CustomDate1/2/3` here to keep each field name unique.\n *\n * `ZEB` holds *encrypted* patient information and `ZAP`/`ZAV` carry\n * patient/visit blobs: naming the field is exactly how a consumer learns\n * that segment is PHI-bearing and must not be logged. This profile only\n * *names* the fields; it never decodes, decrypts, or rewrites them.\n *\n * Authored from the public `defineProfile()` API: zero privileged internal\n * coupling. Consumers extend this profile via\n * `defineProfile({ name: '...', extends: profiles.philips, ... })`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.philips);\n * const zds = msg.allSegments().find((s) => s.type === \"ZDS\");\n * console.log(zds?.get(\"studyInstanceUid\")?.value); // \"1.2.826.0.1.3680043.10.99999.20250326.7\"\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Philips Vue PACS (\"IS Link\") imaging profile (BIP-08). See file\n * header for rationale; use via `parseHL7(raw, profiles.philips)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.philips);\n * ```\n */\nexport const philips = defineProfile({\n name: \"philips\",\n description:\n \"Philips Vue PACS (IS Link) imaging: ZDS/ZLK/ZAO/ZEB/ZAP/ZAV order/patient/visit-filler Z-segments\",\n customSegments: {\n // §5.11 ZDS: Order Filler: DICOM Study Instance UID (RP, comp 1).\n ZDS: { fields: { studyInstanceUid: 1 } },\n // §5.12 ZLK: Order Filler: study/order linking ids.\n ZLK: { fields: { externalWorkitemId: 1, orderLinkId: 2 } },\n // §5.13 ZAO: Order Filler: order additional details (note: no field 7).\n ZAO: {\n fields: {\n orderAdditionalDetails: 1,\n orderWithNoImages: 2,\n modality: 3,\n bodyPart: 4,\n resultTransferStatus: 5,\n departmentId: 6,\n device: 8,\n section: 9,\n orderCustomString1: 10,\n orderCustomString2: 11,\n orderCustomString3: 12,\n orderCustomString4: 13,\n orderCustomString5: 14,\n orderCustomString6: 15,\n orderCustomString7: 16,\n orderCustomNumber1: 17,\n orderCustomNumber2: 18,\n orderCustomDate1: 19,\n orderCustomDate2: 20,\n orderCustomDate3: 21,\n technicianFamilyName: 22,\n technicianGivenName: 23,\n technicianMiddleName: 24,\n technicianId: 25,\n radiologistFamilyName: 26,\n radiologistGivenName: 27,\n radiologistMiddleName: 28,\n radiologistId: 29,\n orderCreatedBy: 30,\n orderUpdatedBy: 31,\n acquisitionStatus: 32,\n },\n },\n // §5.14 ZEB: Patient Filler: encrypted patient-info blob (PHI-bearing).\n ZEB: { fields: { encryptedPatientInfo: 1 } },\n // §5.15 ZAP: Patient Filler: patient additional details (note: no field 2).\n ZAP: {\n fields: {\n patientAdditionalDetails: 1,\n patientCustomString1: 3,\n patientCustomString2: 4,\n patientCustomString3: 5,\n patientCustomString4: 6,\n patientCustomString5: 7,\n patientCustomString6: 8,\n patientCustomString7: 9,\n patientCustomNumber1: 10,\n patientCustomNumber2: 11,\n patientCustomDate1: 12,\n patientCustomDate2: 13,\n patientCustomDate3: 14,\n },\n },\n // §5.16 ZAV: Visit Filler: visit additional details.\n ZAV: { fields: { visitAdditionalDetails: 1 } },\n },\n});\n","/**\n * VA VistA Radiology / Nuclear Medicine imaging HL7 interface quirks. The\n * Veterans Affairs VistA Radiology package exchanges HL7 **v2.4** messages\n * with commercial RIS/PACS systems and carries the DICOM **Study Instance\n * UID** in a `ZDS` Z-segment (field 1, `RP` \"Reference Pointer\" composite,\n * the UID sits in the first component, ZDS-1.1 \"Pointer\"), so the receiving\n * image manager can correlate the HL7 order/result with the DICOM study.\n * This is the same IHE Radiology cross-vendor bridge segment declared by the\n * `visage` and `philips` profiles: `ZDS` is an IHE extension, not a\n * VA-proprietary quirk; the value this profile adds is a **named federal\n * source** grounded in a distinct public spec, plus coverage of the shape the\n * VA spec documents that the imaging-vendor specs do not: `ZDS` on **ORU**\n * result messages (VistA sends `ZDS` in **both ORM and ORU**), not just on\n * the ORM order.\n *\n * Grounded in the public **Radiology/Nuclear Medicine 5.0 HL7 Interface\n * Specification** (Version 3.6, revised for Patch RA*5.0*203, June 2024, U.S.\n * Department of Veterans Affairs), which documents \"ZDS Segment Fields in ORU\n * and ORM\" with `ZDS-1` = Study Instance UID (`RP`: 1.1 Pointer, 1.2\n * Application ID, 1.3 Type of Data, 1.4 Subtype). It is a publicly\n * downloadable federal interface spec on the VA VistA Documentation Library\n * (`va.gov/vdl`), not an invented quirk (ADR 0018). The spec's messaging is\n * HL7-native v2.4, so its `TS` timestamps use the `YYYYMMDDHHMMSS` form: this\n * profile therefore declares **no** custom `dateFormats`, only the ZDS\n * segment.\n *\n * Authored from the public `defineProfile()` API: zero privileged internal\n * coupling. Consumers extend this profile via\n * `defineProfile({ name: '...', extends: profiles.va, ... })`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.va);\n * const zds = msg.allSegments().find((s) => s.type === \"ZDS\");\n * console.log(zds?.get(\"studyInstanceUid\")?.value); // \"1.2.826.0.1.3680043.10.99999.20250326.9\"\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in VA VistA Radiology / Nuclear Medicine imaging profile (BIP-09).\n * See file header for rationale; use via `parseHL7(raw, profiles.va)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.va);\n * ```\n */\nexport const va = defineProfile({\n name: \"va\",\n description:\n \"VA VistA Radiology/Nuclear Medicine imaging: ZDS DICOM Study Instance UID segment (ORM + ORU, IHE RAD)\",\n customSegments: {\n // ZDS-1 = Study Instance UID (RP), UID in the first component (1.1 Pointer).\n // VA Radiology/Nuclear Medicine 5.0 HL7 IS v3.6 (June 2024): \"ZDS Segment\n // Fields in ORU and ORM\".\n ZDS: { fields: { studyInstanceUid: 1 } },\n },\n});\n","/**\n * Visage 7 imaging/PACS HL7 interface quirks. Radiology/PACS order feeds\n * carry the DICOM **Study Instance UID** in a `ZDS` Z-segment (field 1,\n * first component) so the receiving image manager can correlate the HL7\n * order with the DICOM study: the classic RIS/PACS ↔ HL7 bridge segment\n * defined by the IHE Radiology Technical Framework. BIP-07.\n *\n * Grounded in the public **Visage 7 – HL7 Interface Specification**\n * (V23.00, Jun 2026, Visage Imaging GmbH), §4.4 \"ORM Messages\" + the ZDS\n * segment table (\"Study Instance UID … contained in the first component of\n * the first field of the ZDS Segment\"): a publicly downloadable vendor\n * interface spec, not an invented quirk (ADR 0018). Dates in that spec use\n * the HL7-native `YYYYMMDDHHMMSS` form, so this profile declares **no**\n * custom `dateFormats`: only the ZDS segment.\n *\n * Authored from the public `defineProfile()` API: zero privileged internal\n * coupling. Consumers extend this profile via\n * `defineProfile({ name: '...', extends: profiles.visage, ... })`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.visage);\n * const zds = msg.allSegments().find((s) => s.type === \"ZDS\");\n * console.log(zds?.get(\"studyInstanceUid\")?.value); // \"1.2.826.0.1.3680043.10.99999.20250326.1\"\n * ```\n */\n\nimport { defineProfile } from \"./define.js\";\n\n/**\n * Built-in Visage 7 imaging/PACS profile (BIP-07). See file header for\n * rationale; use via `parseHL7(raw, profiles.visage)`.\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.visage);\n * ```\n */\nexport const visage = defineProfile({\n name: \"visage\",\n description: \"Visage 7 imaging/PACS: ZDS DICOM Study Instance UID segment (IHE RAD)\",\n customSegments: {\n ZDS: { fields: { studyInstanceUid: 1 } },\n },\n});\n","/**\n * Public barrel for the `@cosyte/hl7` profile subsystem. Assembles\n * the `profiles` namespace object (8 built-ins) and re-exports the public\n * profile API: `defineProfile`, `setDefaultProfile`, `getDefaultProfile`,\n * plus the two type exports `DefineProfileOptions` and\n * `CustomSegmentDefinition`.\n *\n * D-26 contract: individual built-ins are NOT top-level named exports,\n * consumers access them via `profiles.epic`, `profiles.cerner`, etc.\n * (\"epic\" is too generic a name for a top-level export.)\n */\n\nexport { defineProfile } from \"./define.js\";\nexport type { DefineProfileOptions, CustomSegmentDefinition } from \"./define.js\";\nexport { setDefaultProfile, getDefaultProfile } from \"./default.js\";\n\nimport { athena } from \"./athena.js\";\nimport { cerner } from \"./cerner.js\";\nimport { epic } from \"./epic.js\";\nimport { genericLab } from \"./genericLab.js\";\nimport { meditech } from \"./meditech.js\";\nimport { philips } from \"./philips.js\";\nimport { va } from \"./va.js\";\nimport { visage } from \"./visage.js\";\n\n/**\n * Namespace object exposing the 8 shipped built-in vendor profiles (epic,\n * cerner, meditech, athena, genericLab, visage, philips, va). Each is authored\n * via the public `defineProfile()` API (BIP-01..09).\n *\n * @example\n * ```ts\n * import { parseHL7, profiles } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw, profiles.epic);\n * console.log(msg.profile?.name); // \"epic\"\n * ```\n */\nexport const profiles = Object.freeze({\n athena,\n cerner,\n epic,\n genericLab,\n meditech,\n philips,\n va,\n visage,\n}) as {\n readonly athena: typeof athena;\n readonly cerner: typeof cerner;\n readonly epic: typeof epic;\n readonly genericLab: typeof genericLab;\n readonly meditech: typeof meditech;\n readonly philips: typeof philips;\n readonly va: typeof va;\n readonly visage: typeof visage;\n};\n","/**\n * Coding-system provenance (HL7 Table 0396, READ-ONLY): roadmap Phase F.\n *\n * Answers one question about a coded element: **\"what coding system does this\n * code CLAIM?\"** It surfaces the sender's CWE.3 / CE.3 \"Name of Coding System\"\n * value, normalizes well-known aliases to the registered Table 0396 acronym,\n * and reports a canonical human-readable name. It is provenance only:\n *\n * - **No validation.** It does not check that the code exists in the claimed\n * system, nor that the system is current. A wrong-but-registered code\n * (e.g. a deleted LOINC) still reports `known: true` for LOINC.\n * - **No lookup, no network, no bundled codeset.** Zero runtime deps; this is\n * a frozen acronym→name map, nothing more.\n * - **Fail-safe.** An unregistered / local / mistyped system id is surfaced\n * **verbatim** with `known: false`: never dropped, never guessed.\n *\n * Because provenance is the *sender's claim*, not a verified fact, a consumer\n * MUST still treat the code per its own trust policy. The value of this module\n * is letting that consumer ask \"which system?\" before interpreting a code: a\n * \"PCN\" allergen or an \"I10\" diagnosis is only safe to read once you know the\n * system it belongs to.\n *\n * Spec traceability: HL7 Table 0396 (Coding System): the registry of\n * coding-system acronyms carried in the CWE.3 / CE.3 component. v2.7+ expects\n * the registered acronym. See `docs-content/spec-notes-coding-system.md` for\n * the per-entry source and the `I10` (ICD-10 vs ICD-10-CM) nuance.\n *\n * Zero runtime deps: pure data + pure functions.\n */\n\n/**\n * One recognized HL7 Table 0396 coding system: its registered acronym (the\n * value expected in CWE.3 / CE.3), a canonical human-readable name, and the\n * widely-used aliases tolerated for it. Aliases are matched case-insensitively.\n */\nexport interface KnownCodingSystem {\n /** Registered Table 0396 acronym, e.g. `\"LN\"`. */\n readonly id: string;\n /** Canonical human-readable name, e.g. `\"LOINC\"`. */\n readonly name: string;\n /**\n * Widely-used alternative spellings that claim the same system (matched\n * case-insensitively), e.g. `\"LOINC\"` for `LN`. The registered `id` itself\n * is always recognized and need not be repeated here.\n */\n readonly aliases: readonly string[];\n}\n\n/**\n * The safety-relevant subset of HL7 Table 0396 this library recognizes for\n * provenance. Deliberately small and frozen: it is NOT the full Table 0396\n * registry. Each entry's source is recorded in\n * `docs-content/spec-notes-coding-system.md`.\n *\n * Note on `I10`: Table 0396 registers `I10` as **ICD-10** (the WHO base\n * classification). US v2 feeds frequently send `I10` when they mean\n * ICD-10-**CM**, but that clinical-modification specificity is the sender's\n * convention, not what the acronym registers: so this map reports the\n * registered claim (`\"ICD-10\"`) and does not silently upgrade it to CM.\n *\n * @example\n * ```ts\n * import { KNOWN_CODING_SYSTEMS } from \"@cosyte/hl7\";\n * console.log(KNOWN_CODING_SYSTEMS.find((s) => s.id === \"LN\")?.name); // \"LOINC\"\n * ```\n */\nexport const KNOWN_CODING_SYSTEMS: readonly KnownCodingSystem[] = Object.freeze([\n Object.freeze({ id: \"LN\", name: \"LOINC\", aliases: Object.freeze([\"LOINC\"]) }),\n Object.freeze({\n id: \"SCT\",\n name: \"SNOMED CT\",\n aliases: Object.freeze([\"SNM\", \"SNOMED\", \"SNOMEDCT\"]),\n }),\n Object.freeze({ id: \"I10\", name: \"ICD-10\", aliases: Object.freeze([\"ICD-10\", \"ICD10\"]) }),\n Object.freeze({\n id: \"I10P\",\n name: \"ICD-10-PCS\",\n aliases: Object.freeze([\"ICD-10-PCS\", \"ICD10PCS\"]),\n }),\n Object.freeze({ id: \"RXN\", name: \"RxNorm\", aliases: Object.freeze([\"RXNORM\"]) }),\n Object.freeze({ id: \"NDC\", name: \"National Drug Codes\", aliases: Object.freeze([]) }),\n Object.freeze({ id: \"CVX\", name: \"CDC Vaccine Codes\", aliases: Object.freeze([]) }),\n Object.freeze({\n id: \"MVX\",\n name: \"CDC Vaccine Manufacturer Codes\",\n aliases: Object.freeze([]),\n }),\n Object.freeze({\n id: \"UCUM\",\n name: \"Unified Code for Units of Measure\",\n aliases: Object.freeze([]),\n }),\n] as const);\n\n/**\n * Case-insensitive lookup index: every registered id and every alias\n * (uppercased) → its `KnownCodingSystem`. Built once at module load.\n * @internal\n */\nconst LOOKUP: ReadonlyMap<string, KnownCodingSystem> = (() => {\n const m = new Map<string, KnownCodingSystem>();\n for (const sys of KNOWN_CODING_SYSTEMS) {\n m.set(sys.id.toUpperCase(), sys);\n for (const alias of sys.aliases) m.set(alias.toUpperCase(), sys);\n }\n return m;\n})();\n\n/**\n * A coding-system provenance answer: the system a code CLAIMS, never\n * validated. `claimed` is always present and verbatim (never dropped); the\n * resolved `id` / `name` are present only when the claim maps to a registered\n * Table 0396 entry.\n */\nexport interface CodingSystemInfo {\n /**\n * The coding-system id exactly as it appeared in CWE.3 / CE.3: preserved\n * verbatim (original case and spelling), never altered, never dropped.\n */\n readonly claimed: string;\n /** `true` when `claimed` resolved (directly or via alias) to a registered Table 0396 entry. */\n readonly known: boolean;\n /** Registered Table 0396 acronym (alias-normalized). Present only when `known`. */\n readonly id?: string;\n /** Canonical human-readable name. Present only when `known`. */\n readonly name?: string;\n}\n\n/**\n * Resolve a raw coding-system id (a CWE.3 / CE.3 \"Name of Coding System\"\n * value) to its provenance. Returns `undefined` when there is no claim to\n * resolve: `id` is `undefined`, empty, or whitespace-only.\n *\n * Matching is case-insensitive and tolerant of surrounding whitespace, and\n * normalizes the well-known aliases in {@link KNOWN_CODING_SYSTEMS} (e.g.\n * `\"LOINC\"` → `LN`, `\"SNOMED\"` → `SCT`, `\"RxNorm\"` → `RXN`). An unrecognized\n * id is returned verbatim with `known: false`: never guessed.\n *\n * @example\n * ```ts\n * import { codingSystem } from \"@cosyte/hl7\";\n * codingSystem(\"LN\"); // { claimed: \"LN\", known: true, id: \"LN\", name: \"LOINC\" }\n * codingSystem(\"loinc\"); // { claimed: \"loinc\", known: true, id: \"LN\", name: \"LOINC\" }\n * codingSystem(\"99zL\"); // { claimed: \"99zL\", known: false }\n * codingSystem(undefined); // undefined\n * ```\n */\nexport function codingSystem(id: string | undefined): CodingSystemInfo | undefined {\n if (id === undefined) return undefined;\n const key = id.trim().toUpperCase();\n if (key === \"\") return undefined;\n\n const entry = LOOKUP.get(key);\n if (entry === undefined) {\n return Object.freeze({ claimed: id, known: false });\n }\n return Object.freeze({ claimed: id, known: true, id: entry.id, name: entry.name });\n}\n\n/**\n * Structural shape of any coded element that carries a primary + alternate\n * coding system: both {@link CWE} and {@link CE} satisfy it. Kept structural\n * (not a union) so callers can pass a `dg.code` / `obs.code` directly.\n */\nexport interface CodedSystemFields {\n readonly nameOfCodingSystem?: string;\n readonly nameOfAlternateCodingSystem?: string;\n}\n\n/**\n * Provenance of a coded element's **primary** coding system (CWE.3 / CE.3).\n * Returns `undefined` when the element claims no primary system.\n *\n * @example\n * ```ts\n * import { parseHL7, codingSystemOf } from \"@cosyte/hl7\";\n * const msg = parseHL7(raw);\n * for (const dg of msg.diagnoses()) {\n * const sys = dg.code && codingSystemOf(dg.code);\n * console.log(dg.code?.identifier, sys?.name ?? sys?.claimed ?? \"(no system)\");\n * }\n * ```\n */\nexport function codingSystemOf(coded: CodedSystemFields): CodingSystemInfo | undefined {\n return codingSystem(coded.nameOfCodingSystem);\n}\n\n/**\n * Provenance of a coded element's **alternate** coding system (CWE.6 / CE.6).\n * Returns `undefined` when the element claims no alternate system. Useful for\n * dual-coded fields (e.g. a problem carrying both SNOMED CT and ICD-10), where\n * assuming a single coding system would be unsafe.\n *\n * @example\n * ```ts\n * import { alternateCodingSystemOf } from \"@cosyte/hl7\";\n * const alt = alternateCodingSystemOf(dg.code);\n * if (alt) console.log(\"also coded in\", alt.name ?? alt.claimed);\n * ```\n */\nexport function alternateCodingSystemOf(coded: CodedSystemFields): CodingSystemInfo | undefined {\n return codingSystem(coded.nameOfAlternateCodingSystem);\n}\n","/**\n * Batch / file envelope splitting for the `@cosyte/hl7` parser (roadmap\n * Phase L). Real lab / ELR / IIS feeds ship many messages wrapped in the HL7\n * v2 batch protocol envelope (Ch. 2 §2.10.3):\n *\n * ```\n * [FHS] file header (optional)\n * { [BHS] batch header (optional, repeats)\n * { MSH … } messages (repeat)\n * [BTS] } batch trailer (optional)\n * [FTS] file trailer (optional)\n * ```\n *\n * `splitBatch()` demarcates the individual `MSH`-led messages by **MSH\n * boundaries**, parses each one with {@link parseHL7} (so every message is\n * returned either as a parsed `Hl7Message` **or** as a typed failure entry,\n * a malformed message mid-stream is isolated, never suppresses its siblings),\n * and reconciles the declared envelope counts (BTS-1 batch message count,\n * FTS-1 file batch count) against the actual counts: surfacing a\n * {@link batchCountMismatch} warning on any mismatch **without ever dropping\n * the tail**. A bare single message with no envelope passes straight through\n * as a one-message result.\n *\n * This is a **separate surface** from `parseHL7` on purpose: `parseHL7` rejects\n * non-`MSH`-first input outright (that is correct for a single-message\n * parser), so batch demarcation lives here. `splitBatch` is a **splitter**, not\n * an enforcer: it does not send batch ACKs, does not enforce any profile's\n * mandatory-envelope rule (it warns via {@link batchMissingTrailer}; the caller\n * decides to reject), and does not de-batch across transport framing (that is\n * `@cosyte/mllp`). See `docs-content/spec-notes-batch.md`.\n */\n\nimport { Buffer } from \"node:buffer\";\n\nimport { parseHL7 } from \"./index.js\";\nimport { Hl7ParseError } from \"./errors.js\";\nimport { normalize } from \"./normalize.js\";\nimport { splitSegments } from \"./segments.js\";\nimport type { Hl7Position, ParseOptions, Profile } from \"./types.js\";\nimport { batchCountMismatch, batchMissingTrailer } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\n\nimport type { Hl7Message } from \"../model/message.js\";\n\n/**\n * The four HL7 batch-protocol envelope segment names (Ch. 2 §2.10.3).\n *\n * @example\n * ```ts\n * import type { BatchEnvelopeName } from \"@cosyte/hl7\";\n * const trailer: BatchEnvelopeName = \"BTS\";\n * ```\n */\nexport type BatchEnvelopeName = \"FHS\" | \"BHS\" | \"BTS\" | \"FTS\";\n\n/**\n * A raw batch-envelope segment (`FHS`/`BHS`/`BTS`/`FTS`) surfaced by\n * {@link splitBatch}. `fields` is the segment split on its own field separator\n * with `fields[0]` holding the segment name: deliberately the raw token\n * array, not a typed model: first-class FHS/BHS field helpers are deferred\n * (roadmap Phase L defers \"typed FHS/BHS helpers beyond raw fields\"). Note the\n * HL7 MSH-family indexing quirk: for `FHS`/`BHS`, `fields[1]` is the\n * encoding-characters field (FHS-2/BHS-2); for `BTS`/`FTS`, `fields[1]` is\n * field 1 (BTS-1 batch message count / FTS-1 file batch count).\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * const { fileHeader } = splitBatch(\"FHS|^~\\\\&|SENDER\\r...\");\n * fileHeader?.name; // \"FHS\"\n * fileHeader?.fields[2]; // \"SENDER\" (FHS-3, the File Sending Application)\n * ```\n */\nexport interface BatchEnvelopeSegment {\n readonly name: BatchEnvelopeName;\n /** The verbatim segment string (line-ending normalized). */\n readonly raw: string;\n /** Raw field tokens; `fields[0]` is the segment name. */\n readonly fields: readonly string[];\n /** Position of this envelope segment in the split stream. */\n readonly position: Hl7Position;\n}\n\n/**\n * One message extracted from a batch stream. Discriminated on `ok`: a\n * successful parse carries the `Hl7Message` (whose own `.warnings` hold any\n * per-message Tier-2 deviations); a message that hit one of the four Tier-3\n * fatal conditions carries the `Hl7ParseError` instead: **isolated**, so the\n * rest of the batch still yields. `raw` is the message's verbatim source\n * (re-parseable by {@link parseHL7}); `position` is the message's `MSH` (or,\n * for pre-`MSH` stray content, its first) segment index in the stream.\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * for (const entry of splitBatch(raw).messages) {\n * if (entry.ok) handle(entry.message);\n * else quarantine(entry.raw, entry.error.code);\n * }\n * ```\n */\nexport type BatchMessageEntry =\n | {\n readonly ok: true;\n readonly message: Hl7Message;\n readonly raw: string;\n readonly position: Hl7Position;\n }\n | {\n readonly ok: false;\n readonly error: Hl7ParseError;\n readonly raw: string;\n readonly position: Hl7Position;\n };\n\n/**\n * One batch within a stream: a run of messages delimited by a `BHS` header\n * and/or a `BTS` trailer (both optional in §2.10.3, so a `BTS` closes a\n * preceding run into a batch even with no `BHS`). A run of messages with\n * **neither** a header nor a trailer is *not* a batch: those messages live in\n * {@link BatchSplitResult.messages} only, so they never inflate a batch count.\n * `declaredMessageCount` is BTS-1 when the trailer declared a usable\n * non-negative integer (it is **optional [0..1]** in the spec, so it may be\n * absent); `actualMessageCount` is always the real count.\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * const [batch] = splitBatch(raw).batches;\n * batch?.header?.name; // \"BHS\" (or undefined for a headerless BTS-closed run)\n * batch?.actualMessageCount; // messages actually in the batch\n * ```\n */\nexport interface Batch {\n /** The `BHS` header, when this batch was opened by one. */\n readonly header?: BatchEnvelopeSegment;\n /** The `BTS` trailer, when this batch was closed by one. */\n readonly trailer?: BatchEnvelopeSegment;\n /** The messages in this batch, in stream order. */\n readonly messages: readonly BatchMessageEntry[];\n /** BTS-1 batch message count, when declared as a non-negative integer. */\n readonly declaredMessageCount?: number;\n /** The actual number of messages split out of this batch. */\n readonly actualMessageCount: number;\n}\n\n/**\n * The result of {@link splitBatch}: the flattened `messages` (every message\n * across every batch, in stream order: the primary surface), the nested\n * `batches`, the raw file envelope segments, and the batch-level `warnings`\n * (count-mismatch / missing-trailer). `hadEnvelope` is `false` for a bare\n * passthrough (no FHS/BHS/BTS/FTS seen).\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n * const result = splitBatch(rawBatchFile);\n * result.messages.length; // every message, batched or not\n * result.batches.length; // === result.actualBatchCount\n * result.warnings; // BATCH_COUNT_MISMATCH / BATCH_MISSING_TRAILER (counts only)\n * ```\n */\nexport interface BatchSplitResult {\n /**\n * Every message split out of the stream, in order: the primary surface. This\n * includes messages that belong to no explicit batch (a bare stream, or\n * content outside any `BHS`/`BTS`), so it is a superset of the messages\n * reachable via `batches`.\n */\n readonly messages: readonly BatchMessageEntry[];\n /** The explicit (`BHS`-delimited) batches, in stream order. */\n readonly batches: readonly Batch[];\n /** The **first** `FHS` file header, when present. */\n readonly fileHeader?: BatchEnvelopeSegment;\n /** The **last** `FTS` file trailer, when present. */\n readonly fileTrailer?: BatchEnvelopeSegment;\n /** The last `FTS-1` file batch count, when declared as a non-negative integer. */\n readonly declaredBatchCount?: number;\n /** The number of explicit batches split out of the stream. */\n readonly actualBatchCount: number;\n /** `false` when no envelope segment was seen (bare passthrough). */\n readonly hadEnvelope: boolean;\n /** Batch-level warnings (count mismatch, missing trailer); counts/positions only, never PHI. */\n readonly warnings: readonly Hl7ParseWarning[];\n}\n\n/** Mutable batch accumulator used while walking; frozen into a {@link Batch} at the end. */\ninterface MutableBatch {\n header?: BatchEnvelopeSegment;\n trailer?: BatchEnvelopeSegment;\n readonly messages: BatchMessageEntry[];\n /** BTS-1 once reconciled at close (undefined when absent/non-numeric). */\n declaredMessageCount?: number;\n}\n\n/**\n * The 3-character HL7 segment name at the start of a segment string. HL7\n * segment IDs are always exactly three characters, so a fixed slice is correct.\n *\n * Deliberately **case-sensitive** (no upper-casing): the batch-boundary segment\n * names (`FHS`/`BHS`/`BTS`/`FTS`/`MSH`) are only recognized when spelled in\n * their canonical uppercase form. This is a fail-safe against a lenient lowercase\n * body segment (e.g. `fts`) being mistaken for an envelope boundary: the\n * boundary segments cannot be disambiguated from a same-named body segment by\n * anything but their reserved name, so we keep the match strict. A lowercase\n * `msh`-led message is not a valid message anyway (`parseHL7`'s delimiter reader\n * requires an uppercase `MSH`), so declining to treat it as a boundary loses\n * nothing. See the reserved-name limitation in `docs-content/spec-notes-batch.md`.\n *\n * @internal\n */\nfunction segmentName(raw: string): string {\n return raw.slice(0, 3);\n}\n\n/** @internal narrow a 3-char name to a batch-envelope segment name. */\nfunction isEnvelopeName(name: string): name is BatchEnvelopeName {\n return name === \"FHS\" || name === \"BHS\" || name === \"BTS\" || name === \"FTS\";\n}\n\n/**\n * Split an envelope segment into its raw field tokens on its own field\n * separator (the character at index 3, immediately after the 3-char name: the\n * same self-describing convention MSH uses). Returns `[name]` when the segment\n * has no field separator (a bare 3-char segment).\n *\n * @internal\n */\nfunction envelopeFields(raw: string): readonly string[] {\n const separator = raw.charAt(3);\n if (separator === \"\") return Object.freeze([raw.slice(0, 3)]);\n return Object.freeze(raw.split(separator));\n}\n\n/** @internal build a frozen {@link BatchEnvelopeSegment}. */\nfunction makeEnvelope(\n name: BatchEnvelopeName,\n raw: string,\n segmentIndex: number,\n): BatchEnvelopeSegment {\n return Object.freeze({\n name,\n raw,\n fields: envelopeFields(raw),\n position: Object.freeze({ segmentIndex }),\n });\n}\n\n/**\n * Parse a declared envelope count. Returns the value only for a trimmed,\n * strictly-numeric, safe non-negative integer; `undefined` for an absent,\n * blank, or non-numeric token: so an absent BTS-1 ([0..1] in the spec) or a\n * garbage count tolerantly disables reconciliation rather than fabricating a\n * mismatch.\n *\n * @internal\n */\nfunction parseDeclaredCount(token: string | undefined): number | undefined {\n if (token === undefined) return undefined;\n const trimmed = token.trim();\n if (!/^\\d+$/.test(trimmed)) return undefined;\n const value = Number.parseInt(trimmed, 10);\n return Number.isSafeInteger(value) ? value : undefined;\n}\n\n/**\n * Parse one demarcated message and classify it. A successful {@link parseHL7}\n * yields an `ok` entry; one of the four Tier-3 fatals (`EMPTY_INPUT`,\n * `NO_MSH_SEGMENT`, `MSH_TOO_SHORT`, `INVALID_ENCODING_CHARACTERS`): or, under\n * `strict`, a promoted Tier-2 warning: is caught and returned as a typed\n * failure entry so it never suppresses the sibling messages. Any non-parser\n * throw is genuinely unexpected and re-raised.\n *\n * A `Buffer` stream is decoded/re-encoded via `latin1` (a lossless 1:1\n * byte↔codepoint mapping) so each message's own MSH-18 charset resolution runs\n * on its original bytes rather than a stream-wide guess.\n *\n * @internal\n */\nfunction parseEntry(\n rawMessage: string,\n position: Hl7Position,\n wasBuffer: boolean,\n optionsOrProfile: ParseOptions | Profile | undefined,\n): BatchMessageEntry {\n const input: string | Buffer = wasBuffer ? Buffer.from(rawMessage, \"latin1\") : rawMessage;\n try {\n // parseHL7 re-discriminates Profile vs ParseOptions from the argument's\n // runtime shape (its overloads share one implementation), so forwarding the\n // caller's second argument unchanged preserves identical per-message\n // semantics. The cast only selects an overload signature.\n const message =\n optionsOrProfile === undefined\n ? parseHL7(input)\n : parseHL7(input, optionsOrProfile as ParseOptions);\n return { ok: true, message, raw: rawMessage, position };\n } catch (error) {\n if (error instanceof Hl7ParseError) {\n return { ok: false, error, raw: rawMessage, position };\n }\n throw error;\n }\n}\n\n/**\n * Split a raw HL7 v2 **batch / file** stream into its individual messages plus\n * the envelope metadata. Demarcates by `MSH` boundaries inside the optional\n * `[FHS] { [BHS] { MSH… } [BTS] } [FTS]` frame (HL7 v2 Ch. 2 §2.10.3):\n *\n * - handles a file with **multiple batches** and a batch with multiple messages;\n * - a **bare single message** (no envelope) passes straight through as one entry;\n * - a **malformed message mid-batch is isolated** (returned as a typed failure\n * entry): its siblings are still returned, the tail is never dropped;\n * - reconciles BTS-1 (batch message count) and FTS-1 (file batch count) and\n * emits {@link batchCountMismatch} on a mismatch: counts only, never PHI;\n * - emits {@link batchMissingTrailer} when a `BHS`/`FHS` header opens a scope no\n * `BTS`/`FTS` closes: a warning, never a throw (the caller decides to reject).\n *\n * The second argument, when given, is forwarded verbatim to {@link parseHL7}\n * for **each** message (profile, `strict`, `charset`, `dateFormats`, …). Under\n * `strict`, a message that would warn surfaces as a failure entry (still\n * isolated). `splitBatch` itself never throws: an empty stream yields an empty\n * result.\n *\n * @example\n * ```ts\n * import { splitBatch } from \"@cosyte/hl7\";\n *\n * const { messages, warnings } = splitBatch(\n * \"FHS|^~\\\\&|SENDER\\r\" +\n * \"BHS|^~\\\\&|SENDER\\r\" +\n * \"MSH|^~\\\\&|A|F|B|G|20260101||ADT^A01|1|P|2.5\\rPID|||1\\r\" +\n * \"MSH|^~\\\\&|A|F|B|G|20260101||ADT^A01|2|P|2.5\\rPID|||2\\r\" +\n * \"BTS|2\\rFTS|1\\r\",\n * );\n * console.log(messages.length); // 2\n * for (const entry of messages) {\n * if (entry.ok) console.log(entry.message.version); // \"2.5\"\n * }\n * console.log(warnings.length); // 0: declared counts match\n * ```\n */\nexport function splitBatch(raw: string | Buffer): BatchSplitResult;\nexport function splitBatch(raw: string | Buffer, profile: Profile): BatchSplitResult;\nexport function splitBatch(raw: string | Buffer, options: ParseOptions): BatchSplitResult;\n/** @internal implementation signature; overloads above carry the public JSDoc. */\nexport function splitBatch(\n raw: string | Buffer,\n optionsOrProfile?: ParseOptions | Profile,\n): BatchSplitResult {\n const wasBuffer = typeof raw !== \"string\";\n // latin1 is a lossless byte↔codepoint decode: envelope segments + the \\r\n // segment terminator are ASCII, so demarcation is exact, and each message\n // slice re-encodes to its original bytes for per-message MSH-18 charset\n // resolution. NB: stream-level line-ending `normalize()` runs before that\n // per-message decode: correct for the single-byte / ASCII-superset charsets\n // HL7 batch framing uses (its \\r terminator must be a single 0x0D byte), but\n // not a byte-exact substitute for a multi-byte charset (e.g. UTF-16) whose\n // payload embeds 0x0A/0x0D bytes. Such batch files effectively do not exist.\n let text = wasBuffer ? raw.toString(\"latin1\") : raw;\n\n // Strip a leading BOM (UTF-8 as a string codepoint, or its raw latin1 bytes)\n // so the first FHS/MSH is still detected. Per-message BOMs are stripped again\n // by parseHL7.\n if (text.charCodeAt(0) === 0xfeff) {\n text = text.slice(1);\n } else if (text.startsWith(\"\")) {\n text = text.slice(3);\n }\n\n const segments = splitSegments(normalize(text));\n\n const flattened: BatchMessageEntry[] = [];\n const batches: MutableBatch[] = [];\n const warnings: Hl7ParseWarning[] = [];\n let fileHeader: BatchEnvelopeSegment | undefined;\n let fileTrailer: BatchEnvelopeSegment | undefined;\n let hadEnvelope = false;\n\n // A batch is a run of messages delimited by a `BHS` header AND/OR a `BTS`\n // trailer: both are optional in the §2.10.3 grammar, so a `BTS` closes the\n // preceding run into a batch even with no `BHS`. `pendingMessages` accumulates\n // the messages since the last boundary; `currentHeader` is the `BHS` that\n // opened the current run, if any. A run with NEITHER a header nor a trailer is\n // stray: kept in `flattened`/`messages` only, so it never inflates the FTS-1\n // batch count.\n let currentHeader: BatchEnvelopeSegment | undefined;\n let pendingMessages: BatchMessageEntry[] = [];\n let messageLines: string[] = [];\n let messageIndex = -1;\n\n // Per-file scoping so FTS-1 reconciles against the batches of THIS file only\n // (a concatenated second `FHS` resets the count instead of double-counting).\n let openFileHeader: BatchEnvelopeSegment | undefined; // an FHS awaiting its FTS\n let fileBatchCount = 0; // batches seen since the last FHS\n let lastDeclaredBatchCount: number | undefined; // most recent FTS-1\n\n const flushMessage = (): void => {\n // A blank segment right before a boundary is inter-message whitespace, not\n // part of the message (parseHL7 likewise strips a single trailing CR), so\n // drop trailing empties. Interior empties were already kept below.\n while (messageLines.length > 0 && messageLines[messageLines.length - 1] === \"\") {\n messageLines.pop();\n }\n if (messageLines.length === 0) {\n messageIndex = -1;\n return;\n }\n const entry = parseEntry(\n messageLines.join(\"\\r\"),\n Object.freeze({ segmentIndex: messageIndex }),\n wasBuffer,\n optionsOrProfile,\n );\n flattened.push(entry);\n pendingMessages.push(entry);\n messageLines = [];\n messageIndex = -1;\n };\n\n // Finalize the pending message run. A `BTS` trailer always closes the run into\n // a batch (headerless or headed) and reconciles BTS-1: except a lone `BTS`\n // closing nothing (no messages, no header), which is ignorable noise. Without\n // a trailer, only a `BHS`-opened run is a batch (and warns for its missing\n // BTS); a headerless, trailer-less run is stray.\n const finalizeBatch = (trailer?: BatchEnvelopeSegment): void => {\n flushMessage();\n if (trailer !== undefined) {\n if (pendingMessages.length > 0 || currentHeader !== undefined) {\n const batch: MutableBatch = { messages: pendingMessages, trailer };\n if (currentHeader !== undefined) batch.header = currentHeader;\n const declared = parseDeclaredCount(trailer.fields[1]);\n if (declared !== undefined) {\n batch.declaredMessageCount = declared;\n if (declared !== pendingMessages.length) {\n warnings.push(\n batchCountMismatch(trailer.position, \"message\", declared, pendingMessages.length),\n );\n }\n }\n batches.push(batch);\n fileBatchCount += 1;\n }\n } else if (currentHeader !== undefined) {\n warnings.push(batchMissingTrailer(currentHeader.position, \"BHS\", \"BTS\"));\n batches.push({ messages: pendingMessages, header: currentHeader });\n fileBatchCount += 1;\n }\n // else: headerless, trailer-less run -> stray (already in `flattened`).\n pendingMessages = [];\n currentHeader = undefined;\n };\n\n // Close the current file scope. With an FTS trailer: reconcile FTS-1 against\n // the batches of this file. Without one (a new FHS, or end of stream): if a\n // file header was open, warn that it never got its FTS.\n const closeFile = (trailer?: BatchEnvelopeSegment): void => {\n finalizeBatch();\n if (trailer !== undefined) {\n fileTrailer = trailer;\n const declared = parseDeclaredCount(trailer.fields[1]);\n if (declared !== undefined) {\n lastDeclaredBatchCount = declared;\n if (declared !== fileBatchCount) {\n warnings.push(batchCountMismatch(trailer.position, \"batch\", declared, fileBatchCount));\n }\n }\n } else if (openFileHeader !== undefined) {\n warnings.push(batchMissingTrailer(openFileHeader.position, \"FHS\", \"FTS\"));\n }\n openFileHeader = undefined;\n fileBatchCount = 0;\n };\n\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index];\n if (segment === undefined) continue;\n // Skip a blank / whitespace-only line ONLY between messages: it is\n // inter-message whitespace carrying no segment content (splitBatch is\n // deliberately more tolerant of stream-level whitespace than parseHL7). A\n // blank segment INSIDE an open message is meaningful (HL7 keeps middle empty\n // segments for positional stability) and rides along so the message's `raw`\n // re-parses identically.\n if (messageLines.length === 0 && segment.trim() === \"\") continue;\n const name = segmentName(segment);\n\n if (isEnvelopeName(name)) {\n hadEnvelope = true;\n if (name === \"FHS\") {\n closeFile(); // close any prior file (warns if it had no FTS)\n const env = makeEnvelope(\"FHS\", segment, index);\n if (fileHeader === undefined) fileHeader = env; // result field keeps the first\n openFileHeader = env;\n } else if (name === \"FTS\") {\n closeFile(makeEnvelope(\"FTS\", segment, index));\n } else if (name === \"BHS\") {\n finalizeBatch(); // close the prior run before opening a new batch\n currentHeader = makeEnvelope(\"BHS\", segment, index);\n } else {\n finalizeBatch(makeEnvelope(\"BTS\", segment, index));\n }\n continue;\n }\n\n if (name === \"MSH\") {\n flushMessage();\n messageLines = [segment];\n messageIndex = index;\n continue;\n }\n\n // Message body: or stray content before the first MSH / a body segment\n // severed by a reserved-name boundary, which is kept (never dropped) and\n // surfaces as a NO_MSH_SEGMENT failure entry on flush.\n if (messageLines.length === 0) messageIndex = index;\n messageLines.push(segment);\n }\n\n closeFile(); // flush the final message + batch, and any still-open file header\n\n const publicBatches: Batch[] = batches.map((batch) => {\n const publicBatch: Batch = {\n messages: Object.freeze(batch.messages),\n actualMessageCount: batch.messages.length,\n ...(batch.header !== undefined ? { header: batch.header } : {}),\n ...(batch.trailer !== undefined ? { trailer: batch.trailer } : {}),\n ...(batch.declaredMessageCount !== undefined\n ? { declaredMessageCount: batch.declaredMessageCount }\n : {}),\n };\n return Object.freeze(publicBatch);\n });\n\n const result: BatchSplitResult = {\n messages: Object.freeze(flattened),\n batches: Object.freeze(publicBatches),\n actualBatchCount: publicBatches.length,\n hadEnvelope,\n warnings: Object.freeze(warnings),\n ...(fileHeader !== undefined ? { fileHeader } : {}),\n ...(fileTrailer !== undefined ? { fileTrailer } : {}),\n ...(lastDeclaredBatchCount !== undefined ? { declaredBatchCount: lastDeclaredBatchCount } : {}),\n };\n return Object.freeze(result);\n}\n","/**\n * Public types for the conformance-profile engine (roadmap Phase U). A\n * **consumer authors** a declarative {@link ConformanceProfile}: a bounded\n * subset of the HL7 v2 Message-Profile / NIST-IGAMT model (usage codes,\n * cardinality, length, value-set binding against a consumer-supplied code\n * list): and {@link validateAgainstProfile} runs it against a parsed message,\n * returning typed {@link ConformanceFinding}s.\n *\n * This is the **sanctioned functionality-plane replacement for the retired\n * vendor-corpus arc**: instead of hl7 shipping vendor/IHE/regulatory profiles\n * or code sets, the consumer brings their own interface spec and hl7 validates\n * against it. hl7 ships **no** profile, **no** code set, and makes **no**\n * network call: the profile and every value set are supplied by the caller.\n *\n * Two invariants govern the whole surface:\n *\n * 1. **\"No findings\" is NOT a conformance attestation.** An empty\n * {@link ConformanceResult.findings} means \"nothing THIS profile checked was\n * violated\": never \"this message is conformant.\" The profile only covers\n * what the author declared; everything undeclared is unchecked.\n * 2. **No PHI in findings.** A finding names the structural **locus** (segment\n * name, field / component index, repetition, occurrence) and the rule that\n * fired: **never** the offending field value. A \"value not in set\" finding\n * says *where* and *which value set*, never *what the value was*.\n *\n * @see validateAgainstProfile\n */\n\n/**\n * The six HL7 v2 conformance **usage codes** (HL7 Conformance Methodology,\n * Message Profiles; IHE ITI TF Vol.2 Appendix C). They constrain whether an\n * element must, may, or must not appear:\n *\n * - **`R`**: Required. The element SHALL be present (with a value). Absent →\n * {@link FINDING_CODES.PROFILE_REQUIRED_ABSENT}.\n * - **`RE`**: Required but may be Empty. The element is supported and SHALL be\n * sent when the sender has the data; its **absence is never a violation**\n * (this engine cannot know whether the sender had the data).\n * - **`C`**: Conditional. Presence depends on a predicate. This bounded engine\n * ships **no predicate language** (a documented defer: roadmap §5), so a\n * `C` element's **presence is not evaluated** (treated as optional); its\n * length / value-set / cardinality rules still apply when it IS present.\n * - **`CE`**: Conditional but may be Empty. Same non-evaluation as `C`.\n * - **`O`**: Optional. No presence constraint.\n * - **`X`**: Not supported / not permitted. The element SHALL NOT be present.\n * Present → {@link FINDING_CODES.PROFILE_NOT_PERMITTED}.\n *\n * @example\n * ```ts\n * import type { UsageCode } from \"@cosyte/hl7\";\n * const usage: UsageCode = \"R\";\n * ```\n */\nexport type UsageCode = \"R\" | \"RE\" | \"C\" | \"CE\" | \"O\" | \"X\";\n\n/**\n * The frozen set of valid {@link UsageCode}s, for runtime validation and\n * introspection. `USAGE_CODES.R === \"R\"`.\n *\n * @example\n * ```ts\n * import { USAGE_CODES } from \"@cosyte/hl7\";\n * USAGE_CODES.includes(\"R\" as const); // true\n * ```\n */\nexport const USAGE_CODES: readonly UsageCode[] = Object.freeze([\"R\", \"RE\", \"C\", \"CE\", \"O\", \"X\"]);\n\n/**\n * A repetition-count constraint. `min` / `max` are inclusive bounds on the\n * number of repetitions (for a field rule) or occurrences (for a segment\n * rule). `max` may be the literal `\"*\"` for \"unbounded\". Omitted bounds are\n * unconstrained on that side.\n *\n * **Cardinality `min` is checked only when the element is present.** An absent\n * **Required** element is reported as {@link FINDING_CODES.PROFILE_REQUIRED_ABSENT}\n * (a usage finding), not a cardinality finding: so a missing `R` field with\n * `cardinality.min = 1` yields exactly one finding, never two.\n *\n * @example\n * ```ts\n * import type { Cardinality } from \"@cosyte/hl7\";\n * const once: Cardinality = { min: 1, max: 1 };\n * const many: Cardinality = { min: 1, max: \"*\" };\n * ```\n */\nexport interface Cardinality {\n readonly min?: number;\n readonly max?: number | \"*\";\n}\n\n/**\n * A rule for one **field position** within a segment (roadmap Phase U). Every\n * constraint is optional; a rule with only a `field` index is a no-op.\n *\n * @remarks\n * `field` is the 1-indexed HL7 position (MSH offset handled internally, exactly\n * like `Segment.field(n)`: `{ field: 9 }` on `MSH` targets MSH-9). Length and\n * value-set checks read the value at `component` (default **1**), so a coded\n * field's code (`CWE.1` / `CE.1`) is checked by default; set `component` to\n * check a different component. Both are applied **per present repetition**.\n */\nexport interface FieldRule {\n /** 1-indexed HL7 field position (e.g. `3` for PID-3, `9` for MSH-9). */\n readonly field: number;\n /**\n * Optional human label for the field (e.g. `\"Patient Identifier List\"`).\n * Structural documentation for the profile author only: findings identify a\n * field by its PHI-free structural locus (segment + index), never by this\n * label, so the label is never echoed into a finding message.\n */\n readonly name?: string;\n /** Usage constraint (see {@link UsageCode}). Omitted ⇒ Optional. */\n readonly usage?: UsageCode;\n /** Repetition-count constraint for this field. */\n readonly cardinality?: Cardinality;\n /** Maximum character length of the checked component value (inclusive). */\n readonly length?: number;\n /**\n * Consumer-supplied permitted-value list. The checked component value must be\n * a member (case-sensitive exact match). **hl7 ships no code set**: this is\n * BYO terminology; membership is a literal string check, never a LOINC /\n * SNOMED / ICD / RxNorm lookup and never a network call.\n */\n readonly valueSet?: readonly string[];\n /**\n * 1-indexed component whose value the `length` / `valueSet` checks read.\n * Defaults to `1` (the first component: a coded element's code).\n */\n readonly component?: number;\n /**\n * Severity for findings this rule produces. Defaults to `\"error\"`. A profile\n * author can downgrade a data-quality rule (e.g. a length or value-set check)\n * to `\"warning\"` or `\"info\"` without changing the check itself.\n */\n readonly severity?: FindingSeverity;\n}\n\n/**\n * A rule for one **segment type** (roadmap Phase U). `usage` constrains whether\n * the segment must / must not appear; `cardinality` constrains how many times;\n * `fields` are the per-field rules, applied to **every** occurrence of the\n * segment.\n */\nexport interface SegmentRule {\n /** Segment name: 3 chars, `[A-Z][A-Z0-9]{2}` (standard or `Z…` segment). */\n readonly segment: string;\n /**\n * Usage for the segment as a whole. `R` ⇒ at least one occurrence required;\n * `X` ⇒ none permitted; `RE` / `O` ⇒ no presence constraint; `C` / `CE` ⇒\n * presence not evaluated (no predicate language). Omitted ⇒ Optional.\n */\n readonly usage?: UsageCode;\n /** Occurrence-count constraint for this segment across the message. */\n readonly cardinality?: Cardinality;\n /** Per-field rules, applied to each occurrence of this segment. */\n readonly fields?: readonly FieldRule[];\n /** Severity for the segment-level presence / cardinality findings. Default `\"error\"`. */\n readonly severity?: FindingSeverity;\n}\n\n/**\n * A **user-authored, declarative** conformance profile (roadmap Phase U). The\n * consumer supplies this; hl7 ships none. It is a bounded subset of the HL7 v2\n * Message-Profile model: usage / cardinality / length / consumer-supplied\n * value set: with **no** conditional-predicate language, **no** bundled code\n * set, and **no** network binding (all deliberate scope boundaries).\n *\n * @example\n * ```ts\n * import type { ConformanceProfile } from \"@cosyte/hl7\";\n *\n * // A minimal ADT profile the CONSUMER authors: example, NOT an attestation.\n * const profile: ConformanceProfile = {\n * name: \"example-adt-min\",\n * segments: [\n * { segment: \"MSH\", usage: \"R\", fields: [{ field: 10, name: \"Control ID\", usage: \"R\" }] },\n * { segment: \"PID\", usage: \"R\", cardinality: { min: 1, max: 1 }, fields: [\n * { field: 3, name: \"Patient Identifiers\", usage: \"R\", cardinality: { min: 1, max: 1 } },\n * { field: 8, name: \"Administrative Sex\", usage: \"RE\", valueSet: [\"M\", \"F\", \"U\"] },\n * ] },\n * { segment: \"ZZZ\", usage: \"X\" },\n * ],\n * };\n * ```\n */\nexport interface ConformanceProfile {\n /** A name for provenance: echoed into {@link ConformanceResult.profileName}. */\n readonly name: string;\n /** The segment rules, evaluated in array order (stable finding order). */\n readonly segments: readonly SegmentRule[];\n}\n\n/**\n * Severity of a {@link ConformanceFinding}. `error` is a constraint violation;\n * `warning` / `info` are author-downgraded advisories (via a rule's\n * `severity`). {@link FINDING_CODES.PROFILE_MALFORMED} is always `error`.\n */\nexport type FindingSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * The frozen registry of finding codes. Stable, additive string codes: a\n * consumer compares `finding.code === FINDING_CODES.PROFILE_REQUIRED_ABSENT`.\n * Segment-level vs field-level is disambiguated by whether the finding's\n * {@link FindingLocus.field} is present, not by separate codes.\n *\n * @example\n * ```ts\n * import { validateAgainstProfile, FINDING_CODES } from \"@cosyte/hl7\";\n * const { findings } = validateAgainstProfile(msg, profile);\n * const missing = findings.filter((f) => f.code === FINDING_CODES.PROFILE_REQUIRED_ABSENT);\n * ```\n */\nexport const FINDING_CODES = {\n /** A Required (`R`) segment or field is absent (or present-but-empty). */\n PROFILE_REQUIRED_ABSENT: \"PROFILE_REQUIRED_ABSENT\",\n /** A Not-permitted (`X`) segment or field is present. */\n PROFILE_NOT_PERMITTED: \"PROFILE_NOT_PERMITTED\",\n /** A segment-occurrence or field-repetition count is outside its cardinality. */\n PROFILE_CARDINALITY: \"PROFILE_CARDINALITY\",\n /** A checked component value exceeds the declared maximum length. */\n PROFILE_LENGTH: \"PROFILE_LENGTH\",\n /** A checked component value is not a member of the consumer-supplied value set. */\n PROFILE_VALUE_NOT_IN_SET: \"PROFILE_VALUE_NOT_IN_SET\",\n /** The profile ITSELF is structurally malformed (a diagnostic, not a message finding). */\n PROFILE_MALFORMED: \"PROFILE_MALFORMED\",\n} as const;\n\n/**\n * Discriminant union of every {@link ConformanceFinding} code. Enables\n * exhaustive `switch` narrowing (the `switch-exhaustiveness-check` lint rule).\n */\nexport type FindingCode = (typeof FINDING_CODES)[keyof typeof FINDING_CODES];\n\n/**\n * The **structural** locus a finding refers to: segment name plus, where\n * applicable, the field position, component, repetition, and segment\n * occurrence. Every member is a name or an index: a locus is **inherently\n * PHI-free** and never carries a field value.\n *\n * A finding with no {@link field} is **segment-level** (presence / cardinality\n * of the segment itself); a finding with a `field` is **field-level**. For a\n * {@link FINDING_CODES.PROFILE_MALFORMED} diagnostic (a defect in the profile,\n * not the message) `segment` may be the sentinel `\"(profile)\"`.\n */\nexport interface FindingLocus {\n /** Segment name (e.g. `\"PID\"`), or `\"(profile)\"` for a profile-shape defect. */\n readonly segment: string;\n /** 1-indexed field position, when the finding is field-level. */\n readonly field?: number;\n /** 1-indexed component, when a component-scoped check (length / value-set) fired. */\n readonly component?: number;\n /** 0-indexed field repetition, when the finding is repetition-scoped. */\n readonly repetition?: number;\n /** 0-indexed segment occurrence, when the segment type repeats. */\n readonly occurrence?: number;\n}\n\n/**\n * One typed conformance finding. Carries the {@link FindingCode}, a\n * {@link FindingSeverity}, the structural {@link FindingLocus}, and a\n * human-readable `message` describing the rule that fired.\n *\n * **The `message` is PHI-safe by construction**: it names the locus, the rule,\n * and (for a value-set miss) the SIZE of the value set, but **never** the\n * offending field value.\n *\n * @example\n * ```ts\n * import type { ConformanceFinding } from \"@cosyte/hl7\";\n * const f: ConformanceFinding = {\n * code: \"PROFILE_VALUE_NOT_IN_SET\",\n * severity: \"error\",\n * locus: { segment: \"PID\", field: 8, component: 1 },\n * message: 'PID-8 component 1 value is not in the profile value set (3 permitted codes).',\n * };\n * ```\n */\nexport interface ConformanceFinding {\n readonly code: FindingCode;\n readonly severity: FindingSeverity;\n readonly locus: FindingLocus;\n readonly message: string;\n}\n\n/**\n * The result of {@link validateAgainstProfile}: the profile's `name` and the\n * ordered list of `findings`.\n *\n * **`findings.length === 0` is NOT a conformance attestation.** It means every\n * rule the profile declared was satisfied: nothing about the parts of the\n * message the profile did not cover, and nothing about clinical correctness.\n * Read it as \"no declared rule was violated,\" never as \"conformant.\"\n */\nexport interface ConformanceResult {\n readonly profileName: string;\n readonly findings: readonly ConformanceFinding[];\n}\n","/**\n * Finding factories for the conformance-profile engine (roadmap Phase U).\n * Every {@link ConformanceFinding} the engine emits is built here so that\n * message wording, severity, and (critically) **PHI safety** stay consistent\n * across the engine.\n *\n * The one rule every factory obeys: **a finding message names the structural\n * locus and the rule, never the offending value.** A value-set miss reports the\n * SIZE of the value set and the locus; a length overflow reports the declared\n * limit and the locus; neither ever embeds the field's content. This mirrors\n * the parser's warning discipline (`src/parser/warnings.ts`): the locus is the\n * PHI-free coordinate; the value stays in the (unmodified) message.\n *\n * @internal\n */\n\nimport {\n FINDING_CODES,\n type ConformanceFinding,\n type FindingLocus,\n type FindingSeverity,\n} from \"./types.js\";\n\n/**\n * Render a {@link FindingLocus} as a compact human string for a finding\n * message: `PID`, `PID-3`, `PID-8 component 1`, `PID[1]-3 rep 2`. Structural\n * indices only; never a value. Used only to build the PHI-safe `message`.\n *\n * @internal\n */\nexport function describeLocus(locus: FindingLocus): string {\n let s = locus.segment;\n if (locus.occurrence !== undefined && locus.occurrence > 0) {\n s += `[occurrence ${String(locus.occurrence)}]`;\n }\n if (locus.field !== undefined) {\n s += `-${String(locus.field)}`;\n }\n if (locus.repetition !== undefined) {\n s += ` rep ${String(locus.repetition)}`;\n }\n if (locus.component !== undefined) {\n s += ` component ${String(locus.component)}`;\n }\n return s;\n}\n\n/**\n * A Required (`R`) element is absent. Segment-level when `locus.field` is\n * absent; field-level otherwise.\n *\n * @internal\n */\nexport function requiredAbsent(locus: FindingLocus, severity: FindingSeverity): ConformanceFinding {\n const kind = locus.field === undefined ? \"segment\" : \"field\";\n return {\n code: FINDING_CODES.PROFILE_REQUIRED_ABSENT,\n severity,\n locus,\n message: `Required ${kind} ${describeLocus(locus)} is absent or empty (usage R).`,\n };\n}\n\n/**\n * A Not-permitted (`X`) element is present. Segment- or field-level per\n * `locus.field`.\n *\n * @internal\n */\nexport function notPermitted(locus: FindingLocus, severity: FindingSeverity): ConformanceFinding {\n const kind = locus.field === undefined ? \"segment\" : \"field\";\n return {\n code: FINDING_CODES.PROFILE_NOT_PERMITTED,\n severity,\n locus,\n message: `${kind === \"segment\" ? \"Segment\" : \"Field\"} ${describeLocus(\n locus,\n )} is present but the profile marks it not-permitted (usage X).`,\n };\n}\n\n/**\n * A repetition / occurrence count is outside the declared cardinality. `actual`\n * and the `min` / `max` bounds are structural integers: never a value.\n *\n * @internal\n */\nexport function cardinality(\n locus: FindingLocus,\n actual: number,\n bound: { readonly min?: number; readonly max?: number | \"*\" },\n unit: \"occurrence\" | \"repetition\",\n severity: FindingSeverity,\n): ConformanceFinding {\n const parts: string[] = [];\n if (bound.min !== undefined) parts.push(`min ${String(bound.min)}`);\n if (bound.max !== undefined) parts.push(`max ${String(bound.max)}`);\n return {\n code: FINDING_CODES.PROFILE_CARDINALITY,\n severity,\n locus,\n message: `${describeLocus(locus)} has ${String(actual)} ${unit}(s), outside the declared cardinality (${parts.join(\n \", \",\n )}).`,\n };\n}\n\n/**\n * A checked component value exceeds the declared maximum length. The message\n * reports the declared `max` and the observed length **count**: never the\n * value, and never any substring of it (a length count is a coarse shape fact,\n * consistent with the parser's `FIELD_WHITESPACE_TRIMMED` count-only policy).\n *\n * @internal\n */\nexport function length(\n locus: FindingLocus,\n actualLength: number,\n maxLength: number,\n severity: FindingSeverity,\n): ConformanceFinding {\n return {\n code: FINDING_CODES.PROFILE_LENGTH,\n severity,\n locus,\n message: `${describeLocus(locus)} value length ${String(\n actualLength,\n )} exceeds the declared maximum of ${String(maxLength)}.`,\n };\n}\n\n/**\n * A checked component value is not a member of the consumer-supplied value set.\n * The message reports the locus and the **size** of the value set: never the\n * offending value and never the permitted codes' content beyond their count.\n *\n * @internal\n */\nexport function valueNotInSet(\n locus: FindingLocus,\n valueSetSize: number,\n severity: FindingSeverity,\n): ConformanceFinding {\n return {\n code: FINDING_CODES.PROFILE_VALUE_NOT_IN_SET,\n severity,\n locus,\n message: `${describeLocus(\n locus,\n )} value is not in the profile value set (${String(valueSetSize)} permitted code(s)).`,\n };\n}\n\n/**\n * The profile ITSELF is structurally malformed. A diagnostic about the\n * **profile**, not the message: always `error` severity. `detail` describes\n * the shape defect (a profile is author-supplied configuration, not clinical\n * data, so it carries no PHI).\n *\n * @internal\n */\nexport function malformed(locus: FindingLocus, detail: string): ConformanceFinding {\n return {\n code: FINDING_CODES.PROFILE_MALFORMED,\n severity: \"error\",\n locus,\n message: `Malformed conformance profile: ${detail}`,\n };\n}\n","/**\n * Profile-shape validation for the conformance engine (roadmap Phase U). A\n * conformance profile is **consumer-authored configuration**, so it can be\n * malformed. Two entry points share one total defect collector:\n *\n * - {@link collectProfileDefects}: **total over `unknown`, never throws.** It\n * returns a list of structural {@link ProfileDefect}s (empty ⇒ well-formed).\n * {@link validateAgainstProfile} calls it first and, on any defect, returns\n * `PROFILE_MALFORMED` findings instead of validating a profile it cannot\n * trust (never a silent pass).\n * - {@link defineConformanceProfile}: the **fail-fast authoring** helper. It\n * runs the same collector and **throws {@link ProfileDefinitionError}** on the\n * first-through-all defects, returning the profile typed on success. Use it at\n * profile-authoring time; the engine itself never throws (task invariant).\n *\n * A defect `detail` describes the profile's SHAPE (`segments[2].fields[0].field\n * must be a positive integer`): profile structure only, never PHI.\n *\n * @internal (the two functions are re-exported from the package root)\n */\n\nimport { ProfileDefinitionError } from \"../parser/errors.js\";\n\nimport { USAGE_CODES, type ConformanceProfile, type FindingLocus } from \"./types.js\";\n\n/** Segment-name shape: 3 chars, standard or `Z…` segment. Mirrors the model's rule. @internal */\nconst SEGMENT_NAME_RE = /^[A-Z][A-Z0-9]{2}$/u;\n\n/** The three valid severities, for shape validation. @internal */\nconst SEVERITIES: readonly string[] = [\"error\", \"warning\", \"info\"];\n\n/**\n * One structural defect in a profile: the PHI-free `detail` plus a best-effort\n * {@link FindingLocus} (so the engine can attach it to a `PROFILE_MALFORMED`\n * finding). When the defect is above segment level, `locus.segment` is the\n * sentinel `\"(profile)\"`.\n *\n * @internal\n */\nexport interface ProfileDefect {\n readonly locus: FindingLocus;\n readonly detail: string;\n}\n\n/** Is `v` a plain object (not null, not an array)? @internal */\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Validate a {@link Cardinality} value; append any defect to `out`. @internal */\nfunction checkCardinality(card: unknown, locus: FindingLocus, out: ProfileDefect[]): void {\n if (card === undefined) return;\n if (!isObject(card)) {\n out.push({ locus, detail: `${describe(locus)} cardinality must be an object.` });\n return;\n }\n const min = card[\"min\"];\n const max = card[\"max\"];\n if (min !== undefined && (typeof min !== \"number\" || !Number.isInteger(min) || min < 0)) {\n out.push({\n locus,\n detail: `${describe(locus)} cardinality.min must be a non-negative integer.`,\n });\n }\n if (\n max !== undefined &&\n max !== \"*\" &&\n (typeof max !== \"number\" || !Number.isInteger(max) || max < 0)\n ) {\n out.push({\n locus,\n detail: `${describe(locus)} cardinality.max must be a non-negative integer or \"*\".`,\n });\n }\n if (\n typeof min === \"number\" &&\n typeof max === \"number\" &&\n Number.isInteger(min) &&\n Number.isInteger(max) &&\n max < min\n ) {\n out.push({\n locus,\n detail: `${describe(locus)} cardinality.max (${String(max)}) is less than min (${String(min)}).`,\n });\n }\n}\n\n/** Compact locus label for a defect detail. @internal */\nfunction describe(locus: FindingLocus): string {\n if (locus.segment === \"(profile)\") return \"profile\";\n let s = `segment \"${locus.segment}\"`;\n if (locus.field !== undefined) s += ` field ${String(locus.field)}`;\n return s;\n}\n\n/**\n * Collect every structural defect in a candidate conformance profile. **Total\n * over `unknown` and never throws**: a caller may pass any value (even one\n * cast through `any`) and get back a defect list rather than an exception. An\n * empty result means the profile is well-formed enough to validate against.\n *\n * @internal\n */\nexport function collectProfileDefects(profile: unknown): readonly ProfileDefect[] {\n const out: ProfileDefect[] = [];\n const root: FindingLocus = { segment: \"(profile)\" };\n\n if (!isObject(profile)) {\n out.push({ locus: root, detail: \"profile must be an object with `name` and `segments`.\" });\n return out;\n }\n if (typeof profile[\"name\"] !== \"string\" || profile[\"name\"].trim().length === 0) {\n out.push({ locus: root, detail: \"profile.name must be a non-empty string.\" });\n }\n const segments = profile[\"segments\"];\n if (!Array.isArray(segments)) {\n out.push({ locus: root, detail: \"profile.segments must be an array of segment rules.\" });\n return out;\n }\n\n for (let i = 0; i < segments.length; i++) {\n const seg: unknown = segments[i];\n if (!isObject(seg)) {\n out.push({ locus: root, detail: `segments[${String(i)}] must be an object.` });\n continue;\n }\n const name = seg[\"segment\"];\n if (typeof name !== \"string\" || !SEGMENT_NAME_RE.test(name)) {\n out.push({\n locus: root,\n detail: `segments[${String(i)}].segment must be a valid segment name ([A-Z][A-Z0-9]{2}).`,\n });\n continue;\n }\n const segLocus: FindingLocus = { segment: name };\n checkUsage(seg[\"usage\"], segLocus, out);\n checkSeverity(seg[\"severity\"], segLocus, out);\n checkCardinality(seg[\"cardinality\"], segLocus, out);\n\n const fields = seg[\"fields\"];\n if (fields !== undefined) {\n if (!Array.isArray(fields)) {\n out.push({ locus: segLocus, detail: `segment \"${name}\" fields must be an array.` });\n continue;\n }\n for (let j = 0; j < fields.length; j++) {\n checkFieldRule(fields[j], name, j, out);\n }\n }\n }\n return out;\n}\n\n/** Validate a usage code; append defect if present-and-invalid. @internal */\nfunction checkUsage(usage: unknown, locus: FindingLocus, out: ProfileDefect[]): void {\n if (usage === undefined) return;\n if (typeof usage !== \"string\" || !USAGE_CODES.includes(usage as never)) {\n out.push({\n locus,\n detail: `${describe(locus)} usage must be one of ${USAGE_CODES.join(\"/\")}.`,\n });\n }\n}\n\n/** Validate a severity; append defect if present-and-invalid. @internal */\nfunction checkSeverity(sev: unknown, locus: FindingLocus, out: ProfileDefect[]): void {\n if (sev === undefined) return;\n if (typeof sev !== \"string\" || !SEVERITIES.includes(sev)) {\n out.push({\n locus,\n detail: `${describe(locus)} severity must be one of ${SEVERITIES.join(\"/\")}.`,\n });\n }\n}\n\n/** Validate one field rule object. @internal */\nfunction checkFieldRule(rule: unknown, segment: string, index: number, out: ProfileDefect[]): void {\n const locus: FindingLocus = { segment };\n if (!isObject(rule)) {\n out.push({ locus, detail: `segment \"${segment}\" fields[${String(index)}] must be an object.` });\n return;\n }\n const field = rule[\"field\"];\n if (typeof field !== \"number\" || !Number.isInteger(field) || field < 1) {\n out.push({\n locus,\n detail: `segment \"${segment}\" fields[${String(index)}].field must be a positive (1-indexed) integer.`,\n });\n return;\n }\n const fieldLocus: FindingLocus = { segment, field };\n checkUsage(rule[\"usage\"], fieldLocus, out);\n checkSeverity(rule[\"severity\"], fieldLocus, out);\n checkCardinality(rule[\"cardinality\"], fieldLocus, out);\n\n const len = rule[\"length\"];\n if (len !== undefined && (typeof len !== \"number\" || !Number.isInteger(len) || len < 0)) {\n out.push({\n locus: fieldLocus,\n detail: `${describe(fieldLocus)} length must be a non-negative integer.`,\n });\n }\n const comp = rule[\"component\"];\n if (comp !== undefined && (typeof comp !== \"number\" || !Number.isInteger(comp) || comp < 1)) {\n out.push({\n locus: fieldLocus,\n detail: `${describe(fieldLocus)} component must be a positive (1-indexed) integer.`,\n });\n }\n const vs = rule[\"valueSet\"];\n if (vs !== undefined) {\n if (!Array.isArray(vs)) {\n out.push({\n locus: fieldLocus,\n detail: `${describe(fieldLocus)} valueSet must be an array of strings.`,\n });\n } else if (!vs.every((c) => typeof c === \"string\")) {\n out.push({\n locus: fieldLocus,\n detail: `${describe(fieldLocus)} valueSet entries must all be strings.`,\n });\n }\n }\n}\n\n/**\n * The **fail-fast authoring** gate for a conformance profile (roadmap Phase U's\n * \"malformed profile → typed `ProfileDefinitionError`, build-time, before\n * validation\"). Runs {@link collectProfileDefects}; on any defect, throws a\n * single {@link ProfileDefinitionError} listing every defect. On success,\n * returns the profile typed as {@link ConformanceProfile}.\n *\n * This is **optional**: {@link validateAgainstProfile} tolerates a raw profile\n * object and never throws: but it lets an author catch a typo when the profile\n * is written rather than when it is run.\n *\n * @throws {ProfileDefinitionError} when the profile is structurally malformed.\n *\n * @example\n * ```ts\n * import { defineConformanceProfile } from \"@cosyte/hl7\";\n * const profile = defineConformanceProfile({\n * name: \"example-adt-min\",\n * segments: [{ segment: \"PID\", usage: \"R\" }],\n * });\n * // A typo throws at authoring time:\n * // defineConformanceProfile({ name: \"x\", segments: [{ segment: \"pid\" }] });\n * // → ProfileDefinitionError: segments[0].segment must be a valid segment name…\n * ```\n */\nexport function defineConformanceProfile(profile: unknown): ConformanceProfile {\n const defects = collectProfileDefects(profile);\n if (defects.length > 0) {\n const name =\n isObject(profile) && typeof profile[\"name\"] === \"string\" ? profile[\"name\"] : undefined;\n throw new ProfileDefinitionError(\n `Conformance profile has ${String(defects.length)} defect(s): ` +\n defects.map((d) => d.detail).join(\"; \"),\n name,\n );\n }\n return profile as ConformanceProfile;\n}\n","/**\n * The conformance-profile engine (roadmap Phase U): `validateAgainstProfile`.\n * Runs a **consumer-authored** declarative {@link ConformanceProfile} against a\n * parsed {@link Hl7Message} and returns typed {@link ConformanceFinding}s.\n *\n * The sanctioned functionality-plane replacement for the retired vendor-corpus\n * arc: the consumer brings the profile and every value set; hl7 ships **no**\n * profile, **no** code set, and makes **no** network call. Four invariants the\n * engine holds absolutely:\n *\n * 1. **Never throws.** Any message × any profile (even a malformed profile, or a\n * value cast through `any`) yields a {@link ConformanceResult}, never an\n * exception. A malformed profile becomes `PROFILE_MALFORMED` findings.\n * 2. **Valid ⇒ zero findings**, and **zero findings is NOT an attestation**,\n * it means no *declared* rule was violated, nothing more (see\n * {@link ConformanceResult}).\n * 3. **No PHI in findings.** Findings name the structural locus and the rule,\n * never the offending value (see `src/conformance/findings.ts`).\n * 4. **Read-only.** Validation never mutates the message.\n */\n\nimport type { Hl7Message } from \"../model/message.js\";\nimport type { RawRepetition } from \"../parser/types.js\";\n\nimport type { Field } from \"../model/field.js\";\nimport type { Segment } from \"../model/segment.js\";\nimport * as F from \"./findings.js\";\nimport { collectProfileDefects } from \"./profile-shape.js\";\nimport {\n type Cardinality,\n type ConformanceFinding,\n type ConformanceProfile,\n type ConformanceResult,\n type FieldRule,\n type FindingLocus,\n type FindingSeverity,\n type SegmentRule,\n type UsageCode,\n} from \"./types.js\";\n\n/** A best-effort profile name for the result when the profile may be malformed. @internal */\nfunction safeName(profile: unknown): string {\n if (typeof profile === \"object\" && profile !== null && !Array.isArray(profile)) {\n const n = (profile as Record<string, unknown>)[\"name\"];\n if (typeof n === \"string\" && n.trim().length > 0) return n;\n }\n return \"(unnamed profile)\";\n}\n\n/** The decoded value at 1-indexed `component` of a repetition (`\"\"` when absent). @internal */\nfunction componentValue(rep: RawRepetition, component: number): string {\n return rep.components[component - 1]?.subcomponents[0] ?? \"\";\n}\n\n/** Does the field carry any non-empty content in any repetition/component/subcomponent? @internal */\nfunction fieldHasValue(field: Field): boolean {\n return field.repetitions.some((rep) =>\n rep.components.some((comp) => comp.subcomponents.some((sub) => sub !== \"\")),\n );\n}\n\n/**\n * Evaluate a presence obligation for a usage code against an observed\n * presence flag, returning the finding kind to emit (or `null`). Shared by the\n * segment- and field-level checks so the R / X / RE / O / C / CE semantics are\n * defined in exactly one place.\n *\n * - `R` absent ⇒ `\"required-absent\"`.\n * - `X` present ⇒ `\"not-permitted\"`.\n * - `RE` / `O` ⇒ no presence finding (RE absence is never a violation).\n * - `C` / `CE` ⇒ no presence finding: this bounded engine ships no\n * predicate language, so a conditional element's presence is **not\n * evaluated** (a documented defer, roadmap §5). Its length / value-set /\n * cardinality rules still apply when present.\n *\n * @internal\n */\nfunction presenceVerdict(\n usage: UsageCode | undefined,\n present: boolean,\n): \"required-absent\" | \"not-permitted\" | null {\n if (usage === \"R\" && !present) return \"required-absent\";\n if (usage === \"X\" && present) return \"not-permitted\";\n return null;\n}\n\n/** Check a cardinality bound against an observed count; push a finding if out of range. @internal */\nfunction checkCardinality(\n count: number,\n card: Cardinality | undefined,\n locus: FindingLocus,\n unit: \"occurrence\" | \"repetition\",\n severity: FindingSeverity,\n out: ConformanceFinding[],\n): void {\n if (card === undefined) return;\n const { min, max } = card;\n if (typeof max === \"number\" && count > max) {\n out.push(F.cardinality(locus, count, card, unit, severity));\n return;\n }\n // `min` is only checked when the element is present (count > 0). An absent\n // Required element is reported as PROFILE_REQUIRED_ABSENT (a usage finding),\n // never a second cardinality finding; an absent optional element is fine.\n if (typeof min === \"number\" && count > 0 && count < min) {\n out.push(F.cardinality(locus, count, card, unit, severity));\n }\n}\n\n/** Run every field rule of a segment rule against one occurrence of the segment. @internal */\nfunction checkFields(\n seg: Segment,\n occurrence: number,\n fields: readonly FieldRule[],\n out: ConformanceFinding[],\n): void {\n for (const rule of fields) {\n const severity: FindingSeverity = rule.severity ?? \"error\";\n const field = seg.field(rule.field);\n const present = fieldHasValue(field);\n const baseLocus: FindingLocus = { segment: seg.type, field: rule.field, occurrence };\n\n const verdict = presenceVerdict(rule.usage, present);\n if (verdict === \"required-absent\") {\n out.push(F.requiredAbsent(baseLocus, severity));\n continue; // nothing present to length/value/cardinality-check\n }\n if (verdict === \"not-permitted\") {\n out.push(F.notPermitted(baseLocus, severity));\n continue; // it should not be here; do not also value-check it\n }\n if (!present) continue; // absent-but-allowed (RE/O/C/CE): nothing to check\n\n const reps = field.repetitions;\n checkCardinality(reps.length, rule.cardinality, baseLocus, \"repetition\", severity, out);\n\n if (rule.length === undefined && rule.valueSet === undefined) continue;\n const component = rule.component ?? 1;\n for (let r = 0; r < reps.length; r++) {\n const rep = reps[r];\n if (rep === undefined) continue;\n const value = componentValue(rep, component);\n const locus: FindingLocus = {\n segment: seg.type,\n field: rule.field,\n component,\n repetition: r,\n occurrence,\n };\n if (rule.length !== undefined && value.length > rule.length) {\n out.push(F.length(locus, value.length, rule.length, severity));\n }\n if (rule.valueSet !== undefined && value !== \"\" && !rule.valueSet.includes(value)) {\n out.push(F.valueNotInSet(locus, rule.valueSet.length, severity));\n }\n }\n }\n}\n\n/** Run one segment rule (presence + cardinality + per-occurrence field rules). @internal */\nfunction checkSegment(message: Hl7Message, rule: SegmentRule, out: ConformanceFinding[]): void {\n const severity: FindingSeverity = rule.severity ?? \"error\";\n const occurrences = message.segments(rule.segment);\n const count = occurrences.length;\n const present = count > 0;\n const segLocus: FindingLocus = { segment: rule.segment };\n\n const verdict = presenceVerdict(rule.usage, present);\n if (verdict === \"required-absent\") {\n out.push(F.requiredAbsent(segLocus, severity));\n return; // no occurrences → nothing else to check\n }\n if (verdict === \"not-permitted\") {\n out.push(F.notPermitted(segLocus, severity));\n return; // present-but-forbidden; do not descend into its fields\n }\n\n checkCardinality(count, rule.cardinality, segLocus, \"occurrence\", severity, out);\n\n if (!present || rule.fields === undefined) return;\n for (let occ = 0; occ < occurrences.length; occ++) {\n const seg = occurrences[occ];\n if (seg === undefined) continue;\n checkFields(seg, occ, rule.fields, out);\n }\n}\n\n/**\n * Validate a parsed HL7 v2 message against a **user-authored** declarative\n * conformance profile (roadmap Phase U) and return typed findings.\n *\n * **Never throws.** A well-formed profile is evaluated rule by rule; a\n * malformed profile is reported as `PROFILE_MALFORMED` findings (the engine\n * does not validate against a profile it cannot trust: never a silent pass).\n * Either way you get a {@link ConformanceResult}. For fail-fast authoring, run\n * {@link defineConformanceProfile} first: it throws on a malformed profile.\n *\n * **`findings.length === 0` is NOT a conformance attestation.** It means every\n * rule the profile declared was satisfied: nothing about the parts of the\n * message the profile did not cover, and nothing about clinical correctness.\n *\n * **No PHI in findings**: each finding names the structural locus (segment /\n * field / component / repetition) and the rule, never the offending value.\n *\n * **Read-only**: the message is never mutated.\n *\n * @param message - a parsed message from {@link parseHL7}.\n * @param profile - the consumer's declarative {@link ConformanceProfile}.\n * @returns the profile name and the ordered findings (empty ⇒ no declared rule violated).\n *\n * @example\n * ```ts\n * import { parseHL7, validateAgainstProfile, type ConformanceProfile } from \"@cosyte/hl7\";\n *\n * const profile: ConformanceProfile = {\n * name: \"example-adt-min\",\n * segments: [\n * { segment: \"PID\", usage: \"R\", fields: [\n * { field: 3, name: \"Patient Identifiers\", usage: \"R\" },\n * { field: 8, name: \"Administrative Sex\", usage: \"RE\", valueSet: [\"M\", \"F\", \"U\"] },\n * ] },\n * ],\n * };\n *\n * const msg = parseHL7(raw);\n * const { findings } = validateAgainstProfile(msg, profile);\n * for (const f of findings) console.log(f.severity, f.code, f.message);\n * // findings.length === 0 ⇒ no declared rule violated (NOT an attestation)\n * ```\n */\nexport function validateAgainstProfile(\n message: Hl7Message,\n profile: ConformanceProfile,\n): ConformanceResult {\n const defects = collectProfileDefects(profile);\n if (defects.length > 0) {\n const findings = defects.map((d) => F.malformed(d.locus, d.detail));\n return Object.freeze({ profileName: safeName(profile), findings: Object.freeze(findings) });\n }\n\n const out: ConformanceFinding[] = [];\n for (const rule of profile.segments) {\n checkSegment(message, rule, out);\n }\n return Object.freeze({ profileName: profile.name, findings: Object.freeze(out) });\n}\n","/**\n * Barrel for the conformance-profile engine (roadmap Phase U). Re-exports the\n * engine, the fail-fast profile-authoring gate, and the public types. Also\n * available as the `conformance` namespace object from the package root.\n *\n * @see validateAgainstProfile: run a user-authored profile against a message.\n * @see defineConformanceProfile: optional fail-fast profile-authoring gate.\n */\n\nexport { validateAgainstProfile } from \"./validate-against-profile.js\";\nexport { collectProfileDefects, defineConformanceProfile } from \"./profile-shape.js\";\nexport type { ProfileDefect } from \"./profile-shape.js\";\nexport {\n FINDING_CODES,\n USAGE_CODES,\n type Cardinality,\n type ConformanceFinding,\n type ConformanceProfile,\n type ConformanceResult,\n type FieldRule,\n type FindingCode,\n type FindingLocus,\n type FindingSeverity,\n type SegmentRule,\n type UsageCode,\n} from \"./types.js\";\n","/**\n * Streaming / incremental parse for the `@cosyte/hl7` parser (roadmap\n * Phase S). Real ELR / IIS / lab feeds and files ship many messages and can be\n * far too large to buffer whole; a live source (an already-de-framed MLLP feed,\n * a growing file) has no \"whole\" to buffer at all. `parseStream()` consumes a\n * **chunked** byte/string source: a Node `Readable`, an async-iterable, or a\n * plain iterable of chunks: and **yields one {@link StreamMessageEntry} per\n * `MSH`-delimited message** as each boundary completes, holding only\n * **O(one message)** of state (the in-flight message's lines plus the current\n * partial-segment buffer): never the whole stream.\n *\n * Design (HL7 v2 Ch. 2; note this is engineering guidance, not a spec-mandated\n * streaming grammar: the base standard prescribes no incremental parse):\n *\n * - **`MSH` at segment start is the message boundary.** A message runs from an\n * `MSH` segment up to (but not including) the next `MSH` (or a batch-envelope\n * segment, or end of stream). This mirrors {@link splitBatch}'s in-memory\n * demarcation exactly, so the streamed decomposition of a buffer is identical\n * to the whole-buffer one.\n * - **Batch-aware.** The four batch-envelope segments (`FHS`/`BHS`/`BTS`/`FTS`,\n * §2.10.3) act as message boundaries (they flush the current message) and are\n * **never yielded as messages**, so `yielded count == MSH count`. Envelope\n * **count reconciliation** (BTS-1 / FTS-1) is {@link splitBatch}'s job, not this\n * surface's: `parseStream` streams *messages*, not a batch report.\n * - **Chunk-boundary invariant.** Segments (including the `MSH|^~\\&` header) are\n * only demarcated once their terminator arrives, so a message split across two\n * chunks (mid-segment, mid-field, even mid-`MSH`) is reassembled correctly.\n * Feeding the same bytes in 1-byte chunks vs. one big chunk yields **identical**\n * messages. A `\\r\\n` terminator split across a chunk boundary is not mistaken\n * for a bare `\\r` + empty segment (a trailing `\\r` waits for the next chunk).\n * - **Terminator tolerance.** `\\r`, `\\r\\n`, and `\\n` are all accepted as segment\n * terminators (Postel's Law: real feeds mix them), matching the core parser's\n * `normalize`.\n * - **Isolation, never dropped tails.** Each message is parsed by the shipped\n * {@link parseHL7} (no second grammar; raw extraction semantics unchanged) and\n * surfaced as either an `ok` entry (its own `.warnings` hold per-message\n * deviations) or a typed **failure** entry carrying the `Hl7ParseError`. A\n * corrupt message mid-stream is isolated: it **never suppresses** the messages\n * after it. A final message that ends without a segment terminator is still\n * yielded in full, flagged via a stream-level {@link unterminatedStreamMessage}\n * warning (never a throw), so a truncated feed is surfaced, never silently\n * dropped.\n *\n * Transport framing (MLLP `<SB>…<EB><CR>`) is **out of scope**: this consumes an\n * already-de-framed stream; `@cosyte/mllp` owns the wire. See\n * `docs-content/spec-notes-stream.md`.\n */\n\nimport { Buffer } from \"node:buffer\";\n\nimport { parseHL7 } from \"./index.js\";\nimport { Hl7ParseError } from \"./errors.js\";\nimport type { Hl7Position, ParseOptions, Profile } from \"./types.js\";\nimport { unterminatedStreamMessage } from \"./warnings.js\";\nimport type { Hl7ParseWarning } from \"./warnings.js\";\n\nimport type { Hl7Message } from \"../model/message.js\";\n\n/**\n * A chunked source `parseStream` can consume: a Node `Readable`, any\n * async-iterable, or any plain iterable of chunks. Chunks are `string`\n * (text stream) or `Buffer`/`Uint8Array` (binary stream). A real Node stream in\n * binary mode yields `Buffer`s; in text mode it yields `string`s: a source is\n * expected to be **homogeneous** (all-text or all-binary), which every real\n * `Readable` is. A binary chunk is decoded 1:1 via `latin1` (a lossless\n * byte↔codepoint mapping) so each message's own MSH-18 charset resolution runs\n * on its original bytes, exactly as {@link splitBatch} does.\n *\n * @example\n * ```ts\n * import { createReadStream } from \"node:fs\";\n * import { parseStream } from \"@cosyte/hl7\";\n *\n * const src: Hl7StreamSource = createReadStream(\"feed.hl7\");\n * for await (const entry of parseStream(src)) {\n * if (entry.ok) handle(entry.message);\n * else quarantine(entry.raw, entry.error.code);\n * }\n * ```\n */\nexport type Hl7StreamSource =\n | AsyncIterable<string | Buffer | Uint8Array>\n | Iterable<string | Buffer | Uint8Array>;\n\n/**\n * One message yielded by {@link parseStream}. Discriminated on `ok`, mirroring\n * {@link splitBatch}'s per-message entry: a successful parse carries the\n * `Hl7Message` (whose own `.warnings` hold per-message Tier-2 deviations); a\n * message that hit one of the four Tier-3 fatals carries the `Hl7ParseError`\n * instead: **isolated**, so the rest of the stream still yields.\n *\n * `raw` is the message's verbatim source (re-parseable by {@link parseHL7});\n * `position.segmentIndex` is the message's `MSH` (or, for stray pre-`MSH`\n * content, its first) segment index in the overall stream: the streaming\n * analogue of {@link splitBatch}'s message position. `streamWarnings` holds\n * **stream-level** diagnostics that are not per-message parse warnings: today\n * only {@link unterminatedStreamMessage} on a final message that lacked a\n * terminator. It is kept separate from `message.warnings` (which stays exactly\n * what a whole-buffer `parseHL7` of the same bytes would produce) and is\n * **empty** for every message but a possibly-truncated final one. Both the entry\n * and `streamWarnings` are frozen.\n *\n * @example\n * ```ts\n * import { parseStream, WARNING_CODES } from \"@cosyte/hl7\";\n * for await (const entry of parseStream(source)) {\n * for (const w of entry.streamWarnings) {\n * if (w.code === WARNING_CODES.UNTERMINATED_STREAM_MESSAGE) {\n * // the feed may have been cut off mid-message\n * }\n * }\n * }\n * ```\n */\nexport type StreamMessageEntry =\n | {\n readonly ok: true;\n readonly message: Hl7Message;\n readonly raw: string;\n readonly position: Hl7Position;\n readonly streamWarnings: readonly Hl7ParseWarning[];\n }\n | {\n readonly ok: false;\n readonly error: Hl7ParseError;\n readonly raw: string;\n readonly position: Hl7Position;\n readonly streamWarnings: readonly Hl7ParseWarning[];\n };\n\n/** The three batch-envelope names that act as message boundaries in a stream. */\nfunction isEnvelopeName(name: string): boolean {\n return name === \"FHS\" || name === \"BHS\" || name === \"BTS\" || name === \"FTS\";\n}\n\n/**\n * Decode one raw chunk into text. A `string` passes through; a `Buffer` /\n * `Uint8Array` is read as `latin1` (1 byte → 1 codepoint, lossless) so the\n * per-message slice re-encodes to its original bytes for MSH-18 charset\n * resolution. `wasBuffer` records whether the byte path was taken.\n *\n * @internal\n */\nfunction decodeChunk(chunk: unknown): { text: string; wasBuffer: boolean } {\n if (typeof chunk === \"string\") return { text: chunk, wasBuffer: false };\n if (chunk instanceof Uint8Array) {\n return { text: Buffer.from(chunk).toString(\"latin1\"), wasBuffer: true };\n }\n throw new TypeError(\n \"parseStream: each chunk must be a string, Buffer, or Uint8Array; \" +\n `received ${chunk === null ? \"null\" : typeof chunk}.`,\n );\n}\n\n/**\n * Normalize any source (async-iterable, iterable, or Node `Readable`) into a\n * single async iterator of chunks. A `Readable` is an `AsyncIterable`, so the\n * async-iterable branch covers it. Rejects a non-iterable source with a typed\n * error rather than silently yielding nothing.\n *\n * @internal\n */\nasync function* iterateChunks(source: Hl7StreamSource): AsyncGenerator<unknown> {\n if (source === null || source === undefined) {\n throw new TypeError(\"parseStream: source must be an async-iterable or iterable of chunks.\");\n }\n const asAsync = (source as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator];\n if (typeof asAsync === \"function\") {\n for await (const chunk of source as AsyncIterable<unknown>) yield chunk;\n return;\n }\n const asSync = (source as { [Symbol.iterator]?: unknown })[Symbol.iterator];\n if (typeof asSync === \"function\") {\n for (const chunk of source as Iterable<unknown>) yield chunk;\n return;\n }\n throw new TypeError(\n \"parseStream: source must be an async-iterable or iterable of chunks (e.g. a Node Readable).\",\n );\n}\n\n/**\n * Extract the next complete segment from `buf` starting at `cursor`, or `null`\n * when the buffer does not yet hold a full segment (more data is needed).\n * Terminators are `\\r`, `\\r\\n`, or `\\n`. A trailing `\\r` at the very end of a\n * non-final buffer returns `null` (it may be the first half of a `\\r\\n` split\n * across a chunk boundary: waiting avoids a spurious empty segment); on the\n * final drain (`final: true`) the trailing `\\r` is a real terminator.\n *\n * @internal\n */\nfunction nextSegment(\n buf: string,\n cursor: number,\n final: boolean,\n): { seg: string; next: number } | null {\n if (cursor >= buf.length) return null;\n const r = buf.indexOf(\"\\r\", cursor);\n const n = buf.indexOf(\"\\n\", cursor);\n let idx: number;\n let isCr: boolean;\n if (r === -1 && n === -1) return null;\n else if (r === -1) {\n idx = n;\n isCr = false;\n } else if (n === -1) {\n idx = r;\n isCr = true;\n } else if (r < n) {\n idx = r;\n isCr = true;\n } else {\n idx = n;\n isCr = false;\n }\n // A bare trailing \\r might be the CR of a \\r\\n straddling the chunk boundary.\n if (isCr && idx === buf.length - 1 && !final) return null;\n let termLen = 1;\n if (isCr && idx + 1 < buf.length && buf.charCodeAt(idx + 1) === 0x0a) termLen = 2;\n return { seg: buf.slice(cursor, idx), next: idx + termLen };\n}\n\n/**\n * Parse one fully-demarcated message and classify it, exactly as `splitBatch`\n * does per message: a successful {@link parseHL7} yields an `ok` entry; one of\n * the four Tier-3 fatals (or, under `strict`, a promoted Tier-2 warning) is\n * caught and returned as a typed failure entry so it never suppresses later\n * messages. Any non-parser throw is genuinely unexpected and re-raised.\n *\n * @internal\n */\nfunction parseStreamEntry(\n rawMessage: string,\n position: Hl7Position,\n wasBuffer: boolean,\n optionsOrProfile: ParseOptions | Profile | undefined,\n streamWarnings: readonly Hl7ParseWarning[],\n): StreamMessageEntry {\n const input: string | Buffer = wasBuffer ? Buffer.from(rawMessage, \"latin1\") : rawMessage;\n try {\n const message =\n optionsOrProfile === undefined\n ? parseHL7(input)\n : parseHL7(input, optionsOrProfile as ParseOptions);\n return Object.freeze({ ok: true, message, raw: rawMessage, position, streamWarnings });\n } catch (error) {\n if (error instanceof Hl7ParseError) {\n return Object.freeze({ ok: false, error, raw: rawMessage, position, streamWarnings });\n }\n throw error;\n }\n}\n\n/**\n * Incrementally parse a chunked HL7 v2 byte / text stream, yielding one\n * {@link StreamMessageEntry} per `MSH`-delimited message as its boundary\n * completes, with **O(one-message)** memory: the whole stream is never\n * retained. Demarcates by `MSH` boundaries inside the optional\n * `[FHS] { [BHS] { MSH… } [BTS] } [FTS]` batch frame (HL7 v2 Ch. 2 §2.10.3):\n *\n * - a message split across chunk boundaries (mid-segment, mid-field, even\n * mid-`MSH|^~\\&`) is reassembled correctly: feeding the same bytes in 1-byte\n * chunks vs. one chunk yields **identical** messages;\n * - `\\r`, `\\r\\n`, and `\\n` segment terminators are all tolerated (a `\\r\\n` split\n * across a chunk boundary is not mistaken for a bare `\\r`);\n * - each message is parsed by the shipped {@link parseHL7} (no second grammar),\n * `ok` entries carry the `Hl7Message`, a Tier-3 fatal is an isolated failure\n * entry; a **malformed message never suppresses later messages**;\n * - batch-envelope segments (`FHS`/`BHS`/`BTS`/`FTS`) are treated as boundaries\n * and never yielded as messages, so `yielded count == MSH count` (envelope\n * count reconciliation is {@link splitBatch}'s job);\n * - a final message with no trailing terminator is still yielded, flagged with a\n * stream-level {@link unterminatedStreamMessage} warning: **never a throw, the\n * tail is never dropped**.\n *\n * The second argument, when given, is forwarded verbatim to {@link parseHL7} for\n * **each** message (profile, `strict`, `charset`, `dateFormats`, …), exactly as\n * {@link splitBatch} forwards it.\n *\n * @example\n * ```ts\n * import { parseStream } from \"@cosyte/hl7\";\n *\n * async function* chunks() {\n * yield \"MSH|^~\\\\&|A|F|B|G|20260101||ADT^A01|1|P|2.5\\rPID|||1\\r\";\n * yield \"MSH|^~\\\\&|A|F|B|G|20260101||ADT^A01|2|P|2.5\\rPID|||2\\r\";\n * }\n *\n * let count = 0;\n * for await (const entry of parseStream(chunks())) {\n * if (entry.ok) count += 1; // 2: one per MSH, streamed, released each time\n * }\n * ```\n */\nexport function parseStream(\n source: Hl7StreamSource,\n): AsyncGenerator<StreamMessageEntry, void, void>;\nexport function parseStream(\n source: Hl7StreamSource,\n profile: Profile,\n): AsyncGenerator<StreamMessageEntry, void, void>;\nexport function parseStream(\n source: Hl7StreamSource,\n options: ParseOptions,\n): AsyncGenerator<StreamMessageEntry, void, void>;\n/** @internal implementation signature; overloads above carry the public JSDoc. */\nexport async function* parseStream(\n source: Hl7StreamSource,\n optionsOrProfile?: ParseOptions | Profile,\n): AsyncGenerator<StreamMessageEntry, void, void> {\n // A bare string is Iterable<string> (of single characters) and a bare Buffer\n // is Iterable<number> (of bytes): both would be silently mis-consumed as a\n // \"stream of chunks\". Reject them with a pointer to the right surface: a\n // single message is `parseHL7`'s job, and a whole buffer to stream is wrapped\n // in an array (`parseStream([buffer])`).\n if (typeof source === \"string\" || source instanceof Uint8Array) {\n throw new TypeError(\n \"parseStream expects a stream of chunks (a Node Readable, an async-iterable, or an \" +\n \"iterable of string/Buffer chunks), not a single string or Buffer. For one message use \" +\n \"parseHL7; to stream a whole buffer, wrap it: parseStream([buffer]).\",\n );\n }\n\n // The single partial-segment buffer: text seen but not yet formed into a\n // complete segment. Bounded by one segment (chunked feed): never the file.\n let pending = \"\";\n // The current in-flight message's completed segment lines. Released on every\n // flush (yield), so at most one message's worth of lines is ever retained.\n let currentLines: string[] = [];\n let messageStartIndex = -1;\n // The running segment index in the overall stream (blanks included), so a\n // message's position mirrors splitBatch's MSH segment index.\n let globalSegmentIndex = 0;\n // Whether the byte path was taken (binary source): governs per-message\n // re-encode. Determined by the first chunk; sources are homogeneous.\n let wasBuffer = false;\n let firstChunkSeen = false;\n let bomStripped = false;\n\n /**\n * Finalize `currentLines` into an entry, or `null` when the run is empty.\n * Trailing empty segments are dropped (inter-message whitespace); a run of\n * only-empty lines is nothing. `finalUnterminated` attaches the stream-level\n * unterminated-message warning. Always releases `currentLines`.\n */\n const flush = (finalUnterminated: boolean): StreamMessageEntry | null => {\n while (currentLines.length > 0 && currentLines[currentLines.length - 1] === \"\") {\n currentLines.pop();\n }\n if (currentLines.length === 0) {\n messageStartIndex = -1;\n return null;\n }\n const position: Hl7Position = Object.freeze({ segmentIndex: messageStartIndex });\n const streamWarnings: readonly Hl7ParseWarning[] = finalUnterminated\n ? Object.freeze([unterminatedStreamMessage(position)])\n : Object.freeze([]);\n const entry = parseStreamEntry(\n currentLines.join(\"\\r\"),\n position,\n wasBuffer,\n optionsOrProfile,\n streamWarnings,\n );\n currentLines = [];\n messageStartIndex = -1;\n return entry;\n };\n\n /**\n * Route one completed segment through MSH-boundary demarcation, returning the\n * PREVIOUS message to yield when this segment closes it (an `MSH` or an\n * envelope boundary), else `null`. Mirrors `splitBatch`'s per-segment walk.\n */\n const processSegment = (seg: string): StreamMessageEntry | null => {\n const thisIndex = globalSegmentIndex;\n globalSegmentIndex += 1;\n const name = seg.slice(0, 3);\n if (isEnvelopeName(name)) {\n // Boundary: close the current message; the envelope itself is not a\n // message and is not yielded.\n return flush(false);\n }\n if (name === \"MSH\") {\n const flushed = flush(false);\n currentLines = [seg];\n messageStartIndex = thisIndex;\n return flushed;\n }\n // Message body: or stray content before the first MSH, which is kept (never\n // dropped) and surfaces as a NO_MSH_SEGMENT failure entry on flush.\n if (currentLines.length === 0) {\n // A blank line between messages is inter-message whitespace: skip it (its\n // index is still consumed above so positions stay stable).\n if (seg.trim() === \"\") return null;\n messageStartIndex = thisIndex;\n }\n currentLines.push(seg);\n return null;\n };\n\n /** Resolve a possibly chunk-split leading BOM before segmenting. */\n const tryStripBom = (final: boolean): void => {\n if (bomStripped || pending.length === 0) return;\n if (pending.charCodeAt(0) === 0xfeff) {\n pending = pending.slice(1);\n bomStripped = true;\n } else if (pending.startsWith(\"\")) {\n // UTF-8 BOM read through latin1 (bytes EF BB BF).\n pending = pending.slice(3);\n bomStripped = true;\n } else if (final || !\"\".startsWith(pending)) {\n // Not a BOM (and not a partial BOM prefix awaiting more bytes).\n bomStripped = true;\n }\n };\n\n for await (const rawChunk of iterateChunks(source)) {\n const { text, wasBuffer: chunkWasBuffer } = decodeChunk(rawChunk);\n if (!firstChunkSeen) {\n wasBuffer = chunkWasBuffer;\n firstChunkSeen = true;\n }\n if (text.length === 0) continue;\n pending += text;\n tryStripBom(false);\n if (!bomStripped) continue; // still disambiguating a split BOM\n let cursor = 0;\n for (;;) {\n const res = nextSegment(pending, cursor, false);\n if (res === null) break;\n cursor = res.next;\n const entry = processSegment(res.seg);\n if (entry !== null) yield entry;\n }\n // Release the consumed prefix; keep only the trailing partial segment.\n pending = pending.slice(cursor);\n }\n\n // End of stream. Force-resolve any still-pending BOM, then drain every\n // remaining complete segment (final: a trailing \\r is now a real terminator).\n tryStripBom(true);\n {\n let cursor = 0;\n for (;;) {\n const res = nextSegment(pending, cursor, true);\n if (res === null) break;\n cursor = res.next;\n const entry = processSegment(res.seg);\n if (entry !== null) yield entry;\n }\n pending = pending.slice(cursor);\n }\n\n // Whatever is left in `pending` is a final segment with NO terminator (a\n // truncated tail). Route it through the SAME per-segment logic the rest of the\n // stream uses, so a streamed message stays byte-for-byte identical to what\n // `splitBatch` yields for the same bytes: `splitBatch` keeps a final\n // unterminated segment verbatim (its `flushMessage` pops only exact-empty\n // trailing lines, and `processSegment` here skips a whitespace-only line only\n // when no message is open: the same inter-message-noise rule). The\n // stream-level unterminated flag fires only for a genuine (non-blank) content\n // tail, never for trailing whitespace (which is not a truncation signal).\n const tail = pending;\n pending = \"\";\n let finalUnterminated = false;\n if (tail.length > 0) {\n const flushed = processSegment(tail);\n if (flushed !== null) yield flushed;\n // The message now held in `currentLines` (if any) ends without a terminator.\n finalUnterminated = currentLines.length > 0 && tail.trim() !== \"\";\n }\n const finalEntry = flush(finalUnterminated);\n if (finalEntry !== null) yield finalEntry;\n}\n","/**\n * Public entry point for the `@cosyte/hl7` package.\n *\n * The full public API (parseHL7, defineProfile, helpers, types) is populated\n * in subsequent phases. This stub keeps the module resolvable and typed so\n * downstream tooling (tsup, vitest, tsc) can verify the build/typecheck\n * pipeline end-to-end.\n */\n\n/**\n * Library version string, synced with `package.json#version` at build time\n * by downstream phases. Exported now so consumers (and the type-check\n * pipeline) have at least one symbol to resolve through the `exports` map.\n *\n * @example\n * ```ts\n * import { VERSION } from \"@cosyte/hl7\";\n * console.log(VERSION);\n * ```\n */\nexport const VERSION: string = \"0.0.2\";\n\nexport { parseHL7 } from \"./parser/index.js\";\nexport { Hl7Message } from \"./model/message.js\";\nexport { FATAL_CODES, Hl7ParseError, ProfileDefinitionError } from \"./parser/errors.js\";\nexport type { FatalCode } from \"./parser/errors.js\";\nexport {\n WARNING_CODES,\n mllpFramingStripped,\n fieldWhitespaceTrimmed,\n unknownEscapeSequence,\n unterminatedEscapeSequence,\n timestampFallbackFormat,\n segmentCase,\n extraFields,\n unknownSegment,\n duplicateRequiredSegment,\n encodingMismatch,\n missingRequiredField,\n missingExpectedGroup,\n outOfOrderSegment,\n versionMismatch,\n unknownCharset,\n unsupportedCharset,\n} from \"./parser/warnings.js\";\nexport type { WarningCode, Hl7ParseWarning } from \"./parser/warnings.js\";\n\n// Phase O additive: the frozen HL7 Table-0211 charset registry, so advanced\n// consumers can inspect how an MSH-18 code is treated (decoded vs preserved).\nexport { resolveCharset, canonicalCharset } from \"./parser/charset.js\";\nexport type { CharsetResolution, CharsetTreatment } from \"./parser/charset.js\";\nexport { DEFAULT_ENCODING_CHARACTERS } from \"./parser/delimiters.js\";\nexport type {\n Hl7Position,\n ParseOptions,\n OnWarningCallback,\n Profile,\n EncodingCharacters,\n RawSegment,\n RawField,\n RawRepetition,\n RawComponent,\n} from \"./parser/types.js\";\nexport { BUILTIN_DATE_FALLBACKS, parseDtm, formatDtm, dtmToDate } from \"./parser/dates.js\";\nexport type { DtmParts, DtmPrecision, DtmToDateOptions } from \"./parser/dates.js\";\nexport { unescape, reescape } from \"./parser/escapes.js\";\n\n// Phase R: formatted-text rendering + first-class text codec. `renderText`\n// turns §2.7 escape/formatting-bearing content into a normalized display model\n// (never fabricating: unrenderable escapes are preserved + flagged); the\n// `decodeText`/`encodeText` codec is the ergonomic decode + encode-safe (no\n// delimiter injection) pair. All three are also bundled under the `text`\n// namespace object. This is a read/encode LAYER: raw parse output is unchanged.\nexport { renderText } from \"./text/render.js\";\nexport type { RenderedText, TextRun, RenderTextOptions } from \"./text/render.js\";\nexport { decodeText, encodeText } from \"./text/codec.js\";\nexport * as text from \"./text/index.js\";\n\n// Phase 3 structural model: read-path foundation.\nexport { Segment } from \"./model/segment.js\";\nexport { Field } from \"./model/field.js\";\nexport { parsePath, resolvePath } from \"./model/dot-path.js\";\nexport type { DotPath } from \"./model/dot-path.js\";\n\n// Phase 3 typed composites: named exports for the 10 v1 composites\n// (XPN, XAD, CX, CWE, CE, XTN, PL, TS, NM, HD) alongside their parser\n// functions. D-13: these are ALSO re-exported under the `HL7` namespace\n// below so `import { HL7 } from \"@cosyte/hl7\"; type T = HL7.XPN`\n// resolves to the same interface as the named `XPN` import.\nexport type { XPN } from \"./model/types/xpn.js\";\nexport { parseXpn } from \"./model/types/xpn.js\";\nexport type { XAD } from \"./model/types/xad.js\";\nexport { parseXad } from \"./model/types/xad.js\";\nexport type { CX } from \"./model/types/cx.js\";\nexport { parseCx } from \"./model/types/cx.js\";\nexport type { CWE } from \"./model/types/cwe.js\";\nexport { parseCwe } from \"./model/types/cwe.js\";\nexport type { CE } from \"./model/types/ce.js\";\nexport { parseCe } from \"./model/types/ce.js\";\nexport type { XTN } from \"./model/types/xtn.js\";\nexport { parseXtn } from \"./model/types/xtn.js\";\nexport type { PL } from \"./model/types/pl.js\";\nexport { parsePl } from \"./model/types/pl.js\";\nexport type { TS } from \"./model/types/ts.js\";\nexport { parseTs } from \"./model/types/ts.js\";\nexport type { NM } from \"./model/types/nm.js\";\nexport { parseNm } from \"./model/types/nm.js\";\nexport type { SN } from \"./model/types/sn.js\";\nexport { parseSn } from \"./model/types/sn.js\";\nexport type { HD } from \"./model/types/hd.js\";\nexport { parseHd } from \"./model/types/hd.js\";\n\n// Phase 4: XCN composite (11th v1 composite: D-24 option (a)). Used by\n// helpers for `visit.attendingDoctor` / `visit.referringDoctor` (PV1-7/8)\n// and `order.orderedBy` (OBR-16). Structurally XPN + ID prefix + nested HD.\nexport type { XCN } from \"./model/types/xcn.js\";\nexport { parseXcn } from \"./model/types/xcn.js\";\n\n// Phase 3 HL7 namespace re-export (D-13): `HL7.XPN`, `HL7.XAD`, ..., `HL7.XCN`.\nexport * as HL7 from \"./model/types/namespace.js\";\n\n// Phase 4 named helpers: type-only exports. Runtime behavior lives on\n// `Hl7Message` instance getters (`.meta`, `.patient`, `.visit`) and\n// collection methods (`.observations()`, `.orders()`, `.nextOfKin()`,\n// `.allergies()`, `.diagnoses()`, `.insurance()`). HELPERS-01..07.\nexport type {\n Allergy,\n Appointment,\n AppointmentResource,\n Charge,\n ClinicalDocument,\n Diagnosis,\n Immunization,\n ImmunizationRecordOrigin,\n Insurance,\n Medication,\n MedicationAmount,\n MedicationComponent,\n MedicationContext,\n MedicationRoute,\n MedicationStrength,\n Meta,\n NextOfKin,\n Observation,\n ObservationBase,\n Order,\n OrderTiming,\n Patient,\n RepeatPattern,\n RepeatPatternKind,\n TimingQuantity,\n Visit,\n} from \"./helpers/types.js\";\n\n// Phase 4: `pickMrn` is exposed as a named export so Phase 6 profile override\n// hooks can substitute a profile-aware variant without patching the helper\n// that calls it (D-07/D-08/D-10 default; Phase 6 hook-point).\nexport { pickMrn } from \"./helpers/pick-mrn.js\";\n\n// Roadmap Phase K: patient-identity / merge events. Runtime behavior lives on\n// `Hl7Message.identityEvents()`; the typed views + the event-scoped warning\n// factory are the named exports.\nexport type {\n IdentityEvent,\n IdentityEventKind,\n IdentityParty,\n IdentityRole,\n} from \"./helpers/identity.js\";\nexport { mergeMissingPriorOrSurvivor } from \"./parser/warnings.js\";\n\n// Phase 5: outbound construction + serialization types.\n// D-09: `buildMessage` is a top-level named export, symmetric with `parseHL7`.\n// D-21: `SerializedMessage` is a top-level type export (not under the HL7\n// namespace: that namespace is composite-type territory).\n// The three emit methods (`toString`, `toJSON`, `prettyPrint`) land as\n// instance methods on the already-exported `Hl7Message` class: no new\n// named exports needed for them.\nexport { buildMessage } from \"./builder/build-message.js\";\nexport type { BuildMessageInit } from \"./builder/build-message.js\";\nexport type { SerializedMessage } from \"./serialize/to-json.js\";\n\n// Phase T: typed emit symmetry: the conservative-emit mirror of the read\n// helpers. `encodeComposite` (and the per-type `encodeXpn`/`encodeCx`/… it\n// dispatches to) turn a typed composite into a spec-clean field using the\n// HL7-R encode-safe path (no delimiter injection); the same encoding powers\n// `Hl7Message.setComposite(path, kind, value)`. `buildAdt`/`buildOru` author\n// spec-clean, zero-warning, structurally-complete ADT / ORU^R01 messages from\n// typed inputs: never fabricating a value the caller did not supply.\nexport {\n encodeComposite,\n encodeCompositeReps,\n encodeXpn,\n encodeXad,\n encodeCx,\n encodeCwe,\n encodeCe,\n encodeXtn,\n encodePl,\n encodeHd,\n encodeTs,\n encodeNm,\n encodeXcn,\n} from \"./builder/encode-composite.js\";\nexport type { CompositeKind, CompositeValueByKind } from \"./builder/encode-composite.js\";\nexport { buildAdt } from \"./builder/build-adt.js\";\nexport type { AdtEvent, AdtPatient, AdtVisit, BuildAdtInit } from \"./builder/build-adt.js\";\nexport { buildOru } from \"./builder/build-oru.js\";\nexport type { BuildOruInit, OruObservation, OruOrder, OruPatient } from \"./builder/build-oru.js\";\n\n// Phase C: ACK / response generation. `buildAck` is the single upstream ACK\n// *content* primitive (`@cosyte/mllp`'s ack-from-hl7 adapts over it);\n// `interpretAck` is the read-side; `detectAckMode` exposes the spec-exact\n// original-vs-enhanced detection. Control vocabulary (Tables 0008/0357/0516/\n// 0155) ships as frozen read-only enums.\nexport { buildAck, detectAckMode } from \"./builder/build-ack.js\";\nexport type { AckErrorDetail, BuildAckOptions } from \"./builder/build-ack.js\";\nexport { interpretAck } from \"./helpers/acknowledgment.js\";\nexport type { Acknowledgment, AckErrorEntry } from \"./helpers/acknowledgment.js\";\nexport {\n ACK_CODES,\n ACK_CONDITIONS,\n downgradePositiveAck,\n ERR_CONDITION_CODES,\n ERR_CONDITION_CODE_SYSTEM,\n ERR_SEVERITIES,\n isPositiveAck,\n} from \"./builder/ack-tables.js\";\nexport type { AckCode, AckCondition, AckMode, ErrSeverity } from \"./builder/ack-tables.js\";\nexport { ackNoCorrelationId } from \"./parser/warnings.js\";\n\n// Phase 6: profile system + built-in vendor profiles.\n// D-26: defineProfile / setDefaultProfile / getDefaultProfile are top-level\n// values; built-ins are exposed under the `profiles` namespace object, not\n// as top-level named exports (`epic` is too generic a name for a top-level\n// export).\nexport { defineProfile, setDefaultProfile, getDefaultProfile, profiles } from \"./profiles/index.js\";\nexport type { DefineProfileOptions, CustomSegmentDefinition } from \"./profiles/index.js\";\n\n// Plan 01 additive: SUPPORTED_DATE_TOKENS re-export so profile authors can\n// introspect valid date-format tokens without reaching into internals.\nexport { SUPPORTED_DATE_TOKENS } from \"./parser/dates.js\";\n\n// Plan 03 additive: KNOWN_SEGMENTS re-export so advanced consumers can\n// inspect the UNKNOWN_SEGMENT detection set (read-only).\nexport { KNOWN_SEGMENTS } from \"./parser/known-segments.js\";\n\n// Phase F: coding-system provenance (HL7 Table 0396, read-only). A frozen\n// acronym→name map plus accessors that answer \"what system does this code\n// CLAIM?\" over CWE/CE: alias-normalized, never validated, unknown surfaced\n// verbatim with `known:false`. No lookup, no network, no bundled codeset.\nexport {\n KNOWN_CODING_SYSTEMS,\n codingSystem,\n codingSystemOf,\n alternateCodingSystemOf,\n} from \"./model/coding-system.js\";\nexport type {\n KnownCodingSystem,\n CodingSystemInfo,\n CodedSystemFields,\n} from \"./model/coding-system.js\";\n\n// Phase G: message-type & structure awareness: a conservative misroute/\n// truncation safety net. `Hl7Message.structure` surfaces the read-side\n// summary; the parser emits an additive `MISSING_EXPECTED_GROUP` warning when\n// a recognized type lacks an expected Required segment group. The expected-\n// group registry + the pure analyzer are exposed read-only for introspection.\nexport {\n MESSAGE_STRUCTURE_DEFINITIONS,\n analyzeMessageStructure,\n} from \"./parser/message-structure.js\";\nexport type {\n ExpectedSegmentGroup,\n MessageStructureDefinition,\n StructureGroup,\n MessageStructure,\n} from \"./parser/message-structure.js\";\n\n// Roadmap Phase L: batch / file envelope splitting. `splitBatch` is a\n// top-level utility (symmetric with `parseHL7`) that demarcates the individual\n// MSH-led messages inside an `[FHS]{[BHS]{MSH…}[BTS]}[FTS]` stream, parses each\n// via parseHL7 (ok / typed-failure entries: a malformed message is isolated,\n// never suppresses siblings), and reconciles the declared BTS-1/FTS-1 counts.\n// The two additive Tier-2 warnings live on the returned result, never on\n// Hl7Message.warnings.\nexport { splitBatch } from \"./parser/batch.js\";\nexport type {\n Batch,\n BatchEnvelopeName,\n BatchEnvelopeSegment,\n BatchMessageEntry,\n BatchSplitResult,\n} from \"./parser/batch.js\";\nexport { batchCountMismatch, batchMissingTrailer } from \"./parser/warnings.js\";\n\n// Roadmap Phase U: conformance-profile TOOLING. `validateAgainstProfile` runs a\n// USER-AUTHORED declarative conformance profile (usage R/RE/C/CE/O/X,\n// cardinality, length, and a CONSUMER-SUPPLIED value set) against a parsed\n// message and returns typed findings: never throwing, valid⇒zero findings, and\n// with NO PHI in findings (locus + rule, never the offending value). hl7 ships\n// NO vendor/IHE/regulatory profile and NO code set, makes NO network call, and\n// \"no findings\" is explicitly NOT a conformance attestation. Distinct from the\n// PARSE-profile system (`defineProfile`/`profiles`): this validates a message\n// against a conformance spec; that shapes how a message is parsed.\n// `defineConformanceProfile` is the optional fail-fast authoring gate (throws\n// `ProfileDefinitionError` on a malformed profile); the engine itself tolerates\n// a raw profile and never throws. Also bundled under the `conformance` namespace.\nexport { validateAgainstProfile } from \"./conformance/validate-against-profile.js\";\nexport { defineConformanceProfile } from \"./conformance/profile-shape.js\";\nexport {\n FINDING_CODES,\n USAGE_CODES,\n type Cardinality,\n type ConformanceFinding,\n type ConformanceProfile,\n type ConformanceResult,\n type FieldRule,\n type FindingCode,\n type FindingLocus,\n type FindingSeverity,\n type SegmentRule,\n type UsageCode,\n} from \"./conformance/types.js\";\nexport * as conformance from \"./conformance/index.js\";\n\n// Roadmap Phase S: streaming / incremental parse. `parseStream` consumes a\n// chunked byte/string source (a Node `Readable`, an async-iterable, or an\n// iterable of chunks) and yields one message per MSH-delimited boundary with\n// O(one-message) memory: reassembling messages split across chunk boundaries,\n// isolating a malformed message (typed failure entry) without dropping the tail,\n// and reusing `parseHL7` for each message (no second grammar). Batch-envelope\n// segments are boundaries, never yielded, so yielded count == MSH count. The\n// additive `UNTERMINATED_STREAM_MESSAGE` warning surfaces a truncated final\n// message on the entry's `streamWarnings` (never on `Hl7Message.warnings`).\nexport { parseStream } from \"./parser/stream.js\";\nexport type { Hl7StreamSource, StreamMessageEntry } from \"./parser/stream.js\";\nexport { unterminatedStreamMessage } from \"./parser/warnings.js\";\n"]}
|