@cosyte/cli 0.0.5 → 0.1.0
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 +416 -0
- package/README.md +111 -45
- package/dist/bin/cosyte-mcp.cjs +461 -106
- package/dist/bin/cosyte-mcp.cjs.map +1 -1
- package/dist/bin/cosyte-mcp.mjs +461 -106
- package/dist/bin/cosyte-mcp.mjs.map +1 -1
- package/dist/bin/cosyte.cjs +824 -140
- package/dist/bin/cosyte.cjs.map +1 -1
- package/dist/bin/cosyte.mjs +825 -141
- package/dist/bin/cosyte.mjs.map +1 -1
- package/dist/index.cjs +592 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +515 -281
- package/dist/index.d.ts +515 -281
- package/dist/index.mjs +574 -104
- package/dist/index.mjs.map +1 -1
- package/dist/io-C9bSG2zF.d.cts +381 -0
- package/dist/io-C9bSG2zF.d.ts +381 -0
- package/dist/mcp.cjs +435 -103
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +70 -9
- package/dist/mcp.d.ts +70 -9
- package/dist/mcp.mjs +435 -103
- package/dist/mcp.mjs.map +1 -1
- package/package.json +61 -37
- package/dist/io-B2EobRzC.d.cts +0 -57
- package/dist/io-B2EobRzC.d.ts +0 -57
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/version.ts","../src/core/exit-codes.ts","../src/core/diagnostics.ts","../src/core/format.ts","../src/core/findings.ts","../src/core/parsers.ts","../src/core/input.ts","../src/core/phi.ts","../src/core/wrap.ts","../src/core/io.ts","../src/core/deid.ts","../src/commands/completion.ts","../src/commands/convert.ts","../src/commands/fmt.ts","../src/commands/inspect.ts","../src/commands/map-codes.ts","../src/commands/parse.ts","../src/commands/redact.ts","../src/commands/validate.ts","../src/core/run.ts"],"names":["ERROR_SEVERITIES","parseArgs"],"mappings":";;;;AAyBO,IAAM,OAAA,GAAkB;;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M,IAAA,EAAM,OAAO,CAAA;AAAA,MACjD,KAAK,KAAA;AACH,QAAA,OAAO,MAAM,UAAA,CAAW,IAAA,EAAM,IAAA,EAAM,OAAO,CAAA;AAAA,MAC7C,KAAK,SAAA;AACH,QAAA,OAAO,MAAM,cAAA,CAAe,IAAA,EAAM,IAAA,EAAM,OAAO,CAAA;AAAA,MACjD,KAAK,WAAA;AACH,QAAA,OAAO,MAAM,eAAA,CAAgB,IAAA,EAAM,IAAI,CAAA;AAAA,MACzC,KAAK,QAAA;AAAA,MACL,KAAK,MAAA;AACH,QAAA,OAAO,cAAc,IAAI,CAAA;AAAA,MAC3B,KAAK,YAAA;AACH,QAAA,OAAO,kBAAkB,IAAI,CAAA;AAAA,MAC/B;AACE,QAAA,OAAO,OAAA;AAAA,UACL,IAAI,QAAA;AAAA,YACF,SAAA,CAAU,SAAA;AAAA,YACV,IAAA,CAAK,KAAA;AAAA,YACL,oBAAoB,OAAO,CAAA,wBAAA;AAAA;AAC7B,SACF;AAAA;AACJ,EACF,SAAS,CAAA,EAAG;AACV,IAAA,OAAO,OAAA,CAAQ,UAAA,CAAW,CAAC,CAAC,CAAA;AAAA,EAC9B;AACF;AAGA,SAAS,QAAQ,CAAA,EAAwB;AACvC,EAAA,OAAO,EAAE,QAAQ,EAAA,EAAI,MAAA,EAAQ,WAAW,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,CAAA,CAAE,OAAO;AAAA,CAAA,EAAM,IAAA,EAAM,EAAE,IAAA,EAAK;AACjF","file":"index.mjs","sourcesContent":["/**\n * The CLI version string, synced with `package.json#version` on release by `scripts/sync-version.mjs`,\n * which the `version` script runs immediately after `changeset version`. Kept in its own module so\n * both the programmatic entry point and the dispatcher share one source of truth.\n *\n * The declaration below is rewritten by that script and is matched at column 0, annotation included.\n * Renaming it or reflowing it makes the script exit non-zero rather than silently no-op; the shape is\n * pinned by `test/sanity.test.ts`, and the value is compared against `package.json` there too.\n *\n * @packageDocumentation\n */\n\n/**\n * The `@cosyte/cli` version. On the uniform `v0.0.x-until-first-alpha` ladder.\n *\n * Read by `cosyte --version` and by the MCP server's advertised `SERVER_INFO`, so it is a\n * user-visible surface on both front doors, not merely an export.\n *\n * @example\n * ```ts\n * import { VERSION } from \"@cosyte/cli\";\n *\n * console.log(`cosyte ${VERSION}`);\n * ```\n */\nexport const VERSION: string = \"0.0.5\";\n","/**\n * The `cosyte` CLI **exit-code contract**: a designed, documented surface that CI pipelines and\n * shell scripts branch on. Grounded in the Unix `sysexits.h` conventions.\n *\n * The load-bearing rule: **the CLI never prints a reassuring line and exits `0` on input it could not\n * handle.** An undetectable format, an unreadable file, or a parser that throws each map to a\n * distinct, stable non-zero code, never a silent success.\n *\n * | Code | Name | Meaning |\n * |------|------------|----------------------------------------------------------------------|\n * | `0` | `OK` | success: the operation completed; `validate` found the input **valid** |\n * | `1` | `INVALID` | operation-level failure: `validate` found the input **invalid** (a real, expected CI signal: the message is bad, the tool worked) |\n * | `2` | `USAGE` | usage error: unknown command, bad flag, missing argument (EX_USAGE) |\n * | `65` | `DATAERR` | data error: input could not be parsed / format not detected (EX_DATAERR) |\n * | `66` | `NOINPUT` | no input: the file does not exist or is unreadable (EX_NOINPUT) |\n * | `69` | `UNAVAILABLE` | a required capability is not yet available: e.g. `redact` before `@cosyte/deid` is wired (EX_UNAVAILABLE) |\n * | `70` | `SOFTWARE` | internal error: an unexpected exception, i.e. a bug (EX_SOFTWARE) |\n *\n * The load-bearing `validate` rule: a **parseable-but-invalid** message is exit `1`, never exit `0`.\n * The CLI must never print a reassuring line and exit green on a bad message. Exit `65` is reserved\n * for input that could not be **parsed** at all (a distinct signal from \"parsed, but does not\n * conform\").\n *\n * @packageDocumentation\n */\n\n/**\n * The stable exit-code map. Adding a code is a documented, tested change to the CLI's contract;\n * renaming or repurposing one is a breaking change.\n *\n * @example\n * ```ts\n * import { EXIT } from \"@cosyte/cli\";\n *\n * process.exitCode = EXIT.OK; // => 0\n * ```\n */\nexport const EXIT = {\n /** Success: the operation completed; `validate` found the input **valid**. */\n OK: 0,\n /** Operation-level failure: `validate` found the input **invalid** (parseable but non-conformant):\n * a real, expected CI signal that the message is bad and the tool worked. Never emitted for\n * unparseable input (that is `DATAERR`). */\n INVALID: 1,\n /** Usage error: unknown command, bad flag, missing argument (`EX_USAGE`). */\n USAGE: 2,\n /** Data error: input could not be parsed or its format could not be detected (`EX_DATAERR`). */\n DATAERR: 65,\n /** No input: the named file does not exist or is unreadable (`EX_NOINPUT`). */\n NOINPUT: 66,\n /** Unavailable: a required capability is not yet wired (e.g. `redact` before `@cosyte/deid`), a\n * distinct non-zero signal that is never a fake success (`EX_UNAVAILABLE`). */\n UNAVAILABLE: 69,\n /** Internal error: an unexpected exception (a bug), distinct from a handled bad input (`EX_SOFTWARE`). */\n SOFTWARE: 70,\n} as const;\n\n/**\n * A value from {@link EXIT}: the exit code a CLI invocation resolves to.\n */\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n","/**\n * The CLI's **value-free diagnostic channel**. Every error the CLI raises on its own behalf carries a\n * stable `CLI_*` code, a fixed exit code, and a **PHI-safe** message built only from positional /\n * structural context: a segment or field index, a byte offset, a file path, a format name, a warning\n * code. **A diagnostic never echoes an input value** (a name, a DOB, an MRN, a result). This is the\n * parsers' \"warning = code + position, never a value\" rule applied at the CLI edge.\n *\n * @packageDocumentation\n */\n\nimport { EXIT, type ExitCode } from \"./exit-codes.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Stable **CLI diagnostic code** registry: errors the CLI owns (routing, I/O, argument handling),\n * distinct from the wrapped library's own warning/issue codes which are passed through unchanged.\n * Each code is its own value (`key === value`) so the set survives `Object.values(...)`; renaming or\n * removing one is a **breaking change** because scripts branch on the stderr text.\n *\n * @example\n * ```ts\n * import { CLI_CODES } from \"@cosyte/cli\";\n *\n * if (diagnostic.code === CLI_CODES.CLI_FORMAT_UNDETECTED) {\n * // ask the user for --format\n * }\n * ```\n */\nexport const CLI_CODES = {\n /** A required argument was missing or a flag was invalid. Exit `2`. */\n CLI_USAGE: \"CLI_USAGE\",\n /** The named file does not exist or could not be read. Exit `66`. */\n CLI_NO_INPUT: \"CLI_NO_INPUT\",\n /** The input was empty, no bytes to detect or parse. Exit `65`. */\n CLI_EMPTY_INPUT: \"CLI_EMPTY_INPUT\",\n /** No format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_UNDETECTED: \"CLI_FORMAT_UNDETECTED\",\n /** More than one format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_AMBIGUOUS: \"CLI_FORMAT_AMBIGUOUS\",\n /** A recognised format whose parser does not support the requested operation (e.g. `parse` on a\n * format wired only for `inspect`). Names the format + operation, never the bytes. Exit `65`. */\n CLI_FORMAT_UNSUPPORTED: \"CLI_FORMAT_UNSUPPORTED\",\n /** The optional parser package for a recognised format is not installed. The six breadth parsers\n * (dicom/x12/ccda/ncpdp/astm/mllp) are `optionalDependencies`: normally installed, but if\n * one is absent the CLI degrades to this value-free signal rather than crashing. Exit `69`. */\n CLI_PARSER_UNAVAILABLE: \"CLI_PARSER_UNAVAILABLE\",\n /** The wrapped parser rejected the input. Positional context only, never the offending bytes. Exit `65`. */\n CLI_PARSE_FAILED: \"CLI_PARSE_FAILED\",\n /** The BYO ConceptMap supplied to `map-codes` is not valid JSON or not a loadable FHIR ConceptMap.\n * Names the stable terminology-loader code, never the map's bytes. Exit `65`. */\n CLI_MAP_INVALID: \"CLI_MAP_INVALID\",\n /** A command whose ground-layer library is not yet wired (e.g. `redact` before `@cosyte/deid` is\n * wired). Never a fake success: a distinct, value-free \"unavailable\" signal. Exit `69`. */\n CLI_NOT_IMPLEMENTED: \"CLI_NOT_IMPLEMENTED\",\n /** An unexpected internal error (a bug). Exit `70`. */\n CLI_INTERNAL: \"CLI_INTERNAL\",\n} as const;\n\n/**\n * A value from {@link CLI_CODES}: the stable code carried by a {@link CliError}.\n */\nexport type CliCode = (typeof CLI_CODES)[keyof typeof CLI_CODES];\n\n/**\n * A typed, PHI-safe CLI error. Its {@link CliError.message | message} is **value-free by\n * construction**: callers must build it from codes, indices, offsets, format names, and file paths,\n * never from an input value. It carries the {@link ExitCode} the invocation resolves to.\n *\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT } from \"@cosyte/cli\";\n *\n * throw new CliError(CLI_CODES.CLI_NO_INPUT, EXIT.NOINPUT, \"cannot read the named file\");\n * ```\n */\nexport class CliError extends Error {\n /** The stable diagnostic code. */\n public readonly code: CliCode;\n /** The exit code this error resolves the invocation to. */\n public readonly exit: ExitCode;\n\n /**\n * @param code - A stable {@link CliCode}.\n * @param exit - The {@link ExitCode} to resolve to.\n * @param message - A **value-free** explanation (positional/structural context only, never PHI).\n */\n public constructor(code: CliCode, exit: ExitCode, message: string) {\n super(message);\n this.name = \"CliError\";\n this.code = code;\n this.exit = exit;\n }\n}\n\n/**\n * Render a {@link CliError} as a single value-free `stderr` line: `cosyte: <CODE>: <message>`. The\n * message is already value-free by the {@link CliError} contract; this only prefixes the tool name\n * and the code so scripts and humans can branch on a stable token.\n *\n * @param err - The CLI error to render.\n * @returns The stderr line (no trailing newline).\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, formatDiagnostic } from \"@cosyte/cli\";\n *\n * formatDiagnostic(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file> argument\"));\n * // => \"cosyte: CLI_USAGE: missing <file> argument\"\n * ```\n */\nexport function formatDiagnostic(err: CliError): string {\n return `cosyte: ${err.code}: ${err.message}`;\n}\n\n/**\n * Resolve a {@link CliError} into a value-free {@link RunResult}: empty `stdout` (nothing reaches the\n * data channel on an error), the rendered diagnostic on `stderr`, and the error's exit code. The\n * single place the CLI turns an owned error into a result, so every command and the dispatcher render\n * errors identically.\n *\n * @param err - The CLI error to resolve.\n * @returns The value-free {@link RunResult}.\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, errorResult } from \"@cosyte/cli\";\n *\n * errorResult(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file>\")).exit; // => 2\n * ```\n */\nexport function errorResult(err: CliError): RunResult {\n return { stdout: \"\", stderr: `${formatDiagnostic(err)}\\n`, exit: err.exit };\n}\n\n/**\n * Coerce an unknown thrown value into a {@link CliError}. A {@link CliError} passes through; anything\n * else becomes a `CLI_INTERNAL` / {@link EXIT.SOFTWARE} error whose message is a **fixed, value-free\n * string**: the original message is deliberately discarded so a parser exception that embedded input\n * bytes can never reach stderr.\n *\n * @param err - The caught value.\n * @returns A {@link CliError} safe to render to stderr.\n * @example\n * ```ts\n * import { toCliError } from \"@cosyte/cli\";\n *\n * toCliError(new Error(\"boom\")).code; // => \"CLI_INTERNAL\"\n * ```\n */\nexport function toCliError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n return new CliError(\n CLI_CODES.CLI_INTERNAL,\n EXIT.SOFTWARE,\n \"an unexpected internal error occurred (no input is echoed)\",\n );\n}\n","/**\n * **Content-based format autodetection**: the feature that makes `cosyte parse <file>` feel magic,\n * and the one that must **fail safe**. Detection sniffs the leading bytes' *content*, never the file\n * extension: a `.txt` full of `MSH|^~\\&…` is HL7; a `.json` with a `resourceType` is FHIR.\n *\n * The hazard is a wrong sniff routing bytes to the wrong parser and yielding confident garbage. So\n * detection is **conservative**: a single confident signature match parses; **zero or more than one**\n * match is *not* a guess. It is a typed `none`/`ambiguous` result the caller turns into a data-error\n * exit asking for `--format`. This is the parsers' \"never a confident wrong value\" rule at the\n * routing layer.\n *\n * All eight cosyte formats carry a signature: **hl7** (`MSH` + field separator), **mllp**\n * (a leading `0x0B` VT frame byte: an MLLP-framed stream, de-framed to its enclosed HL7), **fhir** (a\n * JSON object declaring `resourceType`), **x12** (a leading `ISA` interchange header), **astm** (a\n * leading `H` record whose second byte is the field delimiter), **ccda** (a `<ClinicalDocument>` root),\n * **ncpdp** (a `<Message>` root in the NCPDP SCRIPT namespace), and **dicom** (the `DICM` magic at byte\n * 128). The signatures are **conservative and, on realistic inputs, mutually exclusive**: the\n * distinctive-lead formats (`MSH`, `ISA`, `H`+delimiter, `<ClinicalDocument>`, `<Message>`+ncpdp, the\n * `DICM` magic, `0x0B` VT, `{…\"resourceType\"`) don't overlap on a real message of any one type. They\n * are **not** disjoint in the absolute sense: a pathological input could satisfy two (an MLLP frame\n * enclosing a `<ClinicalDocument>` payload matches both `mllp` and `ccda`; a text file whose byte 128\n * is `DICM` matches both), which is exactly why the **`ambiguous` branch is load-bearing, not dead\n * code**: any co-match is a *detected* ambiguity (a value-free data error asking for `--format`),\n * **never a silent mis-route**.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\n\n/** The set of formats the `cosyte` command names. */\nexport type CosyteFormat = \"hl7\" | \"fhir\" | \"dicom\" | \"x12\" | \"ccda\" | \"ncpdp\" | \"astm\" | \"mllp\";\n\n/**\n * How confident autodetection is:\n * - `certain`: exactly one signature matched (`format` names it);\n * - `ambiguous`: more than one matched (`format` is `null`; `candidates` names them);\n * - `none`: nothing matched (`format` is `null`; `candidates` is empty).\n *\n * `format` is `null` unless `confidence` is `certain`, so a non-certain result can never be mistaken\n * for a routable format.\n */\nexport interface DetectResult {\n /** The detected format, or `null` when `confidence` is not `certain`. */\n readonly format: CosyteFormat | null;\n /** The detection confidence. */\n readonly confidence: \"certain\" | \"ambiguous\" | \"none\";\n /** The matching candidate formats (0 for `none`, 1 for `certain`, ≥2 for `ambiguous`). Value-free. */\n readonly candidates: readonly CosyteFormat[];\n}\n\n/** A single format signature: a value-free predicate over the input's decoded prefix + raw bytes. */\ninterface Signature {\n readonly format: CosyteFormat;\n readonly match: (prefix: string, bytes: Uint8Array) => boolean;\n}\n\n/** How many leading bytes to decode for text sniffing. Small: signatures live in the first line. */\nconst SNIFF_BYTES = 512;\n\n/** Strip a leading UTF-8 BOM and any leading ASCII whitespace for a tolerant sniff. Deliberately does\n * **not** strip the MLLP `0x0B` VT frame byte (`\\v`): that byte is the mllp signature, so consuming it\n * here would collide the hl7 and mllp signatures on a framed message. */\nfunction leadingText(bytes: Uint8Array): string {\n const slice = bytes.subarray(0, SNIFF_BYTES);\n let text = new TextDecoder(\"utf-8\", { fatal: false }).decode(slice);\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\n return text;\n}\n\n/** Trim only regular leading whitespace (space/tab/CR/LF/FF), never the `0x0B` VT MLLP frame byte. */\nfunction trimLeading(prefix: string): string {\n return prefix.replace(/^[ \\t\\r\\n\\f]+/, \"\");\n}\n\n/** True iff `ch` is a single printable, non-alphanumeric byte usable as a wire delimiter (e.g. `|`, `*`). */\nfunction isDelimiter(ch: string | undefined): boolean {\n if (ch === undefined) return false;\n const code = ch.charCodeAt(0);\n return code > 0x20 && code < 0x7f && !/[A-Za-z0-9]/.test(ch);\n}\n\n/**\n * HL7 v2: the message begins with an `MSH` segment whose 4th character is the field separator\n * (conventionally `|`) followed by the encoding characters. Conservative: requires `MSH` + a\n * non-alphanumeric single-char field separator. An MLLP-framed message (leading `0x0B`) is **not**\n * claimed here (it is the `mllp` signature) because {@link trimLeading} preserves the VT byte.\n */\nfunction looksLikeHl7(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"MSH\") && isDelimiter(s[3]);\n}\n\n/**\n * MLLP: a Minimal Lower Layer Protocol frame opens with the `0x0B` VT byte. This is a **transport\n * framing**, not a document format: the CLI de-frames it and parses the enclosed HL7 v2 payload(s).\n * The check is on the **raw first byte**, so it is disjoint from every text signature.\n */\nfunction looksLikeMllp(_prefix: string, bytes: Uint8Array): boolean {\n return bytes[0] === 0x0b;\n}\n\n/**\n * FHIR: a JSON object whose first non-whitespace byte is `{` and which declares a string-valued\n * top-level `resourceType` member near the top. Conservative: both the object framing and the\n * `resourceType` key must be present, so a bare JSON object without it is not claimed as FHIR.\n */\nfunction looksLikeFhir(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"{\")) return false;\n return /\"resourceType\"\\s*:\\s*\"/.test(s);\n}\n\n/**\n * X12 EDI: an interchange opens with the fixed 3-byte `ISA` segment id immediately followed by the\n * element separator (a non-alphanumeric byte: `*` conventionally, but delimiter-agnostic).\n */\nfunction looksLikeX12(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"ISA\") && isDelimiter(s[3]);\n}\n\n/**\n * ASTM E1394/E1381 records: the first record is an `H` (header) whose second byte is the field\n * delimiter and whose next three bytes are the repeat / component / escape **delimiter declarations**\n * (all punctuation: classically `\\^&`). Requiring the full 4-delimiter block, not just `H` + one\n * delimiter, keeps a mundane `H:...`/`H!...` text line from being confidently mis-routed to ASTM (it\n * would instead be a value-free `CLI_FORMAT_UNDETECTED`). Distinct from HL7 (`MSH`) and X12 (`ISA`).\n */\nfunction looksLikeAstm(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"H\") || s.length < 5) return false;\n // s[1] = field delimiter; s[2..4] = the repeat/component/escape delimiter declarations.\n return isDelimiter(s[1]) && isDelimiter(s[2]) && isDelimiter(s[3]) && isDelimiter(s[4]);\n}\n\n/** C-CDA: an HL7 v3 CDA document rooted at `<ClinicalDocument>` (XML). */\nfunction looksLikeCcda(prefix: string): boolean {\n return /<ClinicalDocument[\\s>]/.test(prefix);\n}\n\n/**\n * NCPDP SCRIPT: an ePrescribing message rooted at `<Message>` in the NCPDP SCRIPT namespace.\n * Requires **both** the `<Message>` root and the `ncpdp` namespace marker so a generic `<Message>`\n * XML is not mis-claimed (conservative: disjoint from C-CDA's `<ClinicalDocument>`).\n */\nfunction looksLikeNcpdp(prefix: string): boolean {\n return /<Message[\\s>]/.test(prefix) && /ncpdp/i.test(prefix);\n}\n\n/** DICOM Part 10: the `DICM` magic sits at byte offset 128, after the 128-byte preamble. */\nfunction looksLikeDicom(_prefix: string, bytes: Uint8Array): boolean {\n if (bytes.length < 132) return false;\n return (\n bytes[128] === 0x44 && bytes[129] === 0x49 && bytes[130] === 0x43 && bytes[131] === 0x4d // \"DICM\"\n );\n}\n\n/** The signature registry: disjoint by construction across all eight cosyte formats. */\nconst SIGNATURES: readonly Signature[] = [\n { format: \"hl7\", match: (prefix) => looksLikeHl7(prefix) },\n { format: \"mllp\", match: (prefix, bytes) => looksLikeMllp(prefix, bytes) },\n { format: \"fhir\", match: (prefix) => looksLikeFhir(prefix) },\n { format: \"x12\", match: (prefix) => looksLikeX12(prefix) },\n { format: \"astm\", match: (prefix) => looksLikeAstm(prefix) },\n { format: \"ccda\", match: (prefix) => looksLikeCcda(prefix) },\n { format: \"ncpdp\", match: (prefix) => looksLikeNcpdp(prefix) },\n { format: \"dicom\", match: (prefix, bytes) => looksLikeDicom(prefix, bytes) },\n];\n\n/** The formats content-autodetection can recognise (every format now carries a signature). */\nexport const DETECTABLE_FORMATS: readonly CosyteFormat[] = SIGNATURES.map((s) => s.format);\n\n/**\n * Detect the healthcare format of `bytes` by content, conservatively.\n *\n * @param bytes - The input bytes (a whole file or a stdin buffer). Only the leading prefix is sniffed.\n * @returns A {@link DetectResult}: `certain` + a `format` on a single match, else `ambiguous`/`none`\n * with `format: null` and the value-free `candidates` list. **Never guesses.**\n * @example\n * ```ts\n * import { detectFormat } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * detectFormat(enc.encode(\"MSH|^~\\\\&|A|B\\r\")).format; // => \"hl7\"\n * detectFormat(enc.encode('{\"resourceType\":\"Patient\"}')).format; // => \"fhir\"\n * detectFormat(enc.encode(\"hello\")).confidence; // => \"none\"\n * ```\n */\nexport function detectFormat(bytes: Uint8Array): DetectResult {\n if (bytes.length === 0) return classifyCandidates([]);\n const prefix = leadingText(bytes);\n const candidates = SIGNATURES.filter((sig) => sig.match(prefix, bytes)).map((sig) => sig.format);\n return classifyCandidates(candidates);\n}\n\n/**\n * Classify a list of matched candidate formats into a {@link DetectResult}: exactly one → `certain`,\n * zero → `none`, two-or-more → `ambiguous` (all with `format` `null` unless certain). Split out and\n * exported so the **ambiguity** contract is directly testable. It is otherwise unreachable while\n * every signature is disjoint, and it must stay a *detected* ambiguity, never a mis-route.\n *\n * @param candidates - The formats whose signatures matched the input.\n * @returns The classified {@link DetectResult}.\n * @example\n * ```ts\n * import { classifyCandidates } from \"@cosyte/cli\";\n *\n * classifyCandidates([\"hl7\"]).confidence; // => \"certain\"\n * classifyCandidates([]).confidence; // => \"none\"\n * classifyCandidates([\"hl7\", \"fhir\"]).confidence; // => \"ambiguous\"\n * ```\n */\nexport function classifyCandidates(candidates: readonly CosyteFormat[]): DetectResult {\n const [first, second] = candidates;\n if (second !== undefined) return { format: null, confidence: \"ambiguous\", candidates };\n if (first !== undefined) return { format: first, confidence: \"certain\", candidates };\n return { format: null, confidence: \"none\", candidates: [] };\n}\n\n/**\n * Build the value-free {@link CliError} for a **non-certain** detection: the data error the caller\n * returns instead of guessing a parser. `ambiguous` names the matching candidates (a value-free code\n * list); `none` asks for `--format`. Both map to the data-error exit (`65`). Never echoes input bytes.\n *\n * @param detected - A {@link DetectResult} whose `format` is `null` (i.e. not `certain`).\n * @returns A value-free `CLI_FORMAT_AMBIGUOUS` or `CLI_FORMAT_UNDETECTED` error.\n * @example\n * ```ts\n * import { classifyCandidates, detectionError } from \"@cosyte/cli\";\n *\n * detectionError(classifyCandidates([])).code; // => \"CLI_FORMAT_UNDETECTED\"\n * detectionError(classifyCandidates([\"hl7\", \"fhir\"])).code; // => \"CLI_FORMAT_AMBIGUOUS\"\n * ```\n */\nexport function detectionError(detected: DetectResult): CliError {\n if (detected.confidence === \"ambiguous\") {\n return new CliError(\n CLI_CODES.CLI_FORMAT_AMBIGUOUS,\n EXIT.DATAERR,\n `input matched multiple formats (${detected.candidates.join(\", \")}); disambiguate with --format`,\n );\n }\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNDETECTED,\n EXIT.DATAERR,\n `could not detect the input format; re-run with --format (detectable: ${DETECTABLE_FORMATS.join(\", \")})`,\n );\n}\n\n/** The full set of format names `--format` accepts as syntactically valid (a bad value is a usage error). */\nexport const KNOWN_FORMATS: readonly CosyteFormat[] = [\n \"hl7\",\n \"fhir\",\n \"dicom\",\n \"x12\",\n \"ccda\",\n \"ncpdp\",\n \"astm\",\n \"mllp\",\n];\n\n/**\n * Narrow an arbitrary `--format` string to a {@link CosyteFormat}, or `null` if it is not a known\n * format name (which the caller turns into a usage error, exit `2`).\n *\n * @param value - The raw `--format` argument.\n * @returns The narrowed format, or `null`.\n * @example\n * ```ts\n * import { asCosyteFormat } from \"@cosyte/cli\";\n *\n * asCosyteFormat(\"hl7\"); // => \"hl7\"\n * asCosyteFormat(\"nope\"); // => null\n * ```\n */\nexport function asCosyteFormat(value: string): CosyteFormat | null {\n return (KNOWN_FORMATS as readonly string[]).includes(value) ? (value as CosyteFormat) : null;\n}\n","/**\n * The CLI's **value-free finding** shape and the positional locators that populate it. A finding says\n * *what kind* of thing was observed (a stable code + severity) and *where* (a positional locator),\n * **never** the offending value. Shared by `validate` (conformance findings) and\n * `inspect` (structural summary) so both render locations identically and value-free.\n *\n * @packageDocumentation\n */\n\n/**\n * A single value-free finding: a stable code, a severity, and a positional locator. Every field is\n * safe to print, log, or serialize. None carries a name, DOB, MRN, or field value.\n */\nexport interface Finding {\n /** The stable diagnostic/warning code (the wrapped library's or the CLI's). */\n readonly code: string;\n /** The R4-style severity (`fatal` | `error` | `warning` | `information`), or `warning` for HL7. */\n readonly severity: string;\n /** A value-free positional locator: a FHIRPath expression, or an HL7 segment/field index path. */\n readonly location: string;\n}\n\n/** The minimal, value-free positional shape shared by HL7 warnings (indices only, never a value). */\ninterface Hl7PositionLike {\n readonly segmentIndex: number;\n readonly fieldIndex?: number;\n readonly repetitionIndex?: number;\n readonly componentIndex?: number;\n readonly subcomponentIndex?: number;\n}\n\n/**\n * Render an HL7 warning position as a **value-free** locator string built only from its numeric\n * indices: e.g. `seg[3].field[5].comp[1]`. No segment content, no field value, ever appears; only the\n * structural coordinates the parser reported.\n *\n * @param pos - The HL7 position (segment/field/repetition/component/subcomponent indices).\n * @returns A value-free locator, e.g. `\"seg[3].field[5]\"`.\n * @example\n * ```ts\n * import { formatHl7Position } from \"@cosyte/cli\";\n *\n * formatHl7Position({ segmentIndex: 3, fieldIndex: 5 }); // => \"seg[3].field[5]\"\n * formatHl7Position({ segmentIndex: 0 }); // => \"seg[0]\"\n * ```\n */\nexport function formatHl7Position(pos: Hl7PositionLike): string {\n let out = `seg[${String(pos.segmentIndex)}]`;\n if (pos.fieldIndex !== undefined) out += `.field[${String(pos.fieldIndex)}]`;\n if (pos.repetitionIndex !== undefined) out += `.rep[${String(pos.repetitionIndex)}]`;\n if (pos.componentIndex !== undefined) out += `.comp[${String(pos.componentIndex)}]`;\n if (pos.subcomponentIndex !== undefined) out += `.sub[${String(pos.subcomponentIndex)}]`;\n return out;\n}\n","/**\n * The **per-format parser adapter registry**: the single place the CLI routes a resolved format to\n * its wrapped `@cosyte/*` parser, for each of the four wrapping operations (`parse` / `inspect` /\n * `fmt` / `validate`). One lazy, value-free registry, so the wrapper boundary lives in exactly one\n * file.\n *\n * **Capability is per (format, operation).** Not every parser faithfully supports every operation:\n * DICOM's model is binary (no faithful JSON `parse`, no text `fmt`), C-CDA's canonical form is XML (no\n * library-blessed JSON `parse`), MLLP is a transport container (de-framed to HL7, `parse`/`inspect`\n * only). {@link OP_SUPPORT} is the honest matrix; an unsupported (format, op) is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, **never** a faked result.\n *\n * **Lazy + optional.** Every parser is imported dynamically inside its branch, so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code. The six breadth parsers are `optionalDependencies`: if\n * one is absent the dynamic import is caught and degrades to a value-free `CLI_PARSER_UNAVAILABLE`\n * (exit `69`) rather than an unhandled crash: the CLI core still works with any of them missing.\n *\n * @packageDocumentation\n */\n\nimport type * as CosyteFhir from \"@cosyte/fhir\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport { formatHl7Position, type Finding } from \"./findings.js\";\nimport type { CosyteFormat } from \"./format.js\";\n\n/** The four wrapping operations a command can ask a format's adapter to perform. */\nexport type Op = \"parse\" | \"inspect\" | \"fmt\" | \"validate\";\n\n/** A value-free parse warning: a stable code plus the parser's positional (index-only) context. */\nexport type ParseWarning = { readonly code: string } & Readonly<Record<string, unknown>>;\n\n/** The result of wrapping a parser's `parse`: the library's parsed model + its value-free warnings. */\nexport interface ParseResult {\n /** The wrapped library's parsed model: emitted verbatim as JSON on the data channel. */\n readonly model: unknown;\n /** The parser's value-free warnings (code + position). */\n readonly warnings: readonly ParseWarning[];\n}\n\n/** The result of a canonical re-serialization (`fmt`): the spec-clean text + a value-free warning count. */\nexport interface FmtResult {\n /** The wrapped serializer's output text. */\n readonly output: string;\n /** How many parse warnings the round-trip surfaced (value-free count only). */\n readonly warningCount: number;\n}\n\n/** The verdict of running a format's validation surface: value-free findings + the validity boolean. */\nexport interface Verdict {\n /** The value-free findings (code + severity + positional locator). */\n readonly findings: readonly Finding[];\n /** `true` iff the input is valid (no error/fatal-severity finding). */\n readonly valid: boolean;\n}\n\n/* ── value-free structural summaries (one variant per format) ─────────────────────────────────── */\n\n/** Value-free structural summary of an HL7 v2 message. */\nexport interface Hl7Summary {\n readonly format: \"hl7\";\n readonly messageType: string | null;\n readonly version: string | null;\n readonly segmentCount: number;\n readonly segments: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a FHIR resource. */\nexport interface FhirSummary {\n readonly format: \"fhir\";\n readonly resourceType: string | null;\n readonly bundleType?: string | null;\n readonly entryCount?: number;\n readonly entryResourceTypes?: Readonly<Record<string, number>>;\n readonly issueCount: number;\n}\n\n/** Value-free structural summary of an X12 interchange (envelope counts + transaction-set ids). */\nexport interface X12Summary {\n readonly format: \"x12\";\n readonly groupCount: number;\n readonly transactionCount: number;\n /** Count of each transaction-set identifier code (ST-01), e.g. `{ \"834\": 1 }`: value-free codes. */\n readonly transactionSetIds: Readonly<Record<string, number>>;\n readonly segmentCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an ASTM record message. */\nexport interface AstmSummary {\n readonly format: \"astm\";\n /** The host-query classification kind (`results` | `orders` | `host-query` | `indeterminate`). */\n readonly messageKind: string;\n readonly recordCount: number;\n /** Count of each single-letter record type, e.g. `{ H: 1, P: 1, O: 2, R: 4, L: 1 }`. */\n readonly recordTypes: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a C-CDA document (document type + section LOINC codes). */\nexport interface CcdaSummary {\n readonly format: \"ccda\";\n readonly documentType: string | null;\n readonly sectionCount: number;\n /** The LOINC `code` of each top-level section (value-free classification codes). */\n readonly sectionCodes: readonly string[];\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a DICOM dataset (classification UIDs + element count). */\nexport interface DicomSummary {\n readonly format: \"dicom\";\n /** The SOP Class UID (a standard OID identifying the object type: value-free classification). */\n readonly sopClassUid: string | null;\n /** The Transfer Syntax UID (encoding classification: value-free). */\n readonly transferSyntaxUid: string | null;\n readonly elementCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an NCPDP SCRIPT message. */\nexport interface NcpdpSummary {\n readonly format: \"ncpdp\";\n readonly standard: \"SCRIPT\";\n /** The SCRIPT message type (e.g. `NewRx`, `CancelRx`: a value-free classification). */\n readonly messageType: string | null;\n /** The SCRIPT version (e.g. `2017071`: value-free). */\n readonly version: string | null;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an MLLP stream (frame count only; the payloads are HL7). */\nexport interface MllpSummary {\n readonly format: \"mllp\";\n readonly frameCount: number;\n readonly warningCount: number;\n}\n\n/** The discriminated value-free structural summary `inspect` renders. */\nexport type InspectSummary =\n | Hl7Summary\n | FhirSummary\n | X12Summary\n | AstmSummary\n | CcdaSummary\n | DicomSummary\n | NcpdpSummary\n | MllpSummary;\n\n/* ── the capability matrix ───────────────────────────────────────────────────────────────────── */\n\n/**\n * The honest per-format operation matrix. A (format, op) pair absent here is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, never a faked result. The unsupported cells and why:\n * - **dicom** `parse`/`fmt`. The model is binary (no faithful JSON view; `serializeDicom` emits a\n * Part-10 byte stream, not text). `inspect`/`validate` are supported.\n * - **ccda** `parse`: the canonical form is XML; there is no library-blessed JSON model, so `fmt`\n * (XML re-serialize) is the faithful surface. `inspect`/`fmt`/`validate` are supported.\n * - **mllp** `fmt`/`validate`: MLLP is a transport container the CLI de-frames to HL7; `parse` yields\n * the enclosed HL7 message(s) and `inspect` reports the frame count.\n *\n * @example\n * ```ts\n * import { OP_SUPPORT } from \"@cosyte/cli\";\n *\n * OP_SUPPORT.dicom.has(\"parse\"); // => false\n * OP_SUPPORT.hl7.has(\"validate\"); // => true\n * ```\n */\nexport const OP_SUPPORT: Readonly<Record<CosyteFormat, ReadonlySet<Op>>> = {\n hl7: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n fhir: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n x12: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n astm: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ncpdp: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ccda: new Set<Op>([\"inspect\", \"fmt\", \"validate\"]),\n dicom: new Set<Op>([\"inspect\", \"validate\"]),\n mllp: new Set<Op>([\"parse\", \"inspect\"]),\n};\n\n/**\n * True iff `format`'s wrapped parser supports `op` in this build (see {@link OP_SUPPORT}).\n *\n * @param format - The resolved format.\n * @param op - The wrapping operation.\n * @returns Whether the (format, op) pair is wired.\n * @example\n * ```ts\n * import { supportsOp } from \"@cosyte/cli\";\n *\n * supportsOp(\"x12\", \"fmt\"); // => true\n * supportsOp(\"dicom\", \"parse\"); // => false\n * ```\n */\nexport function supportsOp(format: CosyteFormat, op: Op): boolean {\n return OP_SUPPORT[format].has(op);\n}\n\n/**\n * The formats that support `op`, as a sorted, value-free list: used to build the \"does not support\"\n * diagnostic so the user is told which formats *do* support the operation they asked for.\n *\n * @param op - The wrapping operation.\n * @returns The supporting format names, sorted.\n * @example\n * ```ts\n * import { formatsSupporting } from \"@cosyte/cli\";\n *\n * formatsSupporting(\"fmt\"); // => [\"astm\", \"ccda\", \"fhir\", \"hl7\", \"ncpdp\", \"x12\"]\n * ```\n */\nexport function formatsSupporting(op: Op): readonly CosyteFormat[] {\n return (Object.keys(OP_SUPPORT) as CosyteFormat[]).filter((f) => OP_SUPPORT[f].has(op)).sort();\n}\n\n/* ── value-free helpers ──────────────────────────────────────────────────────────────────────── */\n\n/**\n * Render an arbitrary parser **position** object as a value-free locator string, keeping **only**\n * number-valued own properties (the parsers' positions are index-only): e.g. `{ segmentIndex: 3,\n * elementIndex: 2 }` → `segmentIndex[3].elementIndex[2]`. A non-number field (which a position should\n * never carry) is dropped, so a stray value can never reach a diagnostic. Falls back to `\"?\"` when no\n * numeric index is present.\n *\n * @param pos - A parser position object (index-only by the parser's contract).\n * @returns A value-free locator built solely from numeric indices.\n * @example\n * ```ts\n * import { valueFreeLocator } from \"@cosyte/cli\";\n *\n * valueFreeLocator({ segmentIndex: 3, elementIndex: 2 }); // => \"segmentIndex[3].elementIndex[2]\"\n * valueFreeLocator({}); // => \"?\"\n * ```\n */\nexport function valueFreeLocator(pos: unknown): string {\n if (typeof pos !== \"object\" || pos === null) return \"?\";\n const parts: string[] = [];\n for (const [k, v] of Object.entries(pos)) {\n if (typeof v === \"number\") parts.push(`${k}[${String(v)}]`);\n }\n return parts.length > 0 ? parts.join(\".\") : \"?\";\n}\n\n/** Severities that make an input **invalid** (exit `1`). Recovered warnings never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** Whether any finding is error/fatal severity (i.e. the input is invalid). */\nfunction anyError(findings: readonly Finding[]): boolean {\n return findings.some((f) => ERROR_SEVERITIES.has(f.severity));\n}\n\n/**\n * Lazy-import an **optional** parser package, mapping an *absent* package to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`): the graceful-degradation path for the `optionalDependencies`\n * breadth parsers. A genuine import that succeeds passes straight through; any error whose\n * shape is \"module not found\" becomes the value-free CLI error. Other errors propagate unchanged.\n *\n * @template T - The imported module's type.\n * @param format - The format whose optional parser is being loaded (named in the diagnostic).\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptional } from \"@cosyte/cli\";\n *\n * // a present parser resolves; an absent one throws CLI_PARSER_UNAVAILABLE\n * await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n * ```\n */\nexport async function loadOptional<T>(format: CosyteFormat, load: () => Promise<T>): Promise<T> {\n return loadOptionalPackage(\n `the @cosyte/${format} parser is not installed; install it to use this format ` +\n `(it is an optional dependency)`,\n load,\n );\n}\n\n/**\n * The same graceful-degradation path as {@link loadOptional}, keyed on a **package name** rather than\n * a {@link CosyteFormat}, with the diagnostic supplied by the caller.\n *\n * Two of the packages the CLI lazy-loads are not wire-format parsers and so cannot go through\n * {@link loadOptional}: `@cosyte/transform` (a conversion library, not one of the eight formats, so\n * calling it a \"parser\" in the diagnostic would be wrong) and `@cosyte/fhir` (a format, but absent for\n * a reason no reinstall fixes, which the message has to say). Both are reachable from a published\n * install only if the user already has them, so both must degrade to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`) instead of surfacing a raw resolver error and a stack frame.\n *\n * @template T - The imported module's type.\n * @param detail - The value-free diagnostic detail shown when the package is absent.\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptionalPackage } from \"@cosyte/cli\";\n *\n * await loadOptionalPackage(\"the conversion library is not installed\", () =>\n * import(\"@cosyte/transform\"),\n * );\n * ```\n */\nexport async function loadOptionalPackage<T>(detail: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (e) {\n if (isModuleNotFound(e)) {\n throw new CliError(CLI_CODES.CLI_PARSER_UNAVAILABLE, EXIT.UNAVAILABLE, detail);\n }\n throw e;\n }\n}\n\n/**\n * Why `@cosyte/fhir` is absent, in the words a user can act on. It is not on the npm registry, so it\n * cannot be a declared dependency of this package at all, and no reinstall of `@cosyte/cli` will\n * produce it. Value-free by construction: a package name and a statement of fact, no input echoed.\n */\nconst FHIR_UNAVAILABLE =\n \"the @cosyte/fhir parser is not installed, and it is not currently on the npm registry, \" +\n \"so it cannot be installed from there; FHIR support is unavailable in this install\";\n\n/**\n * Load `@cosyte/fhir`, degrading to a value-free `CLI_PARSER_UNAVAILABLE` when it is absent.\n *\n * Every FHIR branch in this file and the `convert` command go through here, so there is exactly one\n * place that decides what an absent FHIR library does. It is deliberately not re-exported from the\n * package entry point: consumers get {@link loadOptionalPackage}, not this repo's own wiring.\n *\n * @returns The `@cosyte/fhir` module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent.\n * @example\n * ```ts\n * const { parseResource } = await loadFhir();\n * ```\n */\nexport async function loadFhir(): Promise<typeof CosyteFhir> {\n return loadOptionalPackage(FHIR_UNAVAILABLE, () => import(\"@cosyte/fhir\"));\n}\n\n/** True iff `e` is a \"module not found\" failure, by Node's `code`, or the standard resolver message. */\nfunction isModuleNotFound(e: unknown): boolean {\n if (typeof e !== \"object\" || e === null) return false;\n const code = \"code\" in e ? e.code : undefined;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") return true;\n const message = \"message\" in e && typeof e.message === \"string\" ? e.message : \"\";\n return /Cannot find (package|module)|Failed to (load|resolve)/i.test(message);\n}\n\n/* ── parse ───────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Parse one record of `format` into the wrapped library's model + its value-free warnings. The model\n * is emitted verbatim on the data channel; the CLI adds no parsing of its own.\n *\n * @param format - A format for which `supportsOp(format, \"parse\")` is true.\n * @param bytes - The single record's bytes (already de-framed for MLLP: callers pass `\"hl7\"` there).\n * @returns The parsed model + value-free warnings.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * own rejection propagates for the command's value-free failure boundary to catch.\n * @example\n * ```ts\n * import { parseFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}');\n * (await parseFormat(\"fhir\", bytes)).warnings.length; // => 0\n * ```\n */\nexport async function parseFormat(format: CosyteFormat, bytes: Uint8Array): Promise<ParseResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return {\n model: msg.toJSON(),\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const text = decode(bytes);\n const { resource, issues } = parseResource(text);\n const model: unknown = JSON.parse(serializeResource(resource));\n return {\n model,\n warnings: issues.map((i) => ({\n code: i.code,\n severity: i.severity,\n expression: i.expression,\n })),\n };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return {\n model: ix,\n warnings: ix.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"dicom\":\n case \"ccda\":\n case \"mllp\":\n // Guarded upstream by supportsOp; a direct call for an unsupported (format, op) is value-free.\n throw unsupportedInternal(format, \"parse\");\n }\n}\n\n/* ── inspect ─────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Build the value-free structural summary of one input of `format`: counts and structural type codes\n * only, never a field value.\n *\n * @param format - A format for which `supportsOp(format, \"inspect\")` is true.\n * @param bytes - The input bytes.\n * @returns A {@link InspectSummary} variant for the format.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary.\n * @example\n * ```ts\n * import { inspectFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\"}');\n * (await inspectFormat(\"fhir\", bytes)).format; // => \"fhir\"\n * ```\n */\nexport async function inspectFormat(\n format: CosyteFormat,\n bytes: Uint8Array,\n): Promise<InspectSummary> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const segments: Record<string, number> = {};\n const all = msg.allSegments();\n for (const seg of all) segments[seg.type] = (segments[seg.type] ?? 0) + 1;\n return {\n format: \"hl7\",\n messageType: msg.meta.type ?? null,\n version: msg.meta.version ?? null,\n segmentCount: all.length,\n segments,\n warningCount: msg.warnings.length,\n };\n }\n case \"fhir\": {\n const { parseResource, resourceType, readBundle } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const rt = resourceType(resource) ?? null;\n if (rt === \"Bundle\") {\n const bundle = readBundle(resource);\n const entryResourceTypes: Record<string, number> = {};\n for (const e of bundle.entries) {\n const t = e.resourceType ?? \"(none)\";\n entryResourceTypes[t] = (entryResourceTypes[t] ?? 0) + 1;\n }\n return {\n format: \"fhir\",\n resourceType: rt,\n bundleType: bundle.type ?? null,\n entryCount: bundle.entries.length,\n entryResourceTypes,\n issueCount: issues.length,\n };\n }\n return { format: \"fhir\", resourceType: rt, issueCount: issues.length };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const transactionSetIds: Record<string, number> = {};\n let transactionCount = 0;\n let segmentCount = 0;\n for (const g of ix.groups) {\n for (const t of g.transactions) {\n transactionCount += 1;\n segmentCount += t.segments.length;\n const id = t.st.elements[1] ?? \"(unknown)\";\n transactionSetIds[id] = (transactionSetIds[id] ?? 0) + 1;\n }\n }\n return {\n format: \"x12\",\n groupCount: ix.groups.length,\n transactionCount,\n transactionSetIds,\n segmentCount,\n warningCount: ix.warnings.length,\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const recordTypes: Record<string, number> = {};\n for (const r of msg.records) recordTypes[r.type] = (recordTypes[r.type] ?? 0) + 1;\n return {\n format: \"astm\",\n messageKind: msg.classification.kind,\n recordCount: msg.records.length,\n recordTypes,\n warningCount: msg.warnings.length,\n };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const sectionCodes: string[] = [];\n for (const s of doc.sections) {\n const code = s.code?.code;\n if (typeof code === \"string\") sectionCodes.push(code);\n }\n return {\n format: \"ccda\",\n documentType: doc.documentType ?? null,\n sectionCount: doc.sections.length,\n sectionCodes,\n warningCount: doc.warnings.length,\n };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n let warningCount = 0;\n const ds = parseDicom(Buffer.from(bytes), { onWarning: () => (warningCount += 1) });\n return {\n format: \"dicom\",\n sopClassUid: ds.fileMeta?.mediaStorageSOPClassUID ?? null,\n transferSyntaxUid: ds.fileMeta?.transferSyntaxUID ?? null,\n elementCount: ds.elements().length,\n warningCount,\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n format: \"ncpdp\",\n standard: \"SCRIPT\",\n messageType: msg.body.kind ?? null,\n version: msg.header.version ?? null,\n warningCount: msg.warnings.length,\n };\n }\n case \"mllp\": {\n const { payloads, warningCount } = await deframeMllp(bytes);\n return { format: \"mllp\", frameCount: payloads.length, warningCount };\n }\n }\n}\n\n/* ── fmt ─────────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Canonically re-serialize one input of `format` via the wrapped library's spec-clean serializer. The\n * CLI never re-canonicalizes on its own; the output is exactly the serializer's.\n *\n * @param format - A format for which `supportsOp(format, \"fmt\")` is true.\n * @param bytes - The input bytes.\n * @returns The serialized text + a value-free warning count.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary (no partial emit).\n * @example\n * ```ts\n * import { fmtFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{ \"resourceType\":\"Patient\" , \"id\":\"x\" }');\n * (await fmtFormat(\"fhir\", bytes)).output.startsWith(\"{\"); // => true\n * ```\n */\nexport async function fmtFormat(format: CosyteFormat, bytes: Uint8Array): Promise<FmtResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return { output: msg.toString(), warningCount: msg.warnings.length };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n return { output: serializeResource(resource), warningCount: issues.length };\n }\n case \"x12\": {\n const { parseX12, serializeX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return { output: serializeX12(ix), warningCount: ix.warnings.length };\n }\n case \"astm\": {\n const { parseAstmRecords, serializeAstmRecords } = await loadOptional(\n \"astm\",\n () => import(\"@cosyte/astm\"),\n );\n const msg = parseAstmRecords(decode(bytes));\n return { output: serializeAstmRecords(msg), warningCount: msg.warnings.length };\n }\n case \"ccda\": {\n const { parseCcda, serializeCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n return { output: serializeCcda(doc), warningCount: doc.warnings.length };\n }\n case \"ncpdp\": {\n const { parseScript, serializeScript } = await loadOptional(\n \"ncpdp\",\n () => import(\"@cosyte/ncpdp\"),\n );\n const msg = parseScript(decode(bytes));\n return { output: serializeScript(msg), warningCount: msg.warnings.length };\n }\n case \"dicom\":\n case \"mllp\":\n throw unsupportedInternal(format, \"fmt\");\n }\n}\n\n/* ── validate ────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Run the format's validation surface and return a value-free {@link Verdict}. For the Postel's-Law\n * lenient parsers, a **parseable** input is valid: recovered deviations are non-fatal warnings the\n * library surfaces, never a stricter verdict the CLI invents. FHIR additionally runs `validateResource`\n * and is invalid on any error/fatal-severity issue.\n *\n * @param format - A format for which `supportsOp(format, \"validate\")` is true.\n * @param bytes - The input bytes.\n * @returns The value-free verdict (findings + validity).\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; an unparseable input\n * propagates as the wrapped parser's throw for the command to map to a data error (`65`).\n * @example\n * ```ts\n * import { validateFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}');\n * (await validateFormat(\"fhir\", bytes)).valid; // => true\n * ```\n */\nexport async function validateFormat(format: CosyteFormat, bytes: Uint8Array): Promise<Verdict> {\n switch (format) {\n case \"fhir\": {\n const { parseResource, validateResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const validation = validateResource(resource);\n const findings: Finding[] = [\n ...issues.map((i) => finding(i.code, i.severity, i.expression)),\n ...validation.issues.map((i) => finding(i.code, i.severity, i.expression, i.constraint)),\n ];\n return { findings, valid: !anyError(findings) };\n }\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", formatHl7Position(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const findings = ix.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const findings = doc.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n const findings: Finding[] = [];\n parseDicom(Buffer.from(bytes), {\n onWarning: (w) => findings.push(finding(w.code, \"warning\", valueFreeLocator(w.position))),\n });\n return { findings, valid: !anyError(findings) };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"mllp\":\n throw unsupportedInternal(format, \"validate\");\n }\n}\n\n/* ── MLLP de-framing (transport → HL7 payloads) ──────────────────────────────────────────────── */\n\n/**\n * De-frame an MLLP byte stream into its enclosed HL7 payloads via `@cosyte/mllp`'s `FrameReader`. MLLP\n * is a transport container, not a document format: each frame's payload is an HL7 v2 message the CLI\n * then parses/inspects with the `hl7` adapter. Multi-frame streams are the CLI's multi-message surface.\n *\n * @param bytes - The MLLP-framed input.\n * @returns The de-framed HL7 payloads (in stream order) + a value-free framing-warning count.\n * **Truncation is a data error, never a silent drop.** The `FrameReader` is a streaming decoder: an\n * unterminated trailing frame (a VT opened with no closing FS/CR) is left buffered and delivered by\n * *no* callback, so feeding a whole file and reading only `onFrame` would silently lose the partial\n * message with a green exit. We therefore detect an open trailing frame at the byte level (the last\n * VT sits after the last FS: MLLP payloads are HL7 v2 text and never carry the `0x0B`/`0x1C` framing\n * bytes) and reject the whole stream as a value-free `CLI_PARSE_FAILED` data error.\n *\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if `@cosyte/mllp` is absent; `CLI_PARSE_FAILED` (exit\n * `65`) on a truncated stream; a hard framing error propagates for the caller's value-free boundary.\n * @example\n * ```ts\n * import { deframeMllp } from \"@cosyte/cli\";\n *\n * // a VT-framed \"MSH|...\" message → one payload\n * (await deframeMllp(new Uint8Array([0x0b, 0x4d, 0x53, 0x48, 0x1c, 0x0d]))).payloads.length; // => 1\n * ```\n */\nexport async function deframeMllp(\n bytes: Uint8Array,\n): Promise<{ payloads: Buffer[]; warningCount: number }> {\n // Reject an unterminated trailing frame BEFORE de-framing: a VT after the last FS is an open frame\n // the streaming reader would buffer and silently drop. (MLLP payloads never contain 0x0B/0x1C.)\n if (bytes.lastIndexOf(0x0b) > bytes.lastIndexOf(0x1c)) {\n throw new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n \"truncated MLLP stream: an unterminated frame at the end of input (no closing FS/CR)\",\n );\n }\n const { FrameReader } = await loadOptional(\"mllp\", () => import(\"@cosyte/mllp\"));\n const payloads: Buffer[] = [];\n let warningCount = 0;\n const reader = new FrameReader({\n onFrame: (payload) => payloads.push(Buffer.from(payload)),\n onWarning: () => (warningCount += 1),\n });\n reader.push(Buffer.from(bytes));\n return { payloads, warningCount };\n}\n\n/* ── shared internals ────────────────────────────────────────────────────────────────────────── */\n\n/** Decode input bytes as tolerant UTF-8 (the text parsers accept a string). */\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n}\n\n/** Build one value-free {@link Finding}; a FHIR `constraint` (a public spec id) is appended if present. */\nfunction finding(code: string, severity: string, location: string, constraint?: string): Finding {\n const loc = constraint !== undefined ? `${location} (${constraint})` : location;\n return { code, severity, location: loc };\n}\n\n/** The value-free error for an internal (guarded-upstream) unsupported (format, op): a programming bug. */\nfunction unsupportedInternal(format: CosyteFormat, op: Op): CliError {\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\``,\n );\n}\n","/**\n * The shared **input + format resolution** every file-consuming command runs before it touches a\n * wrapped parser: resolve the `<file|->` argument, read its bytes (a file, or stdin for `-`), reject\n * empty input, then resolve the format: an explicit `--format` override (validated) or conservative\n * content autodetection, and confirm the format is actually wired in this build. Factored out of the\n * commands so `parse`/`validate`/`inspect`/`fmt` share one identical, value-free front door and the\n * exit-code contract is applied in exactly one place.\n *\n * Every failure is a value-free {@link CliError} rendered to a {@link RunResult}: a missing argument\n * is a usage error (`2`), an unreadable file a no-input error (`66`), empty/undetected/unwired input a\n * data error (`65`). None ever echoes an input byte.\n *\n * @packageDocumentation\n */\n\nimport { asCosyteFormat, detectFormat, detectionError, type CosyteFormat } from \"./format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { RunDeps } from \"./io.js\";\nimport { formatsSupporting, supportsOp, type Op } from \"./parsers.js\";\nimport type { RunResult } from \"./result.js\";\n\n/** A successfully-resolved input: the format (guaranteed to support the requested op) and the bytes. */\nexport interface ResolvedInput {\n /** The resolved format: guaranteed to satisfy `supportsOp(format, op)` for the requested op. */\n readonly format: CosyteFormat;\n /** The input bytes (a whole file or a drained stdin buffer); guaranteed non-empty. */\n readonly bytes: Uint8Array;\n}\n\n/**\n * The outcome of {@link resolveInput}: either the resolved input, or a ready-to-return value-free\n * {@link RunResult} carrying the diagnostic + exit code for whatever went wrong. A discriminated union\n * so a command reads `if (!r.ok) return r.result;` and then works with `r.input`.\n */\nexport type InputResolution =\n | { readonly ok: true; readonly input: ResolvedInput }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Resolve and read the input, and resolve its format, for a file-consuming command.\n *\n * @param source - The positional `<file|->` argument (or `undefined` when it was omitted).\n * @param formatOverride - The raw `--format` value, or `undefined` to autodetect by content.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param op - The wrapping operation the caller will run; the resolved format is confirmed to support\n * it (else a value-free `CLI_FORMAT_UNSUPPORTED` naming the supporting formats).\n * @returns `{ ok: true, input }` when the bytes read and the format resolved to a parser supporting\n * `op`; else `{ ok: false, result }` with a value-free usage/no-input/data-error {@link RunResult}.\n * @throws Propagates a **non-`CliError`** read failure unchanged, so the dispatcher maps it to\n * `CLI_INTERNAL` (a `CliError` read failure, e.g. a missing file, is caught and returned).\n * @example\n * ```ts\n * import { resolveInput } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await resolveInput(\"patient.json\", undefined, deps, \"parse\");\n * if (r.ok) r.input.format; // => \"fhir\"\n * ```\n */\nexport async function resolveInput(\n source: string | undefined,\n formatOverride: string | undefined,\n deps: RunDeps,\n op: Op,\n): Promise<InputResolution> {\n if (source === undefined) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <file> argument; pass a path or `-` to read stdin\",\n ),\n );\n }\n\n let bytes: Uint8Array;\n try {\n bytes = source === \"-\" ? await deps.readStdin() : await deps.readFile(source);\n } catch (e) {\n if (e instanceof CliError) return fail(e);\n throw e;\n }\n\n if (bytes.length === 0) {\n return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n // Resolve the format: an explicit --format override (validated), else content autodetection.\n let format: CosyteFormat;\n if (formatOverride !== undefined) {\n const narrowed = asCosyteFormat(formatOverride);\n if (narrowed === null) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"unknown --format value; expected one of hl7, fhir, dicom, x12, ccda, ncpdp, astm, mllp\",\n ),\n );\n }\n format = narrowed;\n } else {\n const detected = detectFormat(bytes);\n // `format` is non-null iff detection is `certain`; `none`/`ambiguous` become a value-free data error.\n if (detected.format === null) return fail(detectionError(detected));\n format = detected.format;\n }\n\n if (!supportsOp(format, op)) {\n return fail(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\` in this CLI build ` +\n `(${op} supports: ${formatsSupporting(op).join(\", \")})`,\n ),\n );\n }\n\n return { ok: true, input: { format, bytes } };\n}\n\n/** Wrap a {@link CliError} as a failed {@link InputResolution}. */\nfunction fail(e: CliError): InputResolution {\n return { ok: false, result: errorResult(e) };\n}\n","/**\n * The CLI's **global PHI display posture**: the single mechanism that gates whether *any* input\n * value may appear on a **secondary surface** (stderr, a diagnostic, a warning, a log line). The CLI\n * is **value-free by default**: every secondary surface carries only positional/structural context\n * (a stable code, a segment/field index, a byte offset, a file path, a format name), never a name, a\n * DOB, an MRN, or a field value. `stdout` is the **data channel** (the user's explicit request) and\n * is exempt: the posture governs everything *but* stdout.\n *\n * `--unsafe-show-values` is the **single, explicit, loud door** to a value on a secondary surface. It\n * is off by default, PHI-exposing by design, and its effect flows through exactly one chokepoint here\n * ({@link unsafeInputSuffix}) so the \"a value appears on a secondary surface **iff** the flag is set\"\n * property is provable in one place rather than scattered across commands.\n *\n * @packageDocumentation\n */\n\n/**\n * The resolved PHI display posture for one invocation. `showValues` is `true` **only** when the user\n * passed `--unsafe-show-values`; every value-echoing decision reads this one flag.\n */\nexport interface PhiPosture {\n /** `true` iff `--unsafe-show-values` was given: a value may appear on a secondary surface. */\n readonly showValues: boolean;\n}\n\n/** The default, safe posture: no value ever reaches a secondary surface. */\nexport const VALUE_FREE: PhiPosture = { showValues: false };\n\n/** The opted-in, PHI-exposing posture selected by `--unsafe-show-values`. */\nexport const SHOW_VALUES: PhiPosture = { showValues: true };\n\n/** The single global flag token that opts into showing values on secondary surfaces. */\nexport const UNSAFE_SHOW_VALUES_FLAG = \"--unsafe-show-values\";\n\n/**\n * The maximum number of leading input bytes an `--unsafe-show-values` diagnostic may echo. Bounded so\n * an unsafe excerpt stays a single, readable diagnostic line rather than dumping a whole message.\n */\nexport const UNSAFE_EXCERPT_MAX = 200;\n\n/**\n * Resolve the global `--unsafe-show-values` flag out of an argument vector, **order-independently**\n * (it may appear before or after the subcommand), and return the posture plus the argv with every\n * occurrence of the flag removed, so each command's own `parseArgs` never sees it and cannot reject\n * it as unknown. This is the one place the flag is recognised.\n *\n * @param argv - The raw arguments (after the program name).\n * @returns The resolved {@link PhiPosture} and the flag-stripped argv.\n * @example\n * ```ts\n * import { extractPhiPosture } from \"@cosyte/cli\";\n *\n * extractPhiPosture([\"parse\", \"x.hl7\"]).posture.showValues; // => false\n * extractPhiPosture([\"--unsafe-show-values\", \"parse\", \"x.hl7\"]).posture.showValues; // => true\n * extractPhiPosture([\"parse\", \"x.hl7\", \"--unsafe-show-values\"]).argv; // => [\"parse\", \"x.hl7\"]\n * ```\n */\nexport function extractPhiPosture(argv: readonly string[]): {\n posture: PhiPosture;\n argv: string[];\n} {\n const showValues = argv.includes(UNSAFE_SHOW_VALUES_FLAG);\n const cleaned = argv.filter((a) => a !== UNSAFE_SHOW_VALUES_FLAG);\n return { posture: showValues ? SHOW_VALUES : VALUE_FREE, argv: cleaned };\n}\n\n/**\n * Build the **only** value-bearing addition the CLI ever appends to a secondary (stderr) surface: a\n * bounded, single-line excerpt of the offending input, shown **iff** `--unsafe-show-values` is set.\n * Under the default value-free posture it returns the empty string, so a diagnostic stays value-free\n * unless the user explicitly opted in. This is the single chokepoint the PHI-leak matrix pins.\n *\n * @param bytes - The input the CLI is operating on (only the leading {@link UNSAFE_EXCERPT_MAX} bytes\n * are considered).\n * @param posture - The resolved {@link PhiPosture}.\n * @returns `\"\"` under the value-free default; otherwise a ` [unsafe-show-values] …` suffix carrying a\n * bounded, newline-flattened prefix of `bytes`.\n * @example\n * ```ts\n * import { unsafeInputSuffix, VALUE_FREE, SHOW_VALUES } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"bad message\");\n * unsafeInputSuffix(bytes, VALUE_FREE); // => \"\"\n * unsafeInputSuffix(bytes, SHOW_VALUES); // => \" [unsafe-show-values] offending input …: bad message\"\n * ```\n */\nexport function unsafeInputSuffix(bytes: Uint8Array, posture: PhiPosture): string {\n if (!posture.showValues) return \"\";\n const text = new TextDecoder(\"utf-8\", { fatal: false })\n .decode(bytes.subarray(0, UNSAFE_EXCERPT_MAX))\n .replace(/[\\r\\n\\t]+/g, \" \")\n .trim();\n if (text.length === 0) return \"\";\n return ` [unsafe-show-values] offending input (first ${String(UNSAFE_EXCERPT_MAX)} bytes): ${text}`;\n}\n","/**\n * The **wrapped-parser failure boundary**: the single, value-free way every command turns a thrown\n * parser/codec exception into a {@link RunResult}. A wrapped library raises a fatal on genuinely\n * unparseable input; its message (and, for HL7, its `snippet`) can embed the offending bytes, so the\n * CLI **never** surfaces that message. It surfaces only a stable, PHI-free code token (via\n * {@link extractStableCode}) plus the format name: the parsers' \"warning = code + position, never a\n * value\" rule at the CLI edge.\n *\n * The one, opt-in exception is `--unsafe-show-values`, whose bounded excerpt is appended through the\n * lone chokepoint in `core/phi.ts` ({@link unsafeInputSuffix}), so the \"a value appears on a\n * secondary surface **iff** the flag is set\" property stays provable in one place, uniformly across\n * `parse`/`validate`/`inspect`/`fmt`.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { CosyteFormat } from \"./format.js\";\nimport { unsafeInputSuffix, type PhiPosture } from \"./phi.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Pull a `code` off a thrown value **only** when it is a PHI-free constant token\n * (`^[A-Z][A-Z0-9_]*$`: a letter-led UPPER_SNAKE code like `MALFORMED_JSON`), e.g. a wrapped\n * parser's stable fatal code. Anything else (no `code`, a non-string, a non-token, or a **pure-digit**\n * value that could be a raw identifier) yields `null`, so a parser exception that embedded input bytes\n * in a `code`-shaped field can never reach a diagnostic.\n *\n * @param e - A caught value.\n * @returns The stable code token, or `null`.\n * @example\n * ```ts\n * import { extractStableCode } from \"@cosyte/cli\";\n *\n * extractStableCode({ code: \"MALFORMED_JSON\" }); // => \"MALFORMED_JSON\"\n * extractStableCode(new Error(\"boom\")); // => null\n * ```\n */\nexport function extractStableCode(e: unknown): string | null {\n if (typeof e === \"object\" && e !== null && \"code\" in e) {\n const raw: unknown = e.code;\n if (typeof raw === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(raw)) return raw;\n }\n return null;\n}\n\n/**\n * Build the value-free {@link RunResult} for a **wrapped-parser rejection**: a `CLI_PARSE_FAILED`\n * data error (exit `65`). The stderr line names the format and, when the thrown value carried one, a\n * stable code token in parentheses; it **never** echoes the parser's message or the input bytes. Under\n * `--unsafe-show-values` (and only then) a bounded excerpt of the offending input is appended via the\n * single {@link unsafeInputSuffix} chokepoint.\n *\n * @param format - The format whose parser rejected the input.\n * @param bytes - The offending input (only consulted for the opt-in unsafe excerpt).\n * @param posture - The resolved {@link PhiPosture}; the excerpt is appended only when it opts in.\n * @param e - The caught exception (its `code`, if a stable token, is surfaced: nothing else).\n * @returns A value-free `CLI_PARSE_FAILED` / exit-`65` {@link RunResult}.\n * @example\n * ```ts\n * import { parseFailureResult, VALUE_FREE } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"not hl7\");\n * parseFailureResult(\"hl7\", bytes, VALUE_FREE, { code: \"MISSING_MSH\" }).exit; // => 65\n * ```\n */\nexport function parseFailureResult(\n format: CosyteFormat,\n bytes: Uint8Array,\n posture: PhiPosture,\n e: unknown,\n): RunResult {\n const code = extractStableCode(e);\n const detail = code === null ? \"\" : ` (${code})`;\n const suffix = unsafeInputSuffix(bytes, posture);\n return {\n stdout: \"\",\n stderr: `cosyte: ${CLI_CODES.CLI_PARSE_FAILED}: the ${format} parser rejected the input${detail}${suffix}\\n`,\n exit: EXIT.DATAERR,\n };\n}\n","/**\n * Input I/O for the CLI: read the bytes to operate on from a **file argument** or from **stdin**\n * (`-`), with a value-free failure mode. The CLI never writes a temp file and never logs to a file;\n * this module only *reads*.\n *\n * The reader functions are injected into the command layer as {@link RunDeps} so the whole dispatch\n * path is testable without touching `process`: the real `process.stdin` wiring lives in the thin\n * `bin` entry.\n *\n * @packageDocumentation\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type { Readable } from \"node:stream\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\n\n/**\n * The injectable input side-effects the dispatcher needs. Kept tiny and pure-ish so tests drive the\n * CLI end to end with in-memory fakes and no real filesystem or stdin.\n */\nexport interface RunDeps {\n /** Read a file's bytes, or raise a `CLI_NO_INPUT` {@link CliError} if it cannot be read. */\n readonly readFile: (path: string) => Promise<Uint8Array>;\n /** Read all of stdin's bytes. */\n readonly readStdin: () => Promise<Uint8Array>;\n}\n\n/**\n * Read a file into bytes, mapping any read failure to a **value-free** `CLI_NO_INPUT` /\n * {@link EXIT.NOINPUT} error. The path is structural context (the user supplied it), so it may appear\n * in the message; the file *contents* never do.\n *\n * @param path - The file path to read.\n * @returns The file bytes.\n * @throws {CliError} `CLI_NO_INPUT` (exit `66`) when the file is missing, a directory, or unreadable.\n * @example\n * ```ts throws\n * import { readFileBytes } from \"@cosyte/cli\";\n *\n * await readFileBytes(\"/no/such/file\"); // throws CliError CLI_NO_INPUT\n * ```\n */\nexport async function readFileBytes(path: string): Promise<Uint8Array> {\n try {\n return await readFile(path);\n } catch {\n throw new CliError(\n CLI_CODES.CLI_NO_INPUT,\n EXIT.NOINPUT,\n `cannot read input file: ${path} (does it exist and is it readable?)`,\n );\n }\n}\n\n/**\n * Drain a readable stream (e.g. `process.stdin`) into a single byte buffer.\n *\n * @param stream - The readable stream to drain.\n * @returns The concatenated bytes.\n * @example\n * ```ts\n * import { Readable } from \"node:stream\";\n * import { readStreamBytes } from \"@cosyte/cli\";\n *\n * const bytes = await readStreamBytes(Readable.from([Buffer.from(\"MSH|\")]));\n * bytes.length; // => 4\n * ```\n */\nexport async function readStreamBytes(stream: Readable): Promise<Uint8Array> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream as AsyncIterable<Buffer | string>) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk, \"utf-8\") : chunk);\n }\n return Buffer.concat(chunks);\n}\n","/**\n * The **de-identification seam**: the single, documented plug-in point where the `redact` / `deid`\n * command will delegate to **`@cosyte/deid`** once that integration lands and is vetted.\n *\n * ## Why the CLI ships no built-in redactor (the boundary decision)\n *\n * The CLI does **not wire `@cosyte/deid` yet**, and the wrapped\n * parsers (`@cosyte/hl7`, `@cosyte/fhir`) expose **no de-identification API**: they redact only\n * their own *diagnostics*, not the parsed model. So there is nothing for the CLI to delegate to\n * today.\n *\n * A tempting alternative, a \"minimal built-in Safe-Harbor pass over the obvious PHI loci\" (e.g. the\n * HL7 `PID` segment, `Patient.name`/`Patient.address` in FHIR), is **deliberately rejected**. Real\n * messages carry PHI far beyond those loci: HL7 `NK1`/`GT1`/`IN1`/`OBX`/`NTE`, FHIR extensions and\n * contained resources, free-text notes. A redactor that scrubs the obvious fields and emits output\n * that *looks* de-identified while silently leaving PHI behind is a **false-safety impression**. A\n * `redact` that under-redacts is worse than no `redact`.\n *\n * So `redact` is an **honest, typed `CLI_NOT_IMPLEMENTED`** (never a fake success, never a partial\n * scrub presented as de-identified, never invent a capability the ground layer lacks),\n * gated on `@cosyte/deid`, with this seam as its one drop-in point. When that integration lands and is\n * conformance-graded, {@link deidStatus} flips to `available` and the command reads the input, calls\n * the delegated de-identifier, and emits the de-identified model: the command surface (`redact`,\n * `deid`, `<file|->`, `--format`) already exists so that change is additive.\n *\n * @packageDocumentation\n */\n\n/** The value-free reason `redact`/`deid` reports while the ground-layer library is unavailable. */\nexport const DEID_UNAVAILABLE_REASON =\n \"redact/deid is not yet available. It delegates to @cosyte/deid, which the CLI does not wire yet. \" +\n \"The CLI ships no built-in redactor: a partial Safe-Harbor scrub over only the obvious PHI \" +\n \"loci would leave PHI behind and present a false-safety impression, so nothing is emitted. This \" +\n \"command will produce a de-identified copy once that integration lands and is vetted.\";\n\n/**\n * Whether de-identification is available, and (while it is not) the value-free reason why. The one\n * function the `redact` command consults **before reading any input**, so a `redact` invocation never\n * touches the PHI it cannot yet safely strip.\n */\nexport interface DeidAvailability {\n /** `true` once `@cosyte/deid` is wired; `false` today. */\n readonly available: boolean;\n /** A value-free explanation shown when {@link DeidAvailability.available} is `false`. */\n readonly reason: string;\n}\n\n/**\n * Report the current de-identification availability. Today it is always unavailable (see the module\n * docs); this is the single line that flips when `@cosyte/deid` is wired.\n *\n * @returns The {@link DeidAvailability}: `{ available: false, reason }` until `@cosyte/deid` is wired.\n * @example\n * ```ts\n * import { deidStatus } from \"@cosyte/cli\";\n *\n * deidStatus().available; // => false\n * ```\n */\nexport function deidStatus(): DeidAvailability {\n return { available: false, reason: DEID_UNAVAILABLE_REASON };\n}\n","/**\n * `cosyte completion <bash|zsh|fish>`\n *\n * Print a shell completion script for `cosyte`, generated from the command tree, to **stdout**: the\n * user pipes it into their shell (`source <(cosyte completion bash)`) or saves it to their completions\n * directory. The script is static and value-free: it names commands, subcommand tokens, and flags,\n * never any input. An unknown or missing shell is a usage error (exit `2`), never a silent no-op.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunResult } from \"../core/result.js\";\n\n/** The subcommands offered for completion (mirrors the dispatcher in `core/run.ts`). */\nconst COMMANDS = [\n \"parse\",\n \"validate\",\n \"inspect\",\n \"fmt\",\n \"convert\",\n \"map-codes\",\n \"redact\",\n \"deid\",\n \"mcp\",\n \"completion\",\n] as const;\n\n/** The common flags offered across the file-consuming commands. */\nconst FLAGS = [\n \"--format\",\n \"--json\",\n \"--ndjson\",\n \"--quiet\",\n \"--no-color\",\n \"--unsafe-show-values\",\n \"--help\",\n \"--version\",\n] as const;\n\n/** The shells `completion` can emit a script for. */\nconst SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\ntype Shell = (typeof SHELLS)[number];\n\n/**\n * Run the `completion` command.\n *\n * @param args - The arguments after the `completion` subcommand token; the first is the shell name.\n * @returns A {@link RunResult}: the completion script on `stdout` (exit `0`), or a value-free usage\n * error (exit `2`) when the shell is missing or unrecognised.\n * @example\n * ```ts\n * import { completionCommand } from \"@cosyte/cli\";\n *\n * completionCommand([\"bash\"]).exit; // => 0\n * completionCommand([\"powershell\"]).exit; // => 2\n * ```\n */\nexport function completionCommand(args: string[]): RunResult {\n const shell = args[0];\n if (shell === undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `missing shell; usage: cosyte completion <${SHELLS.join(\"|\")}>`,\n ),\n );\n }\n if (!isShell(shell)) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unknown shell '${shell}'; supported: ${SHELLS.join(\", \")}`,\n ),\n );\n }\n return { stdout: SCRIPTS[shell](), stderr: \"\", exit: EXIT.OK };\n}\n\n/** Narrow an arbitrary string to a supported {@link Shell}. */\nfunction isShell(value: string): value is Shell {\n return (SHELLS as readonly string[]).includes(value);\n}\n\n/** The per-shell script generators. Each is static text built from {@link COMMANDS} + {@link FLAGS}. */\nconst SCRIPTS: Readonly<Record<Shell, () => string>> = {\n bash: () => `# cosyte bash completion: source <(cosyte completion bash)\n_cosyte() {\n local cur prev cmds flags\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n cmds=\"${COMMANDS.join(\" \")}\"\n flags=\"${FLAGS.join(\" \")}\"\n if [ \"\\${COMP_CWORD}\" -eq 1 ]; then\n COMPREPLY=( $(compgen -W \"\\${cmds}\" -- \"\\${cur}\") )\n else\n COMPREPLY=( $(compgen -W \"\\${flags}\" -f -- \"\\${cur}\") )\n fi\n}\ncomplete -F _cosyte cosyte\n`,\n zsh: () => `#compdef cosyte\n# cosyte zsh completion: source <(cosyte completion zsh)\n_cosyte() {\n local -a cmds flags\n cmds=(${COMMANDS.map((c) => `'${c}'`).join(\" \")})\n flags=(${FLAGS.map((f) => `'${f}'`).join(\" \")})\n if (( CURRENT == 2 )); then\n _describe 'command' cmds\n else\n _describe 'flag' flags\n _files\n fi\n}\ncompdef _cosyte cosyte\n`,\n fish: () => {\n const lines = COMMANDS.map(\n (c) => `complete -c cosyte -n '__fish_use_subcommand' -a '${c}' -d 'cosyte ${c}'`,\n );\n const flagLines = FLAGS.filter((f) => f.startsWith(\"--\")).map(\n (f) => `complete -c cosyte -l '${f.slice(2)}'`,\n );\n return `# cosyte fish completion: cosyte completion fish | source\n${lines.join(\"\\n\")}\n${flagLines.join(\"\\n\")}\n`;\n },\n};\n","/**\n * `cosyte convert <file|-> --to fhir [--json] [--quiet] [--no-color]`\n *\n * Convert an **HL7 v2** message to **FHIR R4** via **`@cosyte/transform`**: the\n * consumer-of-consumers command. The CLI adds **no** mapping logic of its own: it parses the input\n * with `@cosyte/hl7`, hands the parsed message to `transform`'s `toFhir`, and serializes the resulting\n * FHIR `Bundle` with `@cosyte/fhir`. The mapping guarantees are the library's, graded by *its* gate;\n * `cosyte convert` equals `transform`'s programmatic output.\n *\n * The converted FHIR `Bundle` is the user's explicit request, so it goes to **stdout** (the data\n * channel). Every conversion problem is one of `transform`'s value-free {@link TransformIssue}s: a\n * stable code, a severity, and a positional locator (a v2 index and an optional FHIRPath), **never** a\n * field value: surfaced on stderr (or as value-free JSON under `--json`). The load-bearing rule\n * (mirroring `validate`): a conversion that produces an **error-severity** issue exits **`1`**, never\n * `0`: the tool worked, but the conversion has a real problem a CI gate must see.\n *\n * `--to fhir` is required and is the only supported target (HL7 v2 → FHIR R4). The source must be\n * HL7 v2: a recognised-but-non-HL7 input (e.g. a FHIR document) is a value-free\n * `CLI_FORMAT_UNSUPPORTED` data error (`65`), never a fake conversion.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { Finding } from \"../core/findings.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { loadFhir, loadOptionalPackage } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `convert` understands. */\nconst CONVERT_OPTIONS = {\n to: { type: \"string\" },\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** The only conversion target this build supports (HL7 v2 → FHIR R4). */\nconst SUPPORTED_TARGET = \"fhir\";\n\n/** Transform severities that make a conversion a **failure** (exit `1`). `transform` has no `fatal`. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** The value-free result of a conversion: the serialized FHIR bundle text + the library's findings. */\ninterface Conversion {\n readonly bundleText: string;\n readonly findings: readonly Finding[];\n}\n\n/**\n * Run the `convert` command.\n *\n * @param args - The arguments after the `convert` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on an HL7\n * parse-failure diagnostic; the converted bundle and the value-free findings are unaffected).\n * @returns A {@link RunResult}: the converted FHIR `Bundle` on `stdout` (the data channel), value-free\n * findings on `stderr` (or JSON under `--json`), and an exit code that carries the outcome: `0`\n * clean · `1` an error-severity conversion issue · `65` the HL7 input could not be parsed or is not\n * an HL7 v2 source · `66` no input · `2` usage.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { convertCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode(\"MSH|^~\\\\&|A|B|C|D|20240101||ADT^A01|1|P|2.5\\r\"),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await convertCommand([\"adt.hl7\", \"--to\", \"fhir\"], deps)).exit; // => 0\n * ```\n */\nexport async function convertCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n to?: string;\n format?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: CONVERT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `convert` (see `cosyte convert --help`)\",\n ),\n );\n }\n\n // `--to` is required and names the conversion target. Only `fhir` is supported today; requiring it\n // (rather than defaulting) keeps the surface explicit and future-proof for other targets.\n if (values.to === undefined) {\n return errorResult(\n new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"convert requires --to fhir (the only target)\"),\n );\n }\n if (values.to !== SUPPORTED_TARGET) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unsupported --to '${values.to}'; only --to fhir is supported (HL7 v2 → FHIR R4)`,\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // convert reads HL7 v2 and writes FHIR R4. A recognised-but-non-HL7 source (e.g. a FHIR document) is\n // not a convertible input: a value-free data error, never a fake or identity \"conversion\".\n if (format !== \"hl7\") {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `convert reads HL7 v2 and writes FHIR R4; the input is '${format}', not an HL7 v2 source`,\n ),\n );\n }\n\n const outcome = await runConvert(bytes, posture);\n if (!outcome.ok) return outcome.result;\n const conversion = outcome.conversion;\n\n const { hasError, report } = convertOutcome(conversion.findings);\n const exit = hasError ? EXIT.INVALID : EXIT.OK;\n\n if (values.json === true) {\n // Machine output on the data channel: the converted bundle plus the value-free findings.\n const body = {\n format: SUPPORTED_TARGET,\n bundle: JSON.parse(conversion.bundleText) as unknown,\n findings: conversion.findings,\n };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n // Default: the converted FHIR Bundle (the library's canonical serialization) IS the stdout data\n // channel; the value-free findings + a summary go to stderr unless suppressed by --quiet.\n const stderr = values.quiet === true ? \"\" : report;\n return { stdout: `${conversion.bundleText}\\n`, stderr, exit };\n}\n\n/** Either a completed conversion, or a ready value-free parse-failure {@link RunResult}. */\ntype ConvertOutcome =\n | { readonly ok: true; readonly conversion: Conversion }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Why `@cosyte/transform` is absent, in words a user can act on. **It deliberately does not say\n * \"install it\"**: `npm install @cosyte/transform` fails too (`E404` on its own `@cosyte/fhir` peer),\n * so telling someone to install it would send them at a command that cannot succeed. That is the same\n * defect the `@cosyte/fhir` diagnostic exists to avoid, and it is why neither goes through\n * `loadOptional()`, whose stock wording is exactly \"install it (it is an optional dependency)\".\n * Value-free by construction: package names and a statement of fact, no input echoed.\n */\nconst TRANSFORM_UNAVAILABLE =\n \"the @cosyte/transform conversion library is not installed, so convert is unavailable; it \" +\n \"requires @cosyte/fhir, which is not currently on the npm registry, so npm skips transform as \" +\n \"an unresolvable optional dependency and installing it directly fails for the same reason\";\n\n/**\n * Parse the HL7 v2 bytes and convert to FHIR: every library **lazy-loaded** so this code loads only\n * when `convert` runs. Only the `parseHL7` call is inside the failure boundary: a genuine parser\n * rejection becomes a value-free `CLI_PARSE_FAILED` (65), with the single opt-in excerpt (under\n * `--unsafe-show-values`) flowing through the shared core/wrap chokepoint. The `toFhir` + serialize\n * step is deliberately outside it: `toFhir` never throws for a well-formed message, so any throw there\n * is an unexpected bug the dispatcher maps to `CLI_INTERNAL` (70), never mislabelled as a rejection.\n *\n * Two of the three libraries are **not guaranteed present in an installed copy**, so both loads go\n * through the optional-package boundary and an absent one becomes a value-free\n * `CLI_PARSER_UNAVAILABLE` (69) rather than an unhandled resolver error. `@cosyte/hl7` is a hard\n * dependency and needs no such treatment.\n */\nasync function runConvert(bytes: Uint8Array, posture: PhiPosture): Promise<ConvertOutcome> {\n const [{ parseHL7 }, { toFhir }, { serializeResource }] = await Promise.all([\n import(\"@cosyte/hl7\"),\n loadOptionalPackage(TRANSFORM_UNAVAILABLE, () => import(\"@cosyte/transform\")),\n loadFhir(),\n ]);\n\n let msg: ReturnType<typeof parseHL7>;\n try {\n msg = parseHL7(Buffer.from(bytes));\n } catch (e) {\n return { ok: false, result: parseFailureResult(\"hl7\", bytes, posture, e) };\n }\n\n const { bundle, issues } = toFhir(msg);\n return {\n ok: true,\n conversion: {\n bundleText: serializeResource(bundle),\n findings: issues.map((i) => toFinding(i.code, i.severity, i.v2Location, i.fhirPath)),\n },\n };\n}\n\n/** Build one value-free {@link Finding} from a transform issue: v2 locator, and the FHIRPath if any. */\nfunction toFinding(code: string, severity: string, v2Location: string, fhirPath?: string): Finding {\n const location = fhirPath !== undefined ? `${v2Location} → ${fhirPath}` : v2Location;\n return { code, severity, location };\n}\n\n/**\n * Decide the conversion outcome from the library's value-free findings: whether any is\n * **error-severity** (which drives a non-zero exit: the load-bearing \"a conversion error is never\n * exit 0\" rule) and the value-free human report. The severity classification is\n * the library's: `@cosyte/transform` fixes each issue's severity; the CLI only reads it. Exported so\n * the exit-verdict and report logic is unit-testable with synthetic findings, independent of which HL7\n * message happens to produce an error.\n *\n * @param findings - The value-free {@link Finding}s the conversion produced.\n * @returns `hasError` (true iff any finding is error/fatal severity) and the rendered value-free\n * `report` (one line per finding + a summary line).\n * @example\n * ```ts\n * import { convertOutcome } from \"@cosyte/cli\";\n *\n * convertOutcome([{ code: \"TRANSFORM_RESOURCE_INVALID\", severity: \"error\", location: \"PID\" }])\n * .hasError; // => true\n * convertOutcome([{ code: \"TRANSFORM_ELEMENT_DROPPED\", severity: \"information\", location: \"PID.13\" }])\n * .hasError; // => false\n * ```\n */\nexport function convertOutcome(findings: readonly Finding[]): {\n readonly hasError: boolean;\n readonly report: string;\n} {\n const lines = findings.map((f) => `cosyte: convert: ${f.severity} ${f.code} at ${f.location}\\n`);\n const errors = findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = findings.length - errors;\n const summary =\n errors > 0\n ? `cosyte: convert: hl7 → fhir produced ${String(errors)} error(s), ${String(others)} other finding(s)\\n`\n : `cosyte: convert: hl7 → fhir OK (${String(findings.length)} finding(s))\\n`;\n return { hasError: errors > 0, report: lines.join(\"\") + summary };\n}\n","/**\n * `cosyte fmt <file|-> [--format …] [--quiet] [--no-color]`\n *\n * **Canonical re-serialization.** Parse the input and emit it back through the wrapped library's\n * **conservative, spec-clean serializer**: HL7 via `Hl7Message.toString()` (CR-separated, spec-clean\n * HL7), FHIR via `serializeResource` (canonical JSON, decimals byte-exact). The CLI **never\n * re-canonicalizes on its own**: the output is exactly the wrapped serializer's, so\n * `fmt` round-trips a spec-clean input through the parser.\n *\n * `fmt`'s stdout **is** the data channel: a re-serialization of the message, values included, going to\n * the sink the user chose. Every *secondary* surface stays value-free: a warning-count note on stderr\n * (suppressible with `--quiet`), and an unparseable input is a data error (`65`) with **no partial\n * emit**, never a half-serialized message.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { fmtFormat, type FmtResult } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `fmt` understands. `fmt`'s output shape is the library serializer's, so there is no `--json`. */\nconst FMT_OPTIONS = {\n format: { type: \"string\" },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `fmt` command.\n *\n * @param args - The arguments after the `fmt` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic).\n * @returns A {@link RunResult}: the canonical re-serialization on `stdout` (exit `0`), a value-free\n * warning-count note on `stderr` unless `--quiet`; an unparseable input is a data error (`65`) with\n * no partial emit, an unreadable file `66`, a bad flag `2`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { fmtCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{ \"resourceType\":\"Patient\" , \"id\":\"x\" }'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await fmtCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function fmtCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: { format?: string; quiet?: boolean; \"no-color\"?: boolean };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: FMT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `fmt` (see `cosyte fmt --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"fmt\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let result: FmtResult;\n try {\n result = await fmtFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n // No partial emit: an unparseable input yields a value-free data error, never half a message.\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const stderr =\n result.warningCount > 0 && values.quiet !== true\n ? `cosyte: fmt: re-serialized ${format} with ${String(result.warningCount)} parse warning(s)\\n`\n : \"\";\n return { stdout: `${result.output}\\n`, stderr, exit: EXIT.OK };\n}\n","/**\n * `cosyte inspect <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * A human-readable, **value-free-by-default** structural summary of a message: its type, structural\n * counts, and a warning count: the \"what shape is this?\" answer, without ever printing a field\n * value. Unlike `parse`, whose stdout is the parsed model (the data channel), `inspect`'s\n * stdout is a *structural* summary composed only of counts and structural type **codes** (an HL7 message\n * type like `ADT^A01`, a FHIR `resourceType` like `Patient`, an X12 transaction-set id like `834`, a\n * DICOM SOP Class UID, an NCPDP `NewRx`): classification, never PHI. `--json` emits the same value-free\n * summary as machine JSON. The per-format summaries are built by the shared registry (`core/parsers.ts`).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { inspectFormat, type InspectSummary } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `inspect` understands. */\nconst INSPECT_OPTIONS = {\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `inspect` command.\n *\n * @param args - The arguments after the `inspect` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; the summary itself is always value-free).\n * @returns A {@link RunResult}: the value-free structural summary on `stdout` (human, or JSON under\n * `--json`), exit `0`; a parse failure is a data error (`65`), an unreadable file `66`, a bad flag `2`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { inspectCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await inspectCommand([\"patient.json\", \"--json\"], deps)).exit; // => 0\n * ```\n */\nexport async function inspectCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: { format?: string; json?: boolean; quiet?: boolean; \"no-color\"?: boolean };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: INSPECT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `inspect` (see `cosyte inspect --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"inspect\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let summary: InspectSummary;\n try {\n summary = await inspectFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const stdout = values.json === true ? `${JSON.stringify(summary)}\\n` : renderSummary(summary);\n return { stdout, stderr: \"\", exit: EXIT.OK };\n}\n\n/**\n * Render a value-free human structural summary. Only counts and structural type codes, never a value.\n * Exported for direct branch testing of the per-format render (not re-exported from the package root).\n *\n * @param summary - The value-free {@link InspectSummary} to render.\n * @returns The human-readable, value-free summary text.\n * @example\n * ```ts\n * import { renderSummary } from \"@cosyte/cli/dist/commands/inspect.js\";\n *\n * renderSummary({ format: \"mllp\", frameCount: 2, warningCount: 0 }).includes(\"frames\"); // => true\n * ```\n */\nexport function renderSummary(summary: InspectSummary): string {\n const lines: string[] = [];\n const countLines = (label: string, counts: Readonly<Record<string, number>>): void => {\n if (label.length > 0) lines.push(label);\n for (const key of Object.keys(counts).sort()) lines.push(` ${key}: ${String(counts[key])}`);\n };\n\n switch (summary.format) {\n case \"hl7\":\n lines.push(`format: hl7`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n countLines(\"\", summary.segments);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"fhir\":\n lines.push(`format: fhir`);\n lines.push(`resource type: ${summary.resourceType ?? \"(unknown)\"}`);\n if (summary.entryCount !== undefined) {\n lines.push(`bundle type: ${summary.bundleType ?? \"(unknown)\"}`);\n lines.push(`entries: ${String(summary.entryCount)}`);\n countLines(\"\", summary.entryResourceTypes ?? {});\n }\n lines.push(`issues: ${String(summary.issueCount)}`);\n break;\n case \"x12\":\n lines.push(`format: x12`);\n lines.push(`groups: ${String(summary.groupCount)}`);\n lines.push(`transactions: ${String(summary.transactionCount)}`);\n countLines(\"transaction sets:\", summary.transactionSetIds);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"astm\":\n lines.push(`format: astm`);\n lines.push(`message kind: ${summary.messageKind}`);\n lines.push(`records: ${String(summary.recordCount)}`);\n countLines(\"\", summary.recordTypes);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ccda\":\n lines.push(`format: ccda`);\n lines.push(`document type: ${summary.documentType ?? \"(unknown)\"}`);\n lines.push(`sections: ${String(summary.sectionCount)}`);\n if (summary.sectionCodes.length > 0) {\n lines.push(`section codes: ${summary.sectionCodes.join(\", \")}`);\n }\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"dicom\":\n lines.push(`format: dicom`);\n lines.push(`sop class uid: ${summary.sopClassUid ?? \"(unknown)\"}`);\n lines.push(`transfer syntax:${summary.transferSyntaxUid ?? \" (unknown)\"}`);\n lines.push(`elements: ${String(summary.elementCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ncpdp\":\n lines.push(`format: ncpdp`);\n lines.push(`standard: SCRIPT`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"mllp\":\n lines.push(`format: mllp`);\n lines.push(`frames: ${String(summary.frameCount)}`);\n lines.push(`warnings:${String(summary.warningCount)}`);\n break;\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n","/**\n * `cosyte map-codes <conceptmap|-> --code <code> [--system <uri>] [--version <v>] [--display <d>]\n * [--json] [--quiet]`\n *\n * Translate a single source coding through a **BYO FHIR R4 ConceptMap** via\n * **`@cosyte/terminology`**. The positional argument is the ConceptMap document (a file, or `-` for\n * stdin); `--system` + `--code` (and optional `--version`/`--display`) name the source coding to\n * translate. The CLI adds **no** mapping content of its own: `terminology` is content-free and\n * never fabricates a target; the CLI loads the user's map and forwards the translation faithfully.\n *\n * A ConceptMap and a terminology code are **reference data, not PHI**, so the translation result\n * (the matched target coding(s), or the value-free \"unmapped\" signal) is the user's explicit request\n * and goes to **stdout**. The exit code carries the outcome so it is usable as a gate: **`0`** at\n * least one match · **`1`** no mapping found (the never-fabricate `TERM_TRANSLATE_UNMAPPED` outcome) ·\n * `65` the supplied ConceptMap is not valid JSON / not a loadable ConceptMap · `66` no input · `2`\n * usage. stderr stays value-free (stable codes and counts only).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport type { Coding, TranslateResult } from \"@cosyte/terminology\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { extractStableCode } from \"../core/wrap.js\";\n\n/** The flags `map-codes` understands. */\nconst MAP_CODES_OPTIONS = {\n code: { type: \"string\" },\n system: { type: \"string\" },\n version: { type: \"string\" },\n display: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `map-codes` command.\n *\n * @param args - The arguments after the `map-codes` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}); the positional argument (or `-`) is the BYO\n * ConceptMap document.\n * @returns A {@link RunResult}: the translation result on `stdout` (matched target coding(s) or the\n * value-free unmapped signal), a value-free note on `stderr` (unless `--quiet`), and an exit code\n * carrying the outcome: `0` mapped · `1` unmapped · `65` unloadable ConceptMap · `66` no input ·\n * `2` usage.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { mapCodesCommand } from \"@cosyte/cli\";\n *\n * const cm = JSON.stringify({\n * resourceType: \"ConceptMap\",\n * group: [\n * {\n * source: \"http://hl7.org/fhir/administrative-gender\",\n * target: \"http://terminology.hl7.org/CodeSystem/v2-0001\",\n * element: [{ code: \"male\", target: [{ code: \"M\", equivalence: \"equivalent\" }] }],\n * },\n * ],\n * });\n * const deps = {\n * readFile: async () => new TextEncoder().encode(cm),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await mapCodesCommand(\n * [\"gender.json\", \"--system\", \"http://hl7.org/fhir/administrative-gender\", \"--code\", \"male\"],\n * deps,\n * );\n * r.exit; // => 0\n * ```\n */\nexport async function mapCodesCommand(args: string[], deps: RunDeps): Promise<RunResult> {\n let values: {\n code?: string;\n system?: string;\n version?: string;\n display?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: MAP_CODES_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `map-codes` (see `cosyte map-codes --help`)\",\n ),\n );\n }\n\n const source = positionals[0];\n if (source === undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <conceptmap> argument; pass a FHIR ConceptMap path or `-` to read stdin\",\n ),\n );\n }\n if (values.code === undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"map-codes requires --code (the source code to translate)\",\n ),\n );\n }\n\n // Read the ConceptMap bytes (a missing/unreadable file is a value-free no-input error, 66).\n let bytes: Uint8Array;\n try {\n bytes = source === \"-\" ? await deps.readStdin() : await deps.readFile(source);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n throw e;\n }\n if (bytes.length === 0) {\n return errorResult(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n const coding: Coding = {\n code: values.code,\n ...(values.system !== undefined ? { system: values.system } : {}),\n ...(values.version !== undefined ? { version: values.version } : {}),\n ...(values.display !== undefined ? { display: values.display } : {}),\n };\n\n const outcome = await translateVia(bytes, coding);\n if (!outcome.ok) return outcome.result;\n const { result } = outcome;\n\n const exit = result.unmapped ? EXIT.INVALID : EXIT.OK;\n const body = { source: coding, result };\n\n if (values.json === true) {\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n const stderr = values.quiet === true ? \"\" : renderNote(result);\n return { stdout: `${JSON.stringify(body, null, 2)}\\n`, stderr, exit };\n}\n\n/** The result of loading + translating: either the translate result, or a ready value-free error. */\ntype TranslateOutcome =\n | { readonly ok: true; readonly result: TranslateResult }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Load the BYO ConceptMap (lazy-loading `@cosyte/terminology`) and translate the source coding.\n * Malformed JSON and an unloadable ConceptMap both resolve to a value-free `CLI_MAP_INVALID` data\n * error: the map's bytes are never echoed, only the stable terminology-loader code (when the thrown\n * value carried one, e.g. `TERM_CONCEPTMAP_MALFORMED`).\n */\nasync function translateVia(bytes: Uint8Array, coding: Coding): Promise<TranslateOutcome> {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return mapInvalid(\"the ConceptMap input is not valid JSON\");\n }\n\n const { loadConceptMap, translate } = await import(\"@cosyte/terminology\");\n let map: ReturnType<typeof loadConceptMap>;\n try {\n map = loadConceptMap(json);\n } catch (e) {\n const code = extractStableCode(e);\n const detail = code === null ? \"\" : ` (${code})`;\n return mapInvalid(`the supplied ConceptMap could not be loaded${detail}`);\n }\n return { ok: true, result: translate(coding, map) };\n}\n\n/** Build a value-free `CLI_MAP_INVALID` (exit `65`) failure outcome. */\nfunction mapInvalid(message: string): TranslateOutcome {\n return {\n ok: false,\n result: errorResult(new CliError(CLI_CODES.CLI_MAP_INVALID, EXIT.DATAERR, message)),\n };\n}\n\n/** Render the value-free stderr note: a mapped count, or the stable unmapped code + fallback mode. */\nfunction renderNote(result: TranslateResult): string {\n if (result.unmapped) {\n return `cosyte: map-codes: ${result.code} (fallback mode: ${result.mode})\\n`;\n }\n return `cosyte: map-codes: ${String(result.matches.length)} match(es)\\n`;\n}\n","/**\n * `cosyte parse <file|-> [--format …] [--ndjson] [--json] [--quiet] [--no-color]`\n *\n * Read a file (or stdin via `-`), **autodetect the format by content** (or honour `--format`), route to\n * the wrapped parser via the lazy per-format registry (`core/parsers.ts`) (so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code) and emit the parsed model as **typed JSON on stdout**. Every\n * failure is a value-free diagnostic on stderr with a stable `CLI_*` code and the documented exit code.\n *\n * **Multi-message / streaming.** A single message emits one pretty (or compact under `--json`)\n * JSON envelope, exactly as before. A **multi-record** input emits **NDJSON** (one compact envelope\n * per line) with per-record isolation: a record that fails to parse becomes a value-free\n * `{ record, error }` line and the stream continues, and the overall exit is a data error (`65`) if any\n * record failed. Two inputs are multi-record: an **MLLP** stream (each VT-framed frame is an enclosed\n * HL7 message) and any input under **`--ndjson`** (each non-empty line is a record: the FHIR bulk-data\n * convention).\n *\n * The CLI adds **no** parsing of its own: it routes, reads, and shapes output; `cosyte parse` equals the\n * wrapped library's programmatic parse.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { deframeMllp, parseFormat, type ParseWarning } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { extractStableCode, parseFailureResult } from \"../core/wrap.js\";\n\n// Re-exported from the shared wrapper boundary so the historical `@cosyte/cli` import path stays stable.\nexport { extractStableCode } from \"../core/wrap.js\";\n\n/** The typed JSON envelope a single `parse` emits on stdout: the format, the parsed model, warnings. */\ninterface ParseEnvelope {\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n}\n\n/** One line of NDJSON multi-record output: a parsed record, or a value-free per-record parse error. */\ntype RecordLine =\n | {\n readonly record: number;\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n }\n | { readonly record: number; readonly format: CosyteFormat; readonly error: string };\n\n/** The flags `parse` understands, parsed by {@link parseArgs}. */\nconst PARSE_OPTIONS = {\n format: { type: \"string\" },\n ndjson: { type: \"boolean\", default: false },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `parse` command.\n *\n * @param args - The arguments after the `parse` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture}. Defaults to {@link VALUE_FREE}; under\n * `--unsafe-show-values` a bounded excerpt of the offending input is appended to a `CLI_PARSE_FAILED`\n * diagnostic (the single, opt-in value-echoing surface): single-record mode only.\n * @returns A {@link RunResult}: the typed-JSON model (or NDJSON records) on `stdout`, a value-free note\n * (or nothing) on `stderr`, and the resolved exit code. Never throws a {@link CliError}: it resolves\n * it to a result; unexpected exceptions are caught by the dispatcher and mapped to `CLI_INTERNAL`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { parseCommand } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * const deps = {\n * readFile: async () => enc.encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await parseCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function parseCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n ndjson?: boolean;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: PARSE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `parse` (see `cosyte parse --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // MLLP is a transport container and `--ndjson` is explicit batch mode: both are multi-record.\n if (format === \"mllp\" || values.ndjson === true) {\n return await parseMulti(format, bytes, values.ndjson === true, values.quiet === true);\n }\n return await parseSingle(format, bytes, values.json === true, values.quiet === true, posture);\n}\n\n/** Parse a single message → one JSON envelope (pretty, or compact under `--json`). Preserves the\n * value-free failure boundary and the opt-in `--unsafe-show-values` excerpt. */\nasync function parseSingle(\n format: CosyteFormat,\n bytes: Uint8Array,\n json: boolean,\n quiet: boolean,\n posture: PhiPosture,\n): Promise<RunResult> {\n let result: { model: unknown; warnings: readonly ParseWarning[] };\n try {\n result = await parseFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, posture, e);\n }\n const envelope: ParseEnvelope = { format, model: result.model, warnings: result.warnings };\n const stdout = (json ? JSON.stringify(envelope) : JSON.stringify(envelope, null, 2)) + \"\\n\";\n\n const n = envelope.warnings.length;\n const stderr =\n n > 0 && !quiet\n ? `cosyte: parsed ${format} with ${String(n)} warning(s) (see .warnings in output)\\n`\n : \"\";\n return { stdout, stderr, exit: EXIT.OK };\n}\n\n/** Parse a multi-record input (MLLP frames, or `--ndjson` lines) → NDJSON, with per-record isolation. */\nasync function parseMulti(\n format: CosyteFormat,\n bytes: Uint8Array,\n ndjson: boolean,\n quiet: boolean,\n): Promise<RunResult> {\n // Resolve the records + the format each record is parsed as. MLLP de-frames to enclosed HL7 payloads.\n let records: Uint8Array[];\n let recordFormat: CosyteFormat;\n try {\n if (format === \"mllp\") {\n const { payloads } = await deframeMllp(bytes);\n records = payloads;\n recordFormat = \"hl7\";\n } else {\n records = splitLines(bytes);\n recordFormat = format;\n }\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, VALUE_FREE, e);\n }\n\n if (records.length === 0) {\n // A framed/ndjson input that yielded no record is a data error, never a silent success.\n return errorResult(\n new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n `no ${format === \"mllp\" ? \"MLLP frame\" : \"record\"} found in the input`,\n ),\n );\n }\n\n const lines: RecordLine[] = [];\n let failed = 0;\n let warnings = 0;\n for (let i = 0; i < records.length; i += 1) {\n const rec = records[i] as Uint8Array;\n try {\n const { model, warnings: ws } = await parseFormat(recordFormat, rec);\n warnings += ws.length;\n lines.push({ record: i, format: recordFormat, model, warnings: ws });\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // a parser-unavailable is fatal for the stream\n failed += 1;\n // Value-free per-record error: a stable code (if the throw carried one), never the bytes.\n lines.push({\n record: i,\n format: recordFormat,\n error: extractStableCode(e) ?? \"CLI_PARSE_FAILED\",\n });\n }\n }\n\n const stdout = lines.map((l) => JSON.stringify(l)).join(\"\\n\") + \"\\n\";\n const exit = failed > 0 ? EXIT.DATAERR : EXIT.OK;\n const stderr = quiet\n ? \"\"\n : `cosyte: parsed ${String(records.length)} ${recordFormat} record(s)` +\n ` (${String(warnings)} warning(s), ${String(failed)} failed)` +\n (ndjson ? \" [ndjson]\" : format === \"mllp\" ? \" [mllp]\" : \"\") +\n \"\\n\";\n return { stdout, stderr, exit };\n}\n\n/** Split input bytes into non-empty, whitespace-trimmed newline-delimited records (NDJSON input). */\nfunction splitLines(bytes: Uint8Array): Uint8Array[] {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n const enc = new TextEncoder();\n return text\n .split(/\\r?\\n/)\n .filter((line) => line.trim().length > 0)\n .map((line) => enc.encode(line));\n}\n","/**\n * `cosyte redact <file|-> [--format …]` (alias `cosyte deid …`): the command whose *job* is to strip\n * PHI, emitting a de-identified copy of the parsed model.\n *\n * **It is deliberately not implemented yet.** De-identification belongs to **`@cosyte/deid`**, which\n * the CLI does not wire yet, and the wrapped parsers expose no de-id API to delegate to. A\n * built-in \"minimal Safe-Harbor\" pass over only the obvious PHI loci would leave PHI behind and\n * present a **false-safety impression**: the cardinal hazard `redact` exists to avoid. So this\n * command is an **honest, typed `CLI_NOT_IMPLEMENTED`** (never a fake success, never a partial scrub\n * dressed up as de-identified), gated on the de-identification seam in `core/deid.ts`.\n *\n * To keep that guarantee airtight, the command **never reads the input**: it consults\n * {@link deidStatus} first, and (while de-id is unavailable) reports the value-free reason and exits\n * `EX_UNAVAILABLE` (`69`) without ever touching the file's bytes. The command surface (positional\n * `<file|->`, `--format`) already exists so wiring `@cosyte/deid` later is additive.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES } from \"../core/diagnostics.js\";\nimport { deidStatus } from \"../core/deid.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunResult } from \"../core/result.js\";\n\n/** The flags `redact`/`deid` will honour once de-id is wired; parsed now for a stable command surface. */\nconst REDACT_OPTIONS = {\n format: { type: \"string\" },\n} as const;\n\n/**\n * Run the `redact` / `deid` command.\n *\n * @param args - The arguments after the `redact`/`deid` subcommand token.\n * @returns A {@link RunResult}. While `@cosyte/deid` is unavailable: empty `stdout`, a value-free\n * `CLI_NOT_IMPLEMENTED` diagnostic on `stderr`, and exit `EX_UNAVAILABLE` (`69`). A malformed\n * invocation (an unknown flag) is a usage error (exit `2`). The input is **never read**.\n * @example\n * ```ts\n * import { redactCommand } from \"@cosyte/cli\";\n *\n * const r = redactCommand([\"message.hl7\"]);\n * r.exit; // => 69\n * ```\n */\nexport function redactCommand(args: string[]): RunResult {\n // Validate the invocation for a stable surface (a bad flag is a usage error), but do NOT read the\n // input: while de-identification is unavailable there is nothing safe to do with the bytes.\n try {\n parseArgs({ args, options: REDACT_OPTIONS, allowPositionals: true });\n } catch {\n return {\n stdout: \"\",\n stderr: `cosyte: ${CLI_CODES.CLI_USAGE}: invalid arguments to \\`redact\\` (see \\`cosyte --help\\`)\\n`,\n exit: EXIT.USAGE,\n };\n }\n\n const status = deidStatus();\n // `available` is `false` until `@cosyte/deid` is wired (the only reachable branch today). Report the\n // value-free reason and a distinct non-zero exit, never a fake success, never a partial scrub.\n return {\n stdout: \"\",\n stderr: `cosyte: ${CLI_CODES.CLI_NOT_IMPLEMENTED}: ${status.reason}\\n`,\n exit: EXIT.UNAVAILABLE,\n };\n}\n","/**\n * `cosyte validate <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * Parse the input, run the **wrapped parser's own validation/conformance surface**, and let the\n * **exit code carry the verdict** so `cosyte validate` is usable as a CI gate: **`0` valid, `1`\n * invalid** (parseable but non-conformant), `65` unparseable, `66` no input, `2` usage. The\n * load-bearing rule: the CLI never prints a reassuring line and exits `0` on an invalid message.\n *\n * Findings are **value-free**: a stable code, a severity, and a positional locator (a FHIRPath, or an\n * HL7 segment/field index), never a field value. By default they render on **stderr**; `--json`\n * emits the same value-free verdict + findings as machine JSON on stdout. The CLI invents **no**\n * verdict of its own: FHIR validity is `@cosyte/fhir`'s `validateResource().valid` (plus any\n * error-severity read issue); HL7 validity is \"parseable\": its parser is Postel's-Law lenient and its\n * warnings are, by the library's design, non-fatal deviations (surfaced, never failing).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { validateFormat, type Verdict } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `validate` understands. */\nconst VALIDATE_OPTIONS = {\n format: { type: \"string\" },\n profile: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** Severities that make a resource **invalid** (exit `1`). Warnings/information never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/**\n * Run the `validate` command.\n *\n * @param args - The arguments after the `validate` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; a validation verdict is always value-free).\n * @returns A {@link RunResult} whose **exit code carries the verdict** (`0` valid / `1` invalid /\n * `65` unparseable / `66` no input / `2` usage). Value-free findings on `stderr`, or value-free\n * JSON on stdout under `--json`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { validateCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await validateCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function validateCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n profile?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: VALIDATE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `validate` (see `cosyte validate --help`)\",\n ),\n );\n }\n\n // Profile-based validation is a pass-through to the wrapped library's profile surface, but the CLI\n // bundles no profiles and cannot yet load one, so honouring `--profile` today would either fake a\n // verdict or silently ignore the flag (falsely implying a profile was applied). Both are forbidden\n // (ADR 0018): report a value-free \"unavailable\" and exit 69, without reading the input.\n if (values.profile !== undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_NOT_IMPLEMENTED,\n EXIT.UNAVAILABLE,\n \"profile-based validation is not yet available: the CLI bundles no profiles and cannot yet \" +\n \"load one; validating against `--profile` is gated on that surface. Re-run without --profile \" +\n \"for base validation.\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"validate\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let verdict: Verdict;\n try {\n verdict = await validateFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n // Unparseable input is a data error (65), NOT an invalid verdict (1): the tool could not run the\n // check at all. Value-free; the opt-in excerpt flows through the single core/wrap chokepoint.\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const exit = verdict.valid ? EXIT.OK : EXIT.INVALID;\n\n if (values.json === true) {\n // Machine output on the data channel: value-free (codes/severities/locations only).\n const body = { format, valid: verdict.valid, findings: verdict.findings };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n if (values.quiet === true) {\n // CI mode: the exit code is the whole signal. No stderr noise.\n return { stdout: \"\", stderr: \"\", exit };\n }\n\n return { stdout: \"\", stderr: renderReport(format, verdict), exit };\n}\n\n/** Render the value-free human report: one line per finding + a verdict summary line. */\nfunction renderReport(format: CosyteFormat, verdict: Verdict): string {\n const lines = verdict.findings.map(\n (f) => `cosyte: validate: ${f.severity} ${f.code} at ${f.location}\\n`,\n );\n const errors = verdict.findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = verdict.findings.length - errors;\n const summary = verdict.valid\n ? `cosyte: validate: ${format} is valid (${String(verdict.findings.length)} finding(s))\\n`\n : `cosyte: validate: ${format} is INVALID (${String(errors)} error(s), ${String(others)} other finding(s))\\n`;\n return lines.join(\"\") + summary;\n}\n","/**\n * The top-level **subcommand dispatcher**: a small hand-rolled router over Node's built-in\n * `util.parseArgs`, deliberately **third-party-framework-free** so the CLI core keeps zero third-party\n * runtime dependencies. It maps `argv[0]` to a command handler, serves `--help`\n * and `--version`, and turns any unexpected exception into a value-free `CLI_INTERNAL` result so a\n * stack trace carrying input can never reach the terminal.\n *\n * @packageDocumentation\n */\n\nimport { completionCommand } from \"../commands/completion.js\";\nimport { convertCommand } from \"../commands/convert.js\";\nimport { fmtCommand } from \"../commands/fmt.js\";\nimport { inspectCommand } from \"../commands/inspect.js\";\nimport { mapCodesCommand } from \"../commands/map-codes.js\";\nimport { parseCommand } from \"../commands/parse.js\";\nimport { redactCommand } from \"../commands/redact.js\";\nimport { validateCommand } from \"../commands/validate.js\";\nimport { CLI_CODES, CliError, toCliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { RunDeps } from \"./io.js\";\nimport { extractPhiPosture } from \"./phi.js\";\nimport type { RunResult } from \"./result.js\";\nimport { VERSION } from \"./version.js\";\n\n/** The value-free `--help` text. Names commands, flags, and exit codes, never any input. */\nconst HELP = `cosyte: a PHI-safe developer CLI over the @cosyte/* healthcare parsers\n\nUsage:\n cosyte <command> [options]\n\nCommands:\n parse <file|-> Parse a healthcare message to typed JSON (format autodetected)\n validate <file|-> Validate a message; exit code carries the verdict (0 valid / 1 invalid)\n inspect <file|-> Print a value-free structural summary (segment/resource counts, type)\n fmt <file|-> Canonically re-serialize via the parser's spec-clean serializer\n convert <file|-> Convert HL7 v2 → FHIR R4 via @cosyte/transform (use --to fhir)\n map-codes <cmap|-> Translate a code through a BYO FHIR ConceptMap via @cosyte/terminology\n redact <file|-> De-identify a message (alias: deid): gated on @cosyte/deid, not yet wired\n mcp Start the stdio MCP server (agent front door; also the cosyte-mcp bin)\n completion <shell> Print a shell completion script (bash | zsh | fish)\n\nGlobal:\n -h, --help Show this help\n -V, --version Show the CLI version\n --unsafe-show-values Permit input values on stderr/diagnostics (PHI-exposing; off by default)\n\nCommon options (parse / validate / inspect / fmt):\n --format <fmt> Override autodetection: hl7 | fhir | dicom | x12 | ccda | ncpdp | astm | mllp\n (parse: hl7 fhir x12 astm ncpdp mllp · inspect: all · fmt: hl7 fhir x12 astm\n ccda ncpdp · validate: all but mllp; dicom/ccda parse & mllp fmt are deferred)\n --json Machine-readable JSON output (parse / validate / inspect / convert / map-codes)\n --ndjson Treat each non-empty input line as a record; emit NDJSON (parse; FHIR bulk data)\n --quiet Suppress value-free notes on stderr\n --no-color Disable ANSI colour\n\nconvert options:\n --to fhir The conversion target (required; only HL7 v2 → FHIR R4 today)\n\nmap-codes options (the positional is a BYO FHIR ConceptMap; a code is not PHI):\n --code <code> The source code to translate (required)\n --system <uri> The source code system (optional; selects the ConceptMap group)\n --version <v> The source code system version (optional)\n --display <d> The source display (optional)\n\nExit codes:\n 0 success / valid 65 data error (unparseable / undetected format)\n 1 invalid (validate) 66 no input (missing/unreadable file)\n 2 usage error 69 unavailable (a capability is not yet built, e.g. redact)\n 70 internal error\n\nPHI posture: the parsed model goes to stdout (the data channel you chose); every diagnostic on\nstderr is value-free (codes and positions only, never a field value) unless you pass the loud,\nopt-in --unsafe-show-values (which permits a bounded input excerpt in a failure diagnostic).\n`;\n\n/** True if `argv` requests help (`-h`/`--help` anywhere). */\nfunction wantsHelp(argv: readonly string[]): boolean {\n return argv.includes(\"--help\") || argv.includes(\"-h\");\n}\n\n/**\n * Run a full `cosyte` invocation as data.\n *\n * @param argv - The arguments after the program name (i.e. `process.argv.slice(2)`).\n * @param deps - Injected input readers ({@link RunDeps}).\n * @returns The {@link RunResult} to write to the process streams and exit with.\n * @example\n * ```ts\n * import { run } from \"@cosyte/cli\";\n *\n * const deps = { readFile: async () => new Uint8Array(), readStdin: async () => new Uint8Array() };\n * const { exit } = await run([\"--version\"], deps);\n * exit; // => 0\n * ```\n */\nexport async function run(argv: string[], deps: RunDeps): Promise<RunResult> {\n // Resolve the global, order-independent --unsafe-show-values flag once, and dispatch on the argv\n // with it removed so each command's own parseArgs never sees it (core/phi.ts).\n const { posture, argv: rest0 } = extractPhiPosture(argv);\n const [command, ...rest] = rest0;\n if (command === undefined || wantsHelp(rest0)) {\n return { stdout: HELP, stderr: \"\", exit: EXIT.OK };\n }\n if (command === \"--version\" || command === \"-V\") {\n return { stdout: `${VERSION}\\n`, stderr: \"\", exit: EXIT.OK };\n }\n\n try {\n switch (command) {\n case \"parse\":\n return await parseCommand(rest, deps, posture);\n case \"validate\":\n return await validateCommand(rest, deps, posture);\n case \"inspect\":\n return await inspectCommand(rest, deps, posture);\n case \"fmt\":\n return await fmtCommand(rest, deps, posture);\n case \"convert\":\n return await convertCommand(rest, deps, posture);\n case \"map-codes\":\n return await mapCodesCommand(rest, deps);\n case \"redact\":\n case \"deid\":\n return redactCommand(rest);\n case \"completion\":\n return completionCommand(rest);\n default:\n return resolve(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unknown command '${command}'; run \\`cosyte --help\\``,\n ),\n );\n }\n } catch (e) {\n return resolve(toCliError(e));\n }\n}\n\n/** Render a {@link CliError} as a value-free {@link RunResult}. */\nfunction resolve(e: CliError): RunResult {\n return { stdout: \"\", stderr: `cosyte: ${e.code}: ${e.message}\\n`, exit: e.exit };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/version.ts","../src/core/exit-codes.ts","../src/core/diagnostics.ts","../src/core/format.ts","../src/core/limits.ts","../src/core/findings.ts","../src/core/parsers.ts","../src/core/records.ts","../src/core/input.ts","../src/core/phi.ts","../src/core/wrap.ts","../src/core/io.ts","../src/core/deid.ts","../src/commands/completion.ts","../src/commands/convert.ts","../src/commands/fmt.ts","../src/commands/inspect.ts","../src/commands/map-codes.ts","../src/commands/parse.ts","../src/commands/redact.ts","../src/commands/validate.ts","../src/core/run.ts"],"names":["run","decode","ERROR_SEVERITIES","parseArgs"],"mappings":";;;;;AAyBO,IAAM,OAAA,GAAkB;;;ACgBxB,IAAM,IAAA,GAAO;AAAA;AAAA,EAElB,EAAA,EAAI,CAAA;AAAA;AAAA;AAAA;AAAA,EAIJ,OAAA,EAAS,CAAA;AAAA;AAAA;AAAA,EAGT,KAAA,EAAO,CAAA;AAAA;AAAA,EAEP,OAAA,EAAS,EAAA;AAAA;AAAA,EAET,OAAA,EAAS,EAAA;AAAA;AAAA;AAAA;AAAA,EAIT,WAAA,EAAa,EAAA;AAAA;AAAA,EAEb,QAAA,EAAU,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMV,KAAA,EAAO;AACT;;;ACvCO,IAAM,SAAA,GAAY;AAAA;AAAA,EAEvB,SAAA,EAAW,WAAA;AAAA;AAAA,EAEX,YAAA,EAAc,cAAA;AAAA;AAAA,EA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IAAA,EAAM,EAAE,IAAA,EAAK;AACjF","file":"index.mjs","sourcesContent":["/**\n * The CLI version string, synced with `package.json#version` on release by `scripts/sync-version.mjs`,\n * which the `version` script runs immediately after `changeset version`. Kept in its own module so\n * both the programmatic entry point and the dispatcher share one source of truth.\n *\n * The declaration below is rewritten by that script and is matched at column 0, annotation included.\n * Renaming it or reflowing it makes the script exit non-zero rather than silently no-op; the shape is\n * pinned by `test/sanity.test.ts`, and the value is compared against `package.json` there too.\n *\n * @packageDocumentation\n */\n\n/**\n * The `@cosyte/cli` version. On the uniform `v0.0.x-until-first-alpha` ladder.\n *\n * Read by `cosyte --version` and by the MCP server's advertised `SERVER_INFO`, so it is a\n * user-visible surface on both front doors, not merely an export.\n *\n * @example\n * ```ts\n * import { VERSION } from \"@cosyte/cli\";\n *\n * console.log(`cosyte ${VERSION}`);\n * ```\n */\nexport const VERSION: string = \"0.1.0\";\n","/**\n * The `cosyte` CLI **exit-code contract**: a designed, documented surface that CI pipelines and\n * shell scripts branch on. `0` is the conventional success status; the codes from `65` up are the\n * values the Unix `sysexits.h` header assigns to the constants named beside them; `1` and `2` are\n * this CLI's own, because that header defines no constant for either.\n *\n * The load-bearing rule: **the CLI never prints a reassuring line and exits `0` on input it could not\n * handle.** An undetectable format, an unreadable file, a parser that throws, or a consumer that\n * closed the output stream before the output arrived each map to a distinct, stable non-zero code,\n * never a silent success.\n *\n * | Code | Name | Meaning |\n * |------|------------|----------------------------------------------------------------------|\n * | `0` | `OK` | success: the operation completed; `validate` found the input **valid** |\n * | `1` | `INVALID` | operation-level failure: `validate` found the input **invalid**, or `redact` could not de-identify every locus (this CLI's own value; a real, expected CI signal: the tool worked, the operation did not complete) |\n * | `2` | `USAGE` | usage error: unknown command, bad flag, missing argument (this CLI's own value) |\n * | `65` | `DATAERR` | data error: input could not be parsed / format not detected (EX_DATAERR) |\n * | `66` | `NOINPUT` | no input: the file does not exist or is unreadable (EX_NOINPUT) |\n * | `69` | `UNAVAILABLE` | a required capability is not wired for this input: e.g. `redact` on a format `@cosyte/deid` has no adapter for (EX_UNAVAILABLE) |\n * | `70` | `SOFTWARE` | internal error: an unexpected exception, i.e. a bug (EX_SOFTWARE) |\n * | `74` | `IOERR` | output error: the output stream closed before the CLI had finished writing to it, the shape a downstream consumer that exits early produces (EX_IOERR) |\n *\n * The load-bearing `validate` rule: a **parseable-but-invalid** message is exit `1`, never exit `0`.\n * The CLI must never print a reassuring line and exit green on a bad message. Exit `65` is reserved\n * for input that could not be **parsed** at all (a distinct signal from \"parsed, but does not\n * conform\").\n *\n * @packageDocumentation\n */\n\n/**\n * The stable exit-code map. Adding a code is a documented, tested change to the CLI's contract;\n * renaming or repurposing one is a breaking change.\n *\n * @example\n * ```ts\n * import { EXIT } from \"@cosyte/cli\";\n *\n * process.exitCode = EXIT.OK; // => 0\n * ```\n */\nexport const EXIT = {\n /** Success: the operation completed; `validate` found the input **valid**. */\n OK: 0,\n /** Operation-level failure: `validate` found the input **invalid** (parseable but non-conformant),\n * or `redact` could not de-identify every locus: a real, expected CI signal that the tool worked\n * and the operation did not complete. Never emitted for unparseable input (that is `DATAERR`). */\n INVALID: 1,\n /** Usage error: unknown command, bad flag, missing argument. A value specific to this CLI, not a\n * `sysexits.h` constant. */\n USAGE: 2,\n /** Data error: input could not be parsed or its format could not be detected (`EX_DATAERR`). */\n DATAERR: 65,\n /** No input: the named file does not exist or is unreadable (`EX_NOINPUT`). */\n NOINPUT: 66,\n /** Unavailable: a required capability is not wired for this input (e.g. `redact` on a format\n * `@cosyte/deid` has no adapter for, or with that optional library absent), a distinct non-zero\n * signal that is never a fake success (`EX_UNAVAILABLE`). */\n UNAVAILABLE: 69,\n /** Internal error: an unexpected exception (a bug), distinct from a handled bad input (`EX_SOFTWARE`). */\n SOFTWARE: 70,\n /** Output error: the stream the CLI was writing to closed before the output had been delivered, so\n * the consumer holds nothing or holds only part of the answer. The shape a downstream consumer\n * that exits early produces (a pager quit, a `head` that has seen enough). A handled condition the\n * consumer owns, never a defect in the CLI, so it is deliberately distinct from `SOFTWARE`\n * (`EX_IOERR`). */\n IOERR: 74,\n} as const;\n\n/**\n * A value from {@link EXIT}: the exit code a CLI invocation resolves to.\n */\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n","/**\n * The CLI's **value-free diagnostic channel**. Every error the CLI raises on its own behalf carries a\n * stable `CLI_*` code, a fixed exit code, and a **PHI-safe** message built only from positional /\n * structural context: a segment or field index, a byte offset, a file path, a format name, a warning\n * code. **A diagnostic never echoes an input value** (a name, a DOB, an MRN, a result). This is the\n * parsers' \"warning = code + position, never a value\" rule applied at the CLI edge.\n *\n * @packageDocumentation\n */\n\nimport { EXIT, type ExitCode } from \"./exit-codes.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Stable **CLI diagnostic code** registry: errors the CLI owns (routing, I/O, argument handling),\n * distinct from the wrapped library's own warning/issue codes which are passed through unchanged.\n * Each code is its own value (`key === value`) so the set survives `Object.values(...)`; renaming or\n * removing one is a **breaking change** because scripts branch on the stderr text.\n *\n * @example\n * ```ts\n * import { CLI_CODES } from \"@cosyte/cli\";\n *\n * if (diagnostic.code === CLI_CODES.CLI_FORMAT_UNDETECTED) {\n * // ask the user for --format\n * }\n * ```\n */\nexport const CLI_CODES = {\n /** A required argument was missing or a flag was invalid. Exit `2`. */\n CLI_USAGE: \"CLI_USAGE\",\n /** The named file does not exist or could not be read. Exit `66`. */\n CLI_NO_INPUT: \"CLI_NO_INPUT\",\n /** The input was empty, no bytes to detect or parse. Exit `65`. */\n CLI_EMPTY_INPUT: \"CLI_EMPTY_INPUT\",\n /** No format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_UNDETECTED: \"CLI_FORMAT_UNDETECTED\",\n /** More than one format signature matched; the CLI will not guess. Names the candidates, never the bytes. Exit `65`. */\n CLI_FORMAT_AMBIGUOUS: \"CLI_FORMAT_AMBIGUOUS\",\n /** A recognised format whose parser does not support the requested operation (e.g. `parse` on a\n * format wired only for `inspect`). Names the format + operation, never the bytes. Exit `65`. */\n CLI_FORMAT_UNSUPPORTED: \"CLI_FORMAT_UNSUPPORTED\",\n /** The optional parser package for a recognised format is not installed. The six breadth parsers\n * (dicom/x12/ccda/ncpdp/astm/mllp) are `optionalDependencies`: normally installed, but if\n * one is absent the CLI degrades to this value-free signal rather than crashing. Exit `69`. */\n CLI_PARSER_UNAVAILABLE: \"CLI_PARSER_UNAVAILABLE\",\n /** The wrapped parser rejected the input. Positional context only, never the offending bytes. Exit `65`. */\n CLI_PARSE_FAILED: \"CLI_PARSE_FAILED\",\n /** The input is larger than the documented size limit the CLI reads in one invocation. Raised\n * against the running byte count while the input is read, so the refusal always arrives before an\n * allocation ceiling could. Names the limit, never the input. Exit `65`, never `70`. */\n CLI_INPUT_TOO_LARGE: \"CLI_INPUT_TOO_LARGE\",\n /** The output stream could not be written: a consumer that closes the pipe ends the invocation\n * here rather than as an unhandled platform error, whether it went away part way through a record\n * stream or before a single-result write was delivered. Names no input, and never the platform's\n * own error text. Exit `74`. */\n CLI_OUTPUT_WRITE_FAILED: \"CLI_OUTPUT_WRITE_FAILED\",\n /** The BYO ConceptMap supplied to `map-codes` is not valid JSON or not a loadable FHIR ConceptMap.\n * Names the stable terminology-loader code, never the map's bytes. Exit `65`. */\n CLI_MAP_INVALID: \"CLI_MAP_INVALID\",\n /** A command whose ground-layer library does not cover the resolved format (e.g. `redact` on a\n * format `@cosyte/deid` ships no adapter for). Never a fake success: a distinct, value-free\n * \"unavailable\" signal. Exit `69`. */\n CLI_NOT_IMPLEMENTED: \"CLI_NOT_IMPLEMENTED\",\n /** The delegated de-identifier reported that it could not handle every element of the input (a\n * fail-closed `blocked` locus, or its own fatal). The run is **not** a de-identified copy, so no\n * output is emitted: an operation-level failure, never a bug. Names loci and codes, never a\n * value. Exit `1`. */\n CLI_DEID_INCOMPLETE: \"CLI_DEID_INCOMPLETE\",\n /** An unexpected internal error (a bug). Exit `70`. */\n CLI_INTERNAL: \"CLI_INTERNAL\",\n} as const;\n\n/**\n * A value from {@link CLI_CODES}: the stable code carried by a {@link CliError}.\n */\nexport type CliCode = (typeof CLI_CODES)[keyof typeof CLI_CODES];\n\n/**\n * A typed, PHI-safe CLI error. Its {@link CliError.message | message} is **value-free by\n * construction**: callers must build it from codes, indices, offsets, format names, and file paths,\n * never from an input value. It carries the {@link ExitCode} the invocation resolves to.\n *\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT } from \"@cosyte/cli\";\n *\n * throw new CliError(CLI_CODES.CLI_NO_INPUT, EXIT.NOINPUT, \"cannot read the named file\");\n * ```\n */\nexport class CliError extends Error {\n /** The stable diagnostic code. */\n public readonly code: CliCode;\n /** The exit code this error resolves the invocation to. */\n public readonly exit: ExitCode;\n\n /**\n * @param code - A stable {@link CliCode}.\n * @param exit - The {@link ExitCode} to resolve to.\n * @param message - A **value-free** explanation (positional/structural context only, never PHI).\n */\n public constructor(code: CliCode, exit: ExitCode, message: string) {\n super(message);\n this.name = \"CliError\";\n this.code = code;\n this.exit = exit;\n }\n}\n\n/**\n * Render a {@link CliError} as a single value-free `stderr` line: `cosyte: <CODE>: <message>`. The\n * message is already value-free by the {@link CliError} contract; this only prefixes the tool name\n * and the code so scripts and humans can branch on a stable token.\n *\n * @param err - The CLI error to render.\n * @returns The stderr line (no trailing newline).\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, formatDiagnostic } from \"@cosyte/cli\";\n *\n * formatDiagnostic(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file> argument\"));\n * // => \"cosyte: CLI_USAGE: missing <file> argument\"\n * ```\n */\nexport function formatDiagnostic(err: CliError): string {\n return `cosyte: ${err.code}: ${err.message}`;\n}\n\n/**\n * Resolve a {@link CliError} into a value-free {@link RunResult}: empty `stdout` (nothing reaches the\n * data channel on an error), the rendered diagnostic on `stderr`, and the error's exit code. The\n * single place the CLI turns an owned error into a result, so every command and the dispatcher render\n * errors identically.\n *\n * @param err - The CLI error to resolve.\n * @returns The value-free {@link RunResult}.\n * @example\n * ```ts\n * import { CliError, CLI_CODES, EXIT, errorResult } from \"@cosyte/cli\";\n *\n * errorResult(new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"missing <file>\")).exit; // => 2\n * ```\n */\nexport function errorResult(err: CliError): RunResult {\n return { stdout: \"\", stderr: `${formatDiagnostic(err)}\\n`, exit: err.exit };\n}\n\n/**\n * Coerce an unknown thrown value into a {@link CliError}. A {@link CliError} passes through; anything\n * else becomes a `CLI_INTERNAL` / {@link EXIT.SOFTWARE} error whose message is a **fixed, value-free\n * string**: the original message is deliberately discarded so a parser exception that embedded input\n * bytes can never reach stderr.\n *\n * @param err - The caught value.\n * @returns A {@link CliError} safe to render to stderr.\n * @example\n * ```ts\n * import { toCliError } from \"@cosyte/cli\";\n *\n * toCliError(new Error(\"boom\")).code; // => \"CLI_INTERNAL\"\n * ```\n */\nexport function toCliError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n return new CliError(\n CLI_CODES.CLI_INTERNAL,\n EXIT.SOFTWARE,\n \"an unexpected internal error occurred (no input is echoed)\",\n );\n}\n","/**\n * **Content-based format autodetection**: the feature that makes `cosyte parse <file>` feel magic,\n * and the one that must **fail safe**. Detection sniffs the leading bytes' *content*, never the file\n * extension: a `.txt` full of `MSH|^~\\&…` is HL7; a `.json` with a `resourceType` is FHIR.\n *\n * The hazard is a wrong sniff routing bytes to the wrong parser and yielding confident garbage. So\n * detection is **conservative**: a single confident signature match parses; **zero or more than one**\n * match is *not* a guess. It is a typed `none`/`ambiguous` result the caller turns into a data-error\n * exit asking for `--format`. This is the parsers' \"never a confident wrong value\" rule at the\n * routing layer.\n *\n * All eight cosyte formats carry a signature: **hl7** (`MSH` + field separator), **mllp**\n * (a leading `0x0B` VT frame byte: an MLLP-framed stream, de-framed to its enclosed HL7), **fhir** (a\n * JSON object declaring `resourceType`), **x12** (a leading `ISA` interchange header), **astm** (a\n * leading `H` record whose second byte is the field delimiter), **ccda** (a `<ClinicalDocument>` root),\n * **ncpdp** (a `<Message>` root in the NCPDP SCRIPT namespace), and **dicom** (the `DICM` magic at byte\n * 128). The signatures are **conservative and, on realistic inputs, mutually exclusive**: the\n * distinctive-lead formats (`MSH`, `ISA`, `H`+delimiter, `<ClinicalDocument>`, `<Message>`+ncpdp, the\n * `DICM` magic, `0x0B` VT, `{…\"resourceType\"`) don't overlap on a real message of any one type. They\n * are **not** disjoint in the absolute sense: a pathological input could satisfy two (an MLLP frame\n * enclosing a `<ClinicalDocument>` payload matches both `mllp` and `ccda`; a text file whose byte 128\n * is `DICM` matches both), which is exactly why the **`ambiguous` branch is load-bearing, not dead\n * code**: any co-match is a *detected* ambiguity (a value-free data error asking for `--format`),\n * **never a silent mis-route**.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\n\n/** The set of formats the `cosyte` command names. */\nexport type CosyteFormat = \"hl7\" | \"fhir\" | \"dicom\" | \"x12\" | \"ccda\" | \"ncpdp\" | \"astm\" | \"mllp\";\n\n/**\n * How confident autodetection is:\n * - `certain`: exactly one signature matched (`format` names it);\n * - `ambiguous`: more than one matched (`format` is `null`; `candidates` names them);\n * - `none`: nothing matched (`format` is `null`; `candidates` is empty).\n *\n * `format` is `null` unless `confidence` is `certain`, so a non-certain result can never be mistaken\n * for a routable format.\n */\nexport interface DetectResult {\n /** The detected format, or `null` when `confidence` is not `certain`. */\n readonly format: CosyteFormat | null;\n /** The detection confidence. */\n readonly confidence: \"certain\" | \"ambiguous\" | \"none\";\n /** The matching candidate formats (0 for `none`, 1 for `certain`, ≥2 for `ambiguous`). Value-free. */\n readonly candidates: readonly CosyteFormat[];\n}\n\n/** A single format signature: a value-free predicate over the input's decoded prefix + raw bytes. */\ninterface Signature {\n readonly format: CosyteFormat;\n readonly match: (prefix: string, bytes: Uint8Array) => boolean;\n}\n\n/**\n * How many leading bytes detection reads. Small: every signature lives in the first line (the\n * deepest is DICOM's magic at byte 128). Exported because a **streaming** caller has to know how much\n * of the input to hold back before it can detect the format, and reading a different amount than\n * detection uses would make the two disagree.\n *\n * @example\n * ```ts\n * import { DETECT_PREFIX_BYTES } from \"@cosyte/cli\";\n *\n * DETECT_PREFIX_BYTES; // => 512\n * ```\n */\nexport const DETECT_PREFIX_BYTES = 512;\n\n/** How many leading bytes to decode for text sniffing. Small: signatures live in the first line. */\nconst SNIFF_BYTES = DETECT_PREFIX_BYTES;\n\n/** Strip a leading UTF-8 BOM and any leading ASCII whitespace for a tolerant sniff. Deliberately does\n * **not** strip the MLLP `0x0B` VT frame byte (`\\v`): that byte is the mllp signature, so consuming it\n * here would collide the hl7 and mllp signatures on a framed message. */\nfunction leadingText(bytes: Uint8Array): string {\n const slice = bytes.subarray(0, SNIFF_BYTES);\n let text = new TextDecoder(\"utf-8\", { fatal: false }).decode(slice);\n if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);\n return text;\n}\n\n/** Trim only regular leading whitespace (space/tab/CR/LF/FF), never the `0x0B` VT MLLP frame byte. */\nfunction trimLeading(prefix: string): string {\n return prefix.replace(/^[ \\t\\r\\n\\f]+/, \"\");\n}\n\n/** True iff `ch` is a single printable, non-alphanumeric byte usable as a wire delimiter (e.g. `|`, `*`). */\nfunction isDelimiter(ch: string | undefined): boolean {\n if (ch === undefined) return false;\n const code = ch.charCodeAt(0);\n return code > 0x20 && code < 0x7f && !/[A-Za-z0-9]/.test(ch);\n}\n\n/**\n * HL7 v2: the message begins with an `MSH` segment whose 4th character is the field separator\n * (conventionally `|`) followed by the encoding characters. Conservative: requires `MSH` + a\n * non-alphanumeric single-char field separator. An MLLP-framed message (leading `0x0B`) is **not**\n * claimed here (it is the `mllp` signature) because {@link trimLeading} preserves the VT byte.\n */\nfunction looksLikeHl7(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"MSH\") && isDelimiter(s[3]);\n}\n\n/**\n * MLLP: a Minimal Lower Layer Protocol frame opens with the `0x0B` VT byte. This is a **transport\n * framing**, not a document format: the CLI de-frames it and parses the enclosed HL7 v2 payload(s).\n * The check is on the **raw first byte**, so it is disjoint from every text signature.\n */\nfunction looksLikeMllp(_prefix: string, bytes: Uint8Array): boolean {\n return bytes[0] === 0x0b;\n}\n\n/**\n * FHIR: a JSON object whose first non-whitespace byte is `{` and which declares a string-valued\n * top-level `resourceType` member near the top. Conservative: both the object framing and the\n * `resourceType` key must be present, so a bare JSON object without it is not claimed as FHIR.\n */\nfunction looksLikeFhir(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"{\")) return false;\n return /\"resourceType\"\\s*:\\s*\"/.test(s);\n}\n\n/**\n * X12 EDI: an interchange opens with the fixed 3-byte `ISA` segment id immediately followed by the\n * element separator (a non-alphanumeric byte: `*` conventionally, but delimiter-agnostic).\n */\nfunction looksLikeX12(prefix: string): boolean {\n const s = trimLeading(prefix);\n return s.startsWith(\"ISA\") && isDelimiter(s[3]);\n}\n\n/**\n * ASTM E1394/E1381 records: the first record is an `H` (header) whose second byte is the field\n * delimiter and whose next three bytes are the repeat / component / escape **delimiter declarations**\n * (all punctuation: classically `\\^&`). Requiring the full 4-delimiter block, not just `H` + one\n * delimiter, keeps a mundane `H:...`/`H!...` text line from being confidently mis-routed to ASTM (it\n * would instead be a value-free `CLI_FORMAT_UNDETECTED`). Distinct from HL7 (`MSH`) and X12 (`ISA`).\n */\nfunction looksLikeAstm(prefix: string): boolean {\n const s = trimLeading(prefix);\n if (!s.startsWith(\"H\") || s.length < 5) return false;\n // s[1] = field delimiter; s[2..4] = the repeat/component/escape delimiter declarations.\n return isDelimiter(s[1]) && isDelimiter(s[2]) && isDelimiter(s[3]) && isDelimiter(s[4]);\n}\n\n/** C-CDA: an HL7 v3 CDA document rooted at `<ClinicalDocument>` (XML). */\nfunction looksLikeCcda(prefix: string): boolean {\n return /<ClinicalDocument[\\s>]/.test(prefix);\n}\n\n/**\n * NCPDP SCRIPT: an ePrescribing message rooted at `<Message>` in the NCPDP SCRIPT namespace.\n * Requires **both** the `<Message>` root and the `ncpdp` namespace marker so a generic `<Message>`\n * XML is not mis-claimed (conservative: disjoint from C-CDA's `<ClinicalDocument>`).\n */\nfunction looksLikeNcpdp(prefix: string): boolean {\n return /<Message[\\s>]/.test(prefix) && /ncpdp/i.test(prefix);\n}\n\n/** DICOM Part 10: the `DICM` magic sits at byte offset 128, after the 128-byte preamble. */\nfunction looksLikeDicom(_prefix: string, bytes: Uint8Array): boolean {\n if (bytes.length < 132) return false;\n return (\n bytes[128] === 0x44 && bytes[129] === 0x49 && bytes[130] === 0x43 && bytes[131] === 0x4d // \"DICM\"\n );\n}\n\n/** The signature registry: disjoint by construction across all eight cosyte formats. */\nconst SIGNATURES: readonly Signature[] = [\n { format: \"hl7\", match: (prefix) => looksLikeHl7(prefix) },\n { format: \"mllp\", match: (prefix, bytes) => looksLikeMllp(prefix, bytes) },\n { format: \"fhir\", match: (prefix) => looksLikeFhir(prefix) },\n { format: \"x12\", match: (prefix) => looksLikeX12(prefix) },\n { format: \"astm\", match: (prefix) => looksLikeAstm(prefix) },\n { format: \"ccda\", match: (prefix) => looksLikeCcda(prefix) },\n { format: \"ncpdp\", match: (prefix) => looksLikeNcpdp(prefix) },\n { format: \"dicom\", match: (prefix, bytes) => looksLikeDicom(prefix, bytes) },\n];\n\n/** The formats content-autodetection can recognise (every format now carries a signature). */\nexport const DETECTABLE_FORMATS: readonly CosyteFormat[] = SIGNATURES.map((s) => s.format);\n\n/**\n * Detect the healthcare format of `bytes` by content, conservatively.\n *\n * @param bytes - The input bytes (a whole file or a stdin buffer). Only the leading prefix is sniffed.\n * @returns A {@link DetectResult}: `certain` + a `format` on a single match, else `ambiguous`/`none`\n * with `format: null` and the value-free `candidates` list. **Never guesses.**\n * @example\n * ```ts\n * import { detectFormat } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * detectFormat(enc.encode(\"MSH|^~\\\\&|A|B\\r\")).format; // => \"hl7\"\n * detectFormat(enc.encode('{\"resourceType\":\"Patient\"}')).format; // => \"fhir\"\n * detectFormat(enc.encode(\"hello\")).confidence; // => \"none\"\n * ```\n */\nexport function detectFormat(bytes: Uint8Array): DetectResult {\n if (bytes.length === 0) return classifyCandidates([]);\n const prefix = leadingText(bytes);\n const candidates = SIGNATURES.filter((sig) => sig.match(prefix, bytes)).map((sig) => sig.format);\n return classifyCandidates(candidates);\n}\n\n/**\n * Classify a list of matched candidate formats into a {@link DetectResult}: exactly one → `certain`,\n * zero → `none`, two-or-more → `ambiguous` (all with `format` `null` unless certain). Split out and\n * exported so the **ambiguity** contract is directly testable. It is otherwise unreachable while\n * every signature is disjoint, and it must stay a *detected* ambiguity, never a mis-route.\n *\n * @param candidates - The formats whose signatures matched the input.\n * @returns The classified {@link DetectResult}.\n * @example\n * ```ts\n * import { classifyCandidates } from \"@cosyte/cli\";\n *\n * classifyCandidates([\"hl7\"]).confidence; // => \"certain\"\n * classifyCandidates([]).confidence; // => \"none\"\n * classifyCandidates([\"hl7\", \"fhir\"]).confidence; // => \"ambiguous\"\n * ```\n */\nexport function classifyCandidates(candidates: readonly CosyteFormat[]): DetectResult {\n const [first, second] = candidates;\n if (second !== undefined) return { format: null, confidence: \"ambiguous\", candidates };\n if (first !== undefined) return { format: first, confidence: \"certain\", candidates };\n return { format: null, confidence: \"none\", candidates: [] };\n}\n\n/**\n * Build the value-free {@link CliError} for a **non-certain** detection: the data error the caller\n * returns instead of guessing a parser. `ambiguous` names the matching candidates (a value-free code\n * list); `none` asks for `--format`. Both map to the data-error exit (`65`). Never echoes input bytes.\n *\n * @param detected - A {@link DetectResult} whose `format` is `null` (i.e. not `certain`).\n * @returns A value-free `CLI_FORMAT_AMBIGUOUS` or `CLI_FORMAT_UNDETECTED` error.\n * @example\n * ```ts\n * import { classifyCandidates, detectionError } from \"@cosyte/cli\";\n *\n * detectionError(classifyCandidates([])).code; // => \"CLI_FORMAT_UNDETECTED\"\n * detectionError(classifyCandidates([\"hl7\", \"fhir\"])).code; // => \"CLI_FORMAT_AMBIGUOUS\"\n * ```\n */\nexport function detectionError(detected: DetectResult): CliError {\n if (detected.confidence === \"ambiguous\") {\n return new CliError(\n CLI_CODES.CLI_FORMAT_AMBIGUOUS,\n EXIT.DATAERR,\n `input matched multiple formats (${detected.candidates.join(\", \")}); disambiguate with --format`,\n );\n }\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNDETECTED,\n EXIT.DATAERR,\n `could not detect the input format; re-run with --format (detectable: ${DETECTABLE_FORMATS.join(\", \")})`,\n );\n}\n\n/** The full set of format names `--format` accepts as syntactically valid (a bad value is a usage error). */\nexport const KNOWN_FORMATS: readonly CosyteFormat[] = [\n \"hl7\",\n \"fhir\",\n \"dicom\",\n \"x12\",\n \"ccda\",\n \"ncpdp\",\n \"astm\",\n \"mllp\",\n];\n\n/**\n * Narrow an arbitrary `--format` string to a {@link CosyteFormat}, or `null` if it is not a known\n * format name (which the caller turns into a usage error, exit `2`).\n *\n * @param value - The raw `--format` argument.\n * @returns The narrowed format, or `null`.\n * @example\n * ```ts\n * import { asCosyteFormat } from \"@cosyte/cli\";\n *\n * asCosyteFormat(\"hl7\"); // => \"hl7\"\n * asCosyteFormat(\"nope\"); // => null\n * ```\n */\nexport function asCosyteFormat(value: string): CosyteFormat | null {\n return (KNOWN_FORMATS as readonly string[]).includes(value) ? (value as CosyteFormat) : null;\n}\n","/**\n * The CLI's **own input-size ceiling**, and the value-free refusal it raises.\n *\n * Node has two hard allocation ceilings a byte pipeline can walk into: a single `Buffer` cannot\n * exceed `buffer.constants.MAX_LENGTH` and a single string cannot exceed\n * `buffer.constants.MAX_STRING_LENGTH`. Crossing either raises a *platform* exception, which is\n * indistinguishable, at the CLI edge, from a bug: it would be reported as an internal error even\n * though the input was merely large. That is a lie about whose fault it is, and it is the reason this\n * module exists.\n *\n * So the CLI declares a limit of its **own**, far below both ceilings, checks it against the\n * **running total as input is read** (never after a whole oversized input has been assembled), and\n * refuses an over-limit invocation with a stable, value-free diagnostic and the **data-error** exit\n * code. The number is a documented part of the command surface: it is stated in `cosyte --help` and\n * in the command reference, and both are rendered from {@link MAX_INPUT_BYTES} so they cannot drift.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\n\n/** Bytes in one mebibyte: the unit the human half of the limit text is expressed in. */\nconst BYTES_PER_MIB = 1024 * 1024;\n\n/**\n * The maximum number of input bytes `cosyte parse` reads in one invocation: **67108864 bytes\n * (64 MiB)**.\n *\n * Chosen to sit far below the smaller of Node's two allocation ceilings\n * (`buffer.constants.MAX_STRING_LENGTH`, 536870888 characters), because the bytes read are not the\n * peak: a parsed model rendered as JSON is routinely several times the size of the input that\n * produced it, so the limit has to leave room for the output as well as the input. A power of two, so\n * the byte count and its mebibyte rendering are both exact.\n *\n * @example\n * ```ts\n * import { MAX_INPUT_BYTES } from \"@cosyte/cli\";\n *\n * MAX_INPUT_BYTES; // => 67108864\n * ```\n */\nexport const MAX_INPUT_BYTES = 64 * BYTES_PER_MIB;\n\n/**\n * Render a byte limit as a **concrete number with an explicit byte-based unit**: `\"67108864 bytes\n * (64 MiB)\"`. Every surface that states the limit (the refusal diagnostic, `cosyte --help`, the\n * command reference) renders it through here, so the number a user reads is always the number the\n * code enforces, and never a vague description of one.\n *\n * @param limit - The limit in bytes. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns The limit as bytes, plus a mebibyte rendering when it is a whole number of mebibytes.\n * @example\n * ```ts\n * import { describeByteLimit } from \"@cosyte/cli\";\n *\n * describeByteLimit(67108864); // => \"67108864 bytes (64 MiB)\"\n * describeByteLimit(1000); // => \"1000 bytes\"\n * ```\n */\nexport function describeByteLimit(limit: number = MAX_INPUT_BYTES): string {\n const mib = limit / BYTES_PER_MIB;\n return Number.isInteger(mib)\n ? `${String(limit)} bytes (${String(mib)} MiB)`\n : `${String(limit)} bytes`;\n}\n\n/**\n * Build the value-free over-limit refusal: a stable `CLI_INPUT_TOO_LARGE` code, the **data-error**\n * exit (`65`, never the internal-error `70`), and a message that names the limit and nothing else.\n * The offending input's own size is deliberately not reported either: the limit is the actionable\n * fact, and a size read off the input is a property of the input.\n *\n * @param limit - The limit that was exceeded, in bytes. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns The value-free {@link CliError} to resolve the invocation with.\n * @example\n * ```ts\n * import { inputTooLargeError } from \"@cosyte/cli\";\n *\n * inputTooLargeError().exit; // => 65\n * inputTooLargeError().code; // => \"CLI_INPUT_TOO_LARGE\"\n * ```\n */\nexport function inputTooLargeError(limit: number = MAX_INPUT_BYTES): CliError {\n return new CliError(\n CLI_CODES.CLI_INPUT_TOO_LARGE,\n EXIT.DATAERR,\n `input is larger than the ${describeByteLimit(limit)} this command reads in one ` +\n `invocation; split the input and re-run`,\n );\n}\n","/**\n * The CLI's **value-free finding** shape and the positional locators that populate it. A finding says\n * *what kind* of thing was observed (a stable code + severity) and *where* (a positional locator),\n * **never** the offending value. Shared by `validate` (conformance findings) and\n * `inspect` (structural summary) so both render locations identically and value-free.\n *\n * @packageDocumentation\n */\n\n/**\n * A single value-free finding: a stable code, a severity, and a positional locator. Every field is\n * safe to print, log, or serialize. None carries a name, DOB, MRN, or field value.\n */\nexport interface Finding {\n /** The stable diagnostic/warning code (the wrapped library's or the CLI's). */\n readonly code: string;\n /** The R4-style severity (`fatal` | `error` | `warning` | `information`), or `warning` for HL7. */\n readonly severity: string;\n /** A value-free positional locator: a FHIRPath expression, or an HL7 segment/field index path. */\n readonly location: string;\n}\n\n/** The minimal, value-free positional shape shared by HL7 warnings (indices only, never a value). */\ninterface Hl7PositionLike {\n readonly segmentIndex: number;\n readonly fieldIndex?: number;\n readonly repetitionIndex?: number;\n readonly componentIndex?: number;\n readonly subcomponentIndex?: number;\n}\n\n/**\n * Render an HL7 warning position as a **value-free** locator string built only from its numeric\n * indices: e.g. `seg[3].field[5].comp[1]`. No segment content, no field value, ever appears; only the\n * structural coordinates the parser reported.\n *\n * @param pos - The HL7 position (segment/field/repetition/component/subcomponent indices).\n * @returns A value-free locator, e.g. `\"seg[3].field[5]\"`.\n * @example\n * ```ts\n * import { formatHl7Position } from \"@cosyte/cli\";\n *\n * formatHl7Position({ segmentIndex: 3, fieldIndex: 5 }); // => \"seg[3].field[5]\"\n * formatHl7Position({ segmentIndex: 0 }); // => \"seg[0]\"\n * ```\n */\nexport function formatHl7Position(pos: Hl7PositionLike): string {\n let out = `seg[${String(pos.segmentIndex)}]`;\n if (pos.fieldIndex !== undefined) out += `.field[${String(pos.fieldIndex)}]`;\n if (pos.repetitionIndex !== undefined) out += `.rep[${String(pos.repetitionIndex)}]`;\n if (pos.componentIndex !== undefined) out += `.comp[${String(pos.componentIndex)}]`;\n if (pos.subcomponentIndex !== undefined) out += `.sub[${String(pos.subcomponentIndex)}]`;\n return out;\n}\n","/**\n * The **per-format parser adapter registry**: the single place the CLI routes a resolved format to\n * its wrapped `@cosyte/*` parser, for each of the four wrapping operations (`parse` / `inspect` /\n * `fmt` / `validate`). One lazy, value-free registry, so the wrapper boundary lives in exactly one\n * file.\n *\n * **Capability is per (format, operation).** Not every parser faithfully supports every operation:\n * DICOM's model is binary (no faithful JSON `parse`, no text `fmt`), C-CDA's canonical form is XML (no\n * library-blessed JSON `parse`), MLLP is a transport container (de-framed to HL7, `parse`/`inspect`\n * only). {@link OP_SUPPORT} is the honest matrix; an unsupported (format, op) is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, **never** a faked result.\n *\n * **Lazy + optional.** Every parser is imported dynamically inside its branch, so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code. The six breadth parsers are `optionalDependencies`: if\n * one is absent the dynamic import is caught and degrades to a value-free `CLI_PARSER_UNAVAILABLE`\n * (exit `69`) rather than an unhandled crash: the CLI core still works with any of them missing.\n *\n * @packageDocumentation\n */\n\nimport type * as CosyteFhir from \"@cosyte/fhir\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport { formatHl7Position, type Finding } from \"./findings.js\";\nimport type { CosyteFormat } from \"./format.js\";\n\n/** The four wrapping operations a command can ask a format's adapter to perform. */\nexport type Op = \"parse\" | \"inspect\" | \"fmt\" | \"validate\";\n\n/** A value-free parse warning: a stable code plus the parser's positional (index-only) context. */\nexport type ParseWarning = { readonly code: string } & Readonly<Record<string, unknown>>;\n\n/** The result of wrapping a parser's `parse`: the library's parsed model + its value-free warnings. */\nexport interface ParseResult {\n /** The wrapped library's parsed model: emitted verbatim as JSON on the data channel. */\n readonly model: unknown;\n /** The parser's value-free warnings (code + position). */\n readonly warnings: readonly ParseWarning[];\n}\n\n/** The result of a canonical re-serialization (`fmt`): the spec-clean text + a value-free warning count. */\nexport interface FmtResult {\n /** The wrapped serializer's output text. */\n readonly output: string;\n /** How many parse warnings the round-trip surfaced (value-free count only). */\n readonly warningCount: number;\n}\n\n/** The verdict of running a format's validation surface: value-free findings + the validity boolean. */\nexport interface Verdict {\n /** The value-free findings (code + severity + positional locator). */\n readonly findings: readonly Finding[];\n /** `true` iff the input is valid (no error/fatal-severity finding). */\n readonly valid: boolean;\n}\n\n/* ── value-free structural summaries (one variant per format) ─────────────────────────────────── */\n\n/** Value-free structural summary of an HL7 v2 message. */\nexport interface Hl7Summary {\n readonly format: \"hl7\";\n readonly messageType: string | null;\n readonly version: string | null;\n readonly segmentCount: number;\n readonly segments: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a FHIR resource. */\nexport interface FhirSummary {\n readonly format: \"fhir\";\n readonly resourceType: string | null;\n readonly bundleType?: string | null;\n readonly entryCount?: number;\n readonly entryResourceTypes?: Readonly<Record<string, number>>;\n readonly issueCount: number;\n}\n\n/** Value-free structural summary of an X12 interchange (envelope counts + transaction-set ids). */\nexport interface X12Summary {\n readonly format: \"x12\";\n readonly groupCount: number;\n readonly transactionCount: number;\n /** Count of each transaction-set identifier code (ST-01), e.g. `{ \"834\": 1 }`: value-free codes. */\n readonly transactionSetIds: Readonly<Record<string, number>>;\n readonly segmentCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an ASTM record message. */\nexport interface AstmSummary {\n readonly format: \"astm\";\n /** The host-query classification kind (`results` | `orders` | `host-query` | `indeterminate`). */\n readonly messageKind: string;\n readonly recordCount: number;\n /** Count of each single-letter record type, e.g. `{ H: 1, P: 1, O: 2, R: 4, L: 1 }`. */\n readonly recordTypes: Readonly<Record<string, number>>;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a C-CDA document (document type + section LOINC codes). */\nexport interface CcdaSummary {\n readonly format: \"ccda\";\n readonly documentType: string | null;\n readonly sectionCount: number;\n /** The LOINC `code` of each top-level section (value-free classification codes). */\n readonly sectionCodes: readonly string[];\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of a DICOM dataset (classification UIDs + element count). */\nexport interface DicomSummary {\n readonly format: \"dicom\";\n /** The SOP Class UID (a standard OID identifying the object type: value-free classification). */\n readonly sopClassUid: string | null;\n /** The Transfer Syntax UID (encoding classification: value-free). */\n readonly transferSyntaxUid: string | null;\n readonly elementCount: number;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an NCPDP SCRIPT message. */\nexport interface NcpdpSummary {\n readonly format: \"ncpdp\";\n readonly standard: \"SCRIPT\";\n /** The SCRIPT message type (e.g. `NewRx`, `CancelRx`: a value-free classification). */\n readonly messageType: string | null;\n /** The SCRIPT version (e.g. `2017071`: value-free). */\n readonly version: string | null;\n readonly warningCount: number;\n}\n\n/** Value-free structural summary of an MLLP stream (frame count only; the payloads are HL7). */\nexport interface MllpSummary {\n readonly format: \"mllp\";\n readonly frameCount: number;\n readonly warningCount: number;\n}\n\n/** The discriminated value-free structural summary `inspect` renders. */\nexport type InspectSummary =\n | Hl7Summary\n | FhirSummary\n | X12Summary\n | AstmSummary\n | CcdaSummary\n | DicomSummary\n | NcpdpSummary\n | MllpSummary;\n\n/* ── the capability matrix ───────────────────────────────────────────────────────────────────── */\n\n/**\n * The honest per-format operation matrix. A (format, op) pair absent here is a value-free\n * `CLI_FORMAT_UNSUPPORTED`, never a faked result. The unsupported cells and why:\n * - **dicom** `parse`/`fmt`. The model is binary (no faithful JSON view; `serializeDicom` emits a\n * Part-10 byte stream, not text). `inspect`/`validate` are supported.\n * - **ccda** `parse`: the canonical form is XML; there is no library-blessed JSON model, so `fmt`\n * (XML re-serialize) is the faithful surface. `inspect`/`fmt`/`validate` are supported.\n * - **mllp** `fmt`/`validate`: MLLP is a transport container the CLI de-frames to HL7; `parse` yields\n * the enclosed HL7 message(s) and `inspect` reports the frame count.\n *\n * @example\n * ```ts\n * import { OP_SUPPORT } from \"@cosyte/cli\";\n *\n * OP_SUPPORT.dicom.has(\"parse\"); // => false\n * OP_SUPPORT.hl7.has(\"validate\"); // => true\n * ```\n */\nexport const OP_SUPPORT: Readonly<Record<CosyteFormat, ReadonlySet<Op>>> = {\n hl7: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n fhir: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n x12: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n astm: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ncpdp: new Set<Op>([\"parse\", \"inspect\", \"fmt\", \"validate\"]),\n ccda: new Set<Op>([\"inspect\", \"fmt\", \"validate\"]),\n dicom: new Set<Op>([\"inspect\", \"validate\"]),\n mllp: new Set<Op>([\"parse\", \"inspect\"]),\n};\n\n/**\n * True iff `format`'s wrapped parser supports `op` in this build (see {@link OP_SUPPORT}).\n *\n * @param format - The resolved format.\n * @param op - The wrapping operation.\n * @returns Whether the (format, op) pair is wired.\n * @example\n * ```ts\n * import { supportsOp } from \"@cosyte/cli\";\n *\n * supportsOp(\"x12\", \"fmt\"); // => true\n * supportsOp(\"dicom\", \"parse\"); // => false\n * ```\n */\nexport function supportsOp(format: CosyteFormat, op: Op): boolean {\n return OP_SUPPORT[format].has(op);\n}\n\n/**\n * The formats that support `op`, as a sorted, value-free list: used to build the \"does not support\"\n * diagnostic so the user is told which formats *do* support the operation they asked for.\n *\n * @param op - The wrapping operation.\n * @returns The supporting format names, sorted.\n * @example\n * ```ts\n * import { formatsSupporting } from \"@cosyte/cli\";\n *\n * formatsSupporting(\"fmt\"); // => [\"astm\", \"ccda\", \"fhir\", \"hl7\", \"ncpdp\", \"x12\"]\n * ```\n */\nexport function formatsSupporting(op: Op): readonly CosyteFormat[] {\n return (Object.keys(OP_SUPPORT) as CosyteFormat[]).filter((f) => OP_SUPPORT[f].has(op)).sort();\n}\n\n/* ── value-free helpers ──────────────────────────────────────────────────────────────────────── */\n\n/**\n * Render an arbitrary parser **position** object as a value-free locator string, keeping **only**\n * number-valued own properties (the parsers' positions are index-only): e.g. `{ segmentIndex: 3,\n * elementIndex: 2 }` → `segmentIndex[3].elementIndex[2]`. A non-number field (which a position should\n * never carry) is dropped, so a stray value can never reach a diagnostic. Falls back to `\"?\"` when no\n * numeric index is present.\n *\n * @param pos - A parser position object (index-only by the parser's contract).\n * @returns A value-free locator built solely from numeric indices.\n * @example\n * ```ts\n * import { valueFreeLocator } from \"@cosyte/cli\";\n *\n * valueFreeLocator({ segmentIndex: 3, elementIndex: 2 }); // => \"segmentIndex[3].elementIndex[2]\"\n * valueFreeLocator({}); // => \"?\"\n * ```\n */\nexport function valueFreeLocator(pos: unknown): string {\n if (typeof pos !== \"object\" || pos === null) return \"?\";\n const parts: string[] = [];\n for (const [k, v] of Object.entries(pos)) {\n if (typeof v === \"number\") parts.push(`${k}[${String(v)}]`);\n }\n return parts.length > 0 ? parts.join(\".\") : \"?\";\n}\n\n/** Severities that make an input **invalid** (exit `1`). Recovered warnings never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** Whether any finding is error/fatal severity (i.e. the input is invalid). */\nfunction anyError(findings: readonly Finding[]): boolean {\n return findings.some((f) => ERROR_SEVERITIES.has(f.severity));\n}\n\n/**\n * Lazy-import an **optional** parser package, mapping an *absent* package to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`): the graceful-degradation path for the `optionalDependencies`\n * breadth parsers. A genuine import that succeeds passes straight through; any error whose\n * shape is \"module not found\" becomes the value-free CLI error. Other errors propagate unchanged.\n *\n * @template T - The imported module's type.\n * @param format - The format whose optional parser is being loaded (named in the diagnostic).\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptional } from \"@cosyte/cli\";\n *\n * // a present parser resolves; an absent one throws CLI_PARSER_UNAVAILABLE\n * await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n * ```\n */\nexport async function loadOptional<T>(format: CosyteFormat, load: () => Promise<T>): Promise<T> {\n return loadOptionalPackage(\n `the @cosyte/${format} parser is not installed; install it to use this format ` +\n `(it is an optional dependency)`,\n load,\n );\n}\n\n/**\n * The same graceful-degradation path as {@link loadOptional}, keyed on a **package name** rather than\n * a {@link CosyteFormat}, with the diagnostic supplied by the caller.\n *\n * Two of the packages the CLI lazy-loads are not wire-format parsers and so cannot go through\n * {@link loadOptional}: `@cosyte/transform` (a conversion library, not one of the eight formats, so\n * calling it a \"parser\" in the diagnostic would be wrong) and `@cosyte/fhir` (a format, but absent for\n * a reason no reinstall fixes, which the message has to say). Both are reachable from a published\n * install only if the user already has them, so both must degrade to a value-free\n * `CLI_PARSER_UNAVAILABLE` (exit `69`) instead of surfacing a raw resolver error and a stack frame.\n *\n * @template T - The imported module's type.\n * @param detail - The value-free diagnostic detail shown when the package is absent.\n * @param load - A thunk performing the dynamic import.\n * @returns The imported module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent; any other error\n * propagates unchanged.\n * @example\n * ```ts\n * import { loadOptionalPackage } from \"@cosyte/cli\";\n *\n * await loadOptionalPackage(\"the conversion library is not installed\", () =>\n * import(\"@cosyte/transform\"),\n * );\n * ```\n */\nexport async function loadOptionalPackage<T>(detail: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (e) {\n if (isModuleNotFound(e)) {\n throw new CliError(CLI_CODES.CLI_PARSER_UNAVAILABLE, EXIT.UNAVAILABLE, detail);\n }\n throw e;\n }\n}\n\n/**\n * Why `@cosyte/fhir` is absent, in the words a user can act on. It is not on the npm registry, so it\n * cannot be a declared dependency of this package at all, and no reinstall of `@cosyte/cli` will\n * produce it. Value-free by construction: a package name and a statement of fact, no input echoed.\n */\nconst FHIR_UNAVAILABLE =\n \"the @cosyte/fhir parser is not installed, and it is not currently on the npm registry, \" +\n \"so it cannot be installed from there; FHIR support is unavailable in this install\";\n\n/**\n * Load `@cosyte/fhir`, degrading to a value-free `CLI_PARSER_UNAVAILABLE` when it is absent.\n *\n * Every FHIR branch in this file and the `convert` command go through here, so there is exactly one\n * place that decides what an absent FHIR library does. It is deliberately not re-exported from the\n * package entry point: consumers get {@link loadOptionalPackage}, not this repo's own wiring.\n *\n * @returns The `@cosyte/fhir` module.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent.\n * @example\n * ```ts\n * const { parseResource } = await loadFhir();\n * ```\n */\nexport async function loadFhir(): Promise<typeof CosyteFhir> {\n return loadOptionalPackage(FHIR_UNAVAILABLE, () => import(\"@cosyte/fhir\"));\n}\n\n/** True iff `e` is a \"module not found\" failure, by Node's `code`, or the standard resolver message. */\nfunction isModuleNotFound(e: unknown): boolean {\n if (typeof e !== \"object\" || e === null) return false;\n const code = \"code\" in e ? e.code : undefined;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") return true;\n const message = \"message\" in e && typeof e.message === \"string\" ? e.message : \"\";\n return /Cannot find (package|module)|Failed to (load|resolve)/i.test(message);\n}\n\n/* ── parse ───────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Parse one record of `format` into the wrapped library's model + its value-free warnings. The model\n * is emitted verbatim on the data channel; the CLI adds no parsing of its own.\n *\n * @param format - A format for which `supportsOp(format, \"parse\")` is true.\n * @param bytes - The single record's bytes (already de-framed for MLLP: callers pass `\"hl7\"` there).\n * @returns The parsed model + value-free warnings.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * own rejection propagates for the command's value-free failure boundary to catch.\n * @example\n * ```ts\n * import { parseFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}');\n * (await parseFormat(\"fhir\", bytes)).warnings.length; // => 0\n * ```\n */\nexport async function parseFormat(format: CosyteFormat, bytes: Uint8Array): Promise<ParseResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return {\n model: msg.toJSON(),\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const text = decode(bytes);\n const { resource, issues } = parseResource(text);\n const model: unknown = JSON.parse(serializeResource(resource));\n return {\n model,\n warnings: issues.map((i) => ({\n code: i.code,\n severity: i.severity,\n expression: i.expression,\n })),\n };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return {\n model: ix,\n warnings: ix.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n model: msg,\n warnings: msg.warnings.map((w) => ({ code: w.code, position: w.position })),\n };\n }\n case \"dicom\":\n case \"ccda\":\n case \"mllp\":\n // Guarded upstream by supportsOp; a direct call for an unsupported (format, op) is value-free.\n throw unsupportedInternal(format, \"parse\");\n }\n}\n\n/* ── inspect ─────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Build the value-free structural summary of one input of `format`: counts and structural type codes\n * only, never a field value.\n *\n * @param format - A format for which `supportsOp(format, \"inspect\")` is true.\n * @param bytes - The input bytes.\n * @returns A {@link InspectSummary} variant for the format.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary.\n * @example\n * ```ts\n * import { inspectFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\"}');\n * (await inspectFormat(\"fhir\", bytes)).format; // => \"fhir\"\n * ```\n */\nexport async function inspectFormat(\n format: CosyteFormat,\n bytes: Uint8Array,\n): Promise<InspectSummary> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const segments: Record<string, number> = {};\n const all = msg.allSegments();\n for (const seg of all) segments[seg.type] = (segments[seg.type] ?? 0) + 1;\n return {\n format: \"hl7\",\n messageType: msg.meta.type ?? null,\n version: msg.meta.version ?? null,\n segmentCount: all.length,\n segments,\n warningCount: msg.warnings.length,\n };\n }\n case \"fhir\": {\n const { parseResource, resourceType, readBundle } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const rt = resourceType(resource) ?? null;\n if (rt === \"Bundle\") {\n const bundle = readBundle(resource);\n const entryResourceTypes: Record<string, number> = {};\n for (const e of bundle.entries) {\n const t = e.resourceType ?? \"(none)\";\n entryResourceTypes[t] = (entryResourceTypes[t] ?? 0) + 1;\n }\n return {\n format: \"fhir\",\n resourceType: rt,\n bundleType: bundle.type ?? null,\n entryCount: bundle.entries.length,\n entryResourceTypes,\n issueCount: issues.length,\n };\n }\n return { format: \"fhir\", resourceType: rt, issueCount: issues.length };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const transactionSetIds: Record<string, number> = {};\n let transactionCount = 0;\n let segmentCount = 0;\n for (const g of ix.groups) {\n for (const t of g.transactions) {\n transactionCount += 1;\n segmentCount += t.segments.length;\n const id = t.st.elements[1] ?? \"(unknown)\";\n transactionSetIds[id] = (transactionSetIds[id] ?? 0) + 1;\n }\n }\n return {\n format: \"x12\",\n groupCount: ix.groups.length,\n transactionCount,\n transactionSetIds,\n segmentCount,\n warningCount: ix.warnings.length,\n };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const recordTypes: Record<string, number> = {};\n for (const r of msg.records) recordTypes[r.type] = (recordTypes[r.type] ?? 0) + 1;\n return {\n format: \"astm\",\n messageKind: msg.classification.kind,\n recordCount: msg.records.length,\n recordTypes,\n warningCount: msg.warnings.length,\n };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const sectionCodes: string[] = [];\n for (const s of doc.sections) {\n const code = s.code?.code;\n if (typeof code === \"string\") sectionCodes.push(code);\n }\n return {\n format: \"ccda\",\n documentType: doc.documentType ?? null,\n sectionCount: doc.sections.length,\n sectionCodes,\n warningCount: doc.warnings.length,\n };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n let warningCount = 0;\n const ds = parseDicom(Buffer.from(bytes), { onWarning: () => (warningCount += 1) });\n return {\n format: \"dicom\",\n sopClassUid: ds.fileMeta?.mediaStorageSOPClassUID ?? null,\n transferSyntaxUid: ds.fileMeta?.transferSyntaxUID ?? null,\n elementCount: ds.elements().length,\n warningCount,\n };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n return {\n format: \"ncpdp\",\n standard: \"SCRIPT\",\n messageType: msg.body.kind ?? null,\n version: msg.header.version ?? null,\n warningCount: msg.warnings.length,\n };\n }\n case \"mllp\": {\n const { payloads, warningCount } = await deframeMllp(bytes);\n return { format: \"mllp\", frameCount: payloads.length, warningCount };\n }\n }\n}\n\n/* ── fmt ─────────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Canonically re-serialize one input of `format` via the wrapped library's spec-clean serializer. The\n * CLI never re-canonicalizes on its own; the output is exactly the serializer's.\n *\n * @param format - A format for which `supportsOp(format, \"fmt\")` is true.\n * @param bytes - The input bytes.\n * @returns The serialized text + a value-free warning count.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; the wrapped parser's\n * rejection propagates for the command's value-free failure boundary (no partial emit).\n * @example\n * ```ts\n * import { fmtFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{ \"resourceType\":\"Patient\" , \"id\":\"x\" }');\n * (await fmtFormat(\"fhir\", bytes)).output.startsWith(\"{\"); // => true\n * ```\n */\nexport async function fmtFormat(format: CosyteFormat, bytes: Uint8Array): Promise<FmtResult> {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n return { output: msg.toString(), warningCount: msg.warnings.length };\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n return { output: serializeResource(resource), warningCount: issues.length };\n }\n case \"x12\": {\n const { parseX12, serializeX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n return { output: serializeX12(ix), warningCount: ix.warnings.length };\n }\n case \"astm\": {\n const { parseAstmRecords, serializeAstmRecords } = await loadOptional(\n \"astm\",\n () => import(\"@cosyte/astm\"),\n );\n const msg = parseAstmRecords(decode(bytes));\n return { output: serializeAstmRecords(msg), warningCount: msg.warnings.length };\n }\n case \"ccda\": {\n const { parseCcda, serializeCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n return { output: serializeCcda(doc), warningCount: doc.warnings.length };\n }\n case \"ncpdp\": {\n const { parseScript, serializeScript } = await loadOptional(\n \"ncpdp\",\n () => import(\"@cosyte/ncpdp\"),\n );\n const msg = parseScript(decode(bytes));\n return { output: serializeScript(msg), warningCount: msg.warnings.length };\n }\n case \"dicom\":\n case \"mllp\":\n throw unsupportedInternal(format, \"fmt\");\n }\n}\n\n/* ── validate ────────────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Run the format's validation surface and return a value-free {@link Verdict}. For the Postel's-Law\n * lenient parsers, a **parseable** input is valid: recovered deviations are non-fatal warnings the\n * library surfaces, never a stricter verdict the CLI invents. FHIR additionally runs `validateResource`\n * and is invalid on any error/fatal-severity issue.\n *\n * @param format - A format for which `supportsOp(format, \"validate\")` is true.\n * @param bytes - The input bytes.\n * @returns The value-free verdict (findings + validity).\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if the optional parser is absent; an unparseable input\n * propagates as the wrapped parser's throw for the command to map to a data error (`65`).\n * @example\n * ```ts\n * import { validateFormat } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}');\n * (await validateFormat(\"fhir\", bytes)).valid; // => true\n * ```\n */\nexport async function validateFormat(format: CosyteFormat, bytes: Uint8Array): Promise<Verdict> {\n switch (format) {\n case \"fhir\": {\n const { parseResource, validateResource } = await loadFhir();\n const { resource, issues } = parseResource(decode(bytes));\n const validation = validateResource(resource);\n const findings: Finding[] = [\n ...issues.map((i) => finding(i.code, i.severity, i.expression)),\n ...validation.issues.map((i) => finding(i.code, i.severity, i.expression, i.constraint)),\n ];\n return { findings, valid: !anyError(findings) };\n }\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const msg = parseHL7(Buffer.from(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", formatHl7Position(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const ix = parseX12(Buffer.from(bytes));\n const findings = ix.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"astm\": {\n const { parseAstmRecords } = await loadOptional(\"astm\", () => import(\"@cosyte/astm\"));\n const msg = parseAstmRecords(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"ccda\": {\n const { parseCcda } = await loadOptional(\"ccda\", () => import(\"@cosyte/ccda\"));\n const doc = parseCcda(decode(bytes));\n const findings = doc.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"dicom\": {\n const { parseDicom } = await loadOptional(\"dicom\", () => import(\"@cosyte/dicom\"));\n const findings: Finding[] = [];\n parseDicom(Buffer.from(bytes), {\n onWarning: (w) => findings.push(finding(w.code, \"warning\", valueFreeLocator(w.position))),\n });\n return { findings, valid: !anyError(findings) };\n }\n case \"ncpdp\": {\n const { parseScript } = await loadOptional(\"ncpdp\", () => import(\"@cosyte/ncpdp\"));\n const msg = parseScript(decode(bytes));\n const findings = msg.warnings.map((w) =>\n finding(w.code, \"warning\", valueFreeLocator(w.position)),\n );\n return { findings, valid: !anyError(findings) };\n }\n case \"mllp\":\n throw unsupportedInternal(format, \"validate\");\n }\n}\n\n/* ── MLLP de-framing (transport → HL7 payloads) ──────────────────────────────────────────────── */\n\n/**\n * De-frame an MLLP byte stream into its enclosed HL7 payloads via `@cosyte/mllp`'s `FrameReader`. MLLP\n * is a transport container, not a document format: each frame's payload is an HL7 v2 message the CLI\n * then parses/inspects with the `hl7` adapter. Multi-frame streams are the CLI's multi-message surface.\n *\n * @param bytes - The MLLP-framed input.\n * @returns The de-framed HL7 payloads (in stream order) + a value-free framing-warning count.\n * **Truncation is a data error, never a silent drop.** The `FrameReader` is a streaming decoder: an\n * unterminated trailing frame (a VT opened with no closing FS/CR) is left buffered and delivered by\n * *no* callback, so feeding a whole file and reading only `onFrame` would silently lose the partial\n * message with a green exit. We therefore detect an open trailing frame at the byte level (the last\n * VT sits after the last FS: MLLP payloads are HL7 v2 text and never carry the `0x0B`/`0x1C` framing\n * bytes) and reject the whole stream as a value-free `CLI_PARSE_FAILED` data error.\n *\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` if `@cosyte/mllp` is absent; `CLI_PARSE_FAILED` (exit\n * `65`) on a truncated stream; a hard framing error propagates for the caller's value-free boundary.\n * @example\n * ```ts\n * import { deframeMllp } from \"@cosyte/cli\";\n *\n * // a VT-framed \"MSH|...\" message → one payload\n * (await deframeMllp(new Uint8Array([0x0b, 0x4d, 0x53, 0x48, 0x1c, 0x0d]))).payloads.length; // => 1\n * ```\n */\nexport async function deframeMllp(\n bytes: Uint8Array,\n): Promise<{ payloads: Buffer[]; warningCount: number }> {\n // Reject an unterminated trailing frame BEFORE de-framing: a VT after the last FS is an open frame\n // the streaming reader would buffer and silently drop. (MLLP payloads never contain 0x0B/0x1C.)\n if (bytes.lastIndexOf(0x0b) > bytes.lastIndexOf(0x1c)) {\n throw truncatedMllpError();\n }\n const { FrameReader } = await loadOptional(\"mllp\", () => import(\"@cosyte/mllp\"));\n const payloads: Buffer[] = [];\n let warningCount = 0;\n const reader = new FrameReader({\n onFrame: (payload) => payloads.push(Buffer.from(payload)),\n onWarning: () => (warningCount += 1),\n });\n reader.push(Buffer.from(bytes));\n return { payloads, warningCount };\n}\n\n/**\n * The value-free data error for a **truncated MLLP stream**: a frame opened and never closed, which\n * the streaming reader buffers and delivers to no callback. Built here so the whole-buffer de-framer\n * above and the chunk-by-chunk one in `core/records.ts` refuse the same input with the same code and\n * the same words.\n *\n * @returns A `CLI_PARSE_FAILED` (exit `65`) {@link CliError}.\n * @example\n * ```ts\n * import { truncatedMllpError } from \"@cosyte/cli\";\n *\n * truncatedMllpError().exit; // => 65\n * ```\n */\nexport function truncatedMllpError(): CliError {\n return new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n \"truncated MLLP stream: an unterminated frame at the end of input (no closing FS/CR)\",\n );\n}\n\n/* ── shared internals ────────────────────────────────────────────────────────────────────────── */\n\n/** Decode input bytes as tolerant UTF-8 (the text parsers accept a string). */\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n}\n\n/** Build one value-free {@link Finding}; a FHIR `constraint` (a public spec id) is appended if present. */\nfunction finding(code: string, severity: string, location: string, constraint?: string): Finding {\n const loc = constraint !== undefined ? `${location} (${constraint})` : location;\n return { code, severity, location: loc };\n}\n\n/** The value-free error for an internal (guarded-upstream) unsupported (format, op): a programming bug. */\nfunction unsupportedInternal(format: CosyteFormat, op: Op): CliError {\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\``,\n );\n}\n","/**\n * **Record streaming**: turning a stream of input byte chunks into a stream of whole records, so a\n * multi-record command can emit a record's output *before* the rest of its input has been read.\n *\n * Two input shapes are multi-record, and both arrive here as chunks rather than as one buffer: an\n * **MLLP** stream (each VT-framed frame encloses one HL7 v2 message) and any input under\n * **`--ndjson`** (each non-empty line is a record). Neither splitter re-implements a wire format: the\n * MLLP one drives `@cosyte/mllp`'s own streaming `FrameReader`, and the NDJSON one splits on the line\n * terminator, which is the bulk-data convention's own framing, not a parse of the records inside it.\n *\n * The size limit is enforced here too, as {@link withinLimit}: a running byte count over the chunk\n * stream, so an over-limit input is refused **while it is arriving** rather than after it has been\n * assembled.\n *\n * @packageDocumentation\n */\n\nimport { inputTooLargeError, MAX_INPUT_BYTES } from \"./limits.js\";\nimport { loadOptional, truncatedMllpError } from \"./parsers.js\";\n\n/** A stream of input byte chunks, in arrival order: what every function here consumes. */\nexport type ByteChunks = AsyncIterable<Uint8Array>;\n\n/** The NDJSON record terminator (`\\n`); a preceding `\\r` is part of the terminator, not the record. */\nconst LINE_FEED = 0x0a;\n/** The carriage return that may precede a line feed on a CRLF stream. */\nconst CARRIAGE_RETURN = 0x0d;\n/** The MLLP start-of-block byte: a frame opens with it. */\nconst VERTICAL_TAB = 0x0b;\n/** The MLLP end-of-block byte: a frame closes with it (followed by a carriage return). */\nconst FILE_SEPARATOR = 0x1c;\n\n/** View a chunk as a `Buffer` without copying it. */\nfunction asBuffer(chunk: Uint8Array): Buffer {\n return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.length);\n}\n\n/**\n * Wrap `bytes` as a one-chunk stream, so the streaming record path can also serve a caller that\n * hands the CLI a whole buffer (an injected reader, or the programmatic API). The path is the same;\n * only the granularity the input arrives at differs.\n *\n * @param bytes - The whole input.\n * @returns A stream yielding exactly one chunk (or none, when `bytes` is empty).\n * @example\n * ```ts\n * import { oneChunk } from \"@cosyte/cli\";\n *\n * let n = 0;\n * for await (const c of oneChunk(new Uint8Array([1, 2, 3]))) n += c.length;\n * n; // => 3\n * ```\n */\nexport async function* oneChunk(bytes: Uint8Array): AsyncGenerator<Uint8Array> {\n // A one-element stream still has to be a real async iterable, so the tick is deliberate: every\n // consumer here is written against a source that arrives over time.\n await Promise.resolve();\n if (bytes.length > 0) yield bytes;\n}\n\n/**\n * Pass chunks through while counting them against the CLI's own size limit, and **refuse the moment\n * the running total passes it**: the chunk that crosses the limit is never yielded, the source is\n * never pulled again, and nothing downstream ever allocates memory proportional to an oversized\n * input. This is why the refusal a caller sees is the CLI's own data error rather than a platform\n * allocation failure reported as an internal error.\n *\n * @param chunks - The input chunk stream.\n * @param limit - The maximum number of bytes to accept. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns The same chunks, up to the limit.\n * @throws {CliError} `CLI_INPUT_TOO_LARGE` (exit `65`) as soon as the running total passes `limit`.\n * @example\n * ```ts\n * import { oneChunk, withinLimit } from \"@cosyte/cli\";\n *\n * const src = withinLimit(oneChunk(new Uint8Array(10)), 4);\n * await src.next().catch((e: unknown) => (e as { code: string }).code); // => \"CLI_INPUT_TOO_LARGE\"\n * ```\n */\nexport async function* withinLimit(\n chunks: ByteChunks,\n limit: number = MAX_INPUT_BYTES,\n): AsyncGenerator<Uint8Array> {\n let total = 0;\n for await (const chunk of chunks) {\n total += chunk.length;\n if (total > limit) throw inputTooLargeError(limit);\n yield chunk;\n }\n}\n\n/**\n * Drain a chunk stream into one buffer: the single-message path, where the parser needs the whole\n * message anyway. The size limit is already applied by {@link withinLimit} upstream, so this cannot\n * accumulate more than the limit allows.\n *\n * @param chunks - The input chunk stream.\n * @returns The concatenated bytes.\n * @example\n * ```ts\n * import { collectChunks, oneChunk } from \"@cosyte/cli\";\n *\n * (await collectChunks(oneChunk(new TextEncoder().encode(\"MSH|\")))).length; // => 4\n * ```\n */\nexport async function collectChunks(chunks: ByteChunks): Promise<Uint8Array> {\n const parts: Buffer[] = [];\n for await (const chunk of chunks) parts.push(asBuffer(chunk));\n return Buffer.concat(parts);\n}\n\n/** True iff every byte of `line` is whitespace (so the line carries no record). */\nfunction isBlank(line: Uint8Array): boolean {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(line).trim().length === 0;\n}\n\n/** Drop the `\\r` of a CRLF terminator, which belongs to the terminator rather than to the record. */\nfunction stripCarriageReturn(line: Buffer): Buffer {\n return line.length > 0 && line[line.length - 1] === CARRIAGE_RETURN\n ? line.subarray(0, line.length - 1)\n : line;\n}\n\n/**\n * Split a chunk stream into **NDJSON records**: each non-empty, newline-terminated line, yielded as\n * soon as its terminator arrives. A record split across two chunks is carried over; a final record\n * with no trailing newline is yielded at end of stream; a blank line carries no record and is\n * skipped.\n *\n * @param chunks - The input chunk stream.\n * @returns A stream of record bytes, in input order.\n * @example\n * ```ts\n * import { ndjsonRecords, oneChunk } from \"@cosyte/cli\";\n *\n * const src = oneChunk(new TextEncoder().encode('{\"a\":1}\\n\\n{\"b\":2}\\n'));\n * const out: string[] = [];\n * for await (const r of ndjsonRecords(src)) out.push(new TextDecoder().decode(r));\n * out.length; // => 2\n * ```\n */\nexport async function* ndjsonRecords(chunks: ByteChunks): AsyncGenerator<Uint8Array> {\n let carry: Buffer = Buffer.alloc(0);\n for await (const chunk of chunks) {\n const buf = carry.length > 0 ? Buffer.concat([carry, asBuffer(chunk)]) : asBuffer(chunk);\n let start = 0;\n for (;;) {\n const end = buf.indexOf(LINE_FEED, start);\n if (end < 0) break;\n const line = stripCarriageReturn(buf.subarray(start, end));\n if (!isBlank(line)) yield line;\n start = end + 1;\n }\n // Copy the tail so the chunk it came from can be released while we wait for the next one.\n carry = start === 0 ? asBuffer(buf) : Buffer.from(buf.subarray(start));\n }\n const last = stripCarriageReturn(carry);\n if (!isBlank(last)) yield last;\n}\n\n/**\n * De-frame a chunk stream into **MLLP frame payloads** (each an enclosed HL7 v2 message), yielded as\n * each frame completes. The framing is `@cosyte/mllp`'s own streaming `FrameReader`, fed chunk by\n * chunk; the CLI only tracks where the frame bytes fell so it can tell a **truncated** stream from a\n * complete one.\n *\n * **Truncation is a data error, never a silent drop.** An unterminated trailing frame (a start-of-block\n * byte after the last end-of-block byte) is delivered by no callback, so it would otherwise vanish\n * with a green exit. It is detected at end of stream and raised, after the frames that did complete\n * have already been yielded: their output stands, and the invocation still resolves to the data error.\n *\n * @param chunks - The input chunk stream.\n * @returns A stream of enclosed HL7 payloads, in frame order.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) if `@cosyte/mllp` is absent;\n * `CLI_PARSE_FAILED` (exit `65`) at end of stream on a truncated final frame.\n * @example\n * ```ts\n * import { mllpFrames, oneChunk } from \"@cosyte/cli\";\n *\n * const framed = new Uint8Array([0x0b, 0x4d, 0x53, 0x48, 0x1c, 0x0d]);\n * const seen: number[] = [];\n * for await (const p of mllpFrames(oneChunk(framed))) seen.push(p.length);\n * seen.length; // => 1\n * ```\n */\nexport async function* mllpFrames(chunks: ByteChunks): AsyncGenerator<Uint8Array> {\n const { FrameReader } = await loadOptional(\"mllp\", () => import(\"@cosyte/mllp\"));\n const ready: Buffer[] = [];\n const reader = new FrameReader({\n onFrame: (payload) => ready.push(Buffer.from(payload)),\n onWarning: () => undefined,\n // The CLI's own documented input limit is the binding one, so the reader's smaller default frame\n // ceiling is raised to it: an over-limit MLLP stream is refused by the limit the help output and\n // the command reference state, not by an undocumented one underneath it.\n maxFrameSizeBytes: MAX_INPUT_BYTES,\n });\n\n // Offsets of the last start-of-block and end-of-block bytes seen anywhere in the stream: an\n // enclosed HL7 v2 payload never carries either byte, so their order at end of stream is the same\n // truncation test the whole-buffer de-framer applies.\n let lastStart = -1;\n let lastEnd = -1;\n let offset = 0;\n\n for await (const chunk of chunks) {\n const buf = asBuffer(chunk);\n const start = buf.lastIndexOf(VERTICAL_TAB);\n if (start >= 0) lastStart = offset + start;\n const end = buf.lastIndexOf(FILE_SEPARATOR);\n if (end >= 0) lastEnd = offset + end;\n offset += buf.length;\n\n reader.push(buf);\n while (ready.length > 0) {\n const frame = ready.shift();\n if (frame !== undefined) yield frame;\n }\n }\n\n if (lastStart > lastEnd) throw truncatedMllpError();\n}\n","/**\n * The shared **input + format resolution** every file-consuming command runs before it touches a\n * wrapped parser: resolve the `<file|->` argument, read its bytes (a file, or stdin for `-`), reject\n * empty input, then resolve the format: an explicit `--format` override (validated) or conservative\n * content autodetection, and confirm the format is actually wired in this build. Factored out of the\n * commands so `parse`/`validate`/`inspect`/`fmt` share one identical, value-free front door and the\n * exit-code contract is applied in exactly one place.\n *\n * Every failure is a value-free {@link CliError} rendered to a {@link RunResult}: a missing argument\n * is a usage error (`2`), an unreadable file a no-input error (`66`), empty/undetected/unwired input a\n * data error (`65`), an input past the documented size limit a data error too (`65`, never the\n * internal-error code). None ever echoes an input byte.\n *\n * Two front doors, one contract: {@link resolveInput} hands back the whole input as one buffer, and\n * {@link resolveInputStream} hands back a chunk stream for a command that emits output before the\n * input has finished arriving. They share the format-resolution and exit-code decisions, so a bad\n * `--format`, an undetectable input and an unwired (format, op) resolve identically either way.\n *\n * @packageDocumentation\n */\n\nimport {\n asCosyteFormat,\n detectFormat,\n detectionError,\n DETECT_PREFIX_BYTES,\n type CosyteFormat,\n} from \"./format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { RunDeps } from \"./io.js\";\nimport { MAX_INPUT_BYTES } from \"./limits.js\";\nimport { formatsSupporting, supportsOp, type Op } from \"./parsers.js\";\nimport { oneChunk, withinLimit, type ByteChunks } from \"./records.js\";\nimport type { RunResult } from \"./result.js\";\n\n/** A successfully-resolved input: the format (guaranteed to support the requested op) and the bytes. */\nexport interface ResolvedInput {\n /** The resolved format: guaranteed to satisfy `supportsOp(format, op)` for the requested op. */\n readonly format: CosyteFormat;\n /** The input bytes (a whole file or a drained stdin buffer); guaranteed non-empty. */\n readonly bytes: Uint8Array;\n}\n\n/**\n * The outcome of {@link resolveInput}: either the resolved input, or a ready-to-return value-free\n * {@link RunResult} carrying the diagnostic + exit code for whatever went wrong. A discriminated union\n * so a command reads `if (!r.ok) return r.result;` and then works with `r.input`.\n */\nexport type InputResolution =\n | { readonly ok: true; readonly input: ResolvedInput }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Resolve and read the input, and resolve its format, for a file-consuming command.\n *\n * @param source - The positional `<file|->` argument (or `undefined` when it was omitted).\n * @param formatOverride - The raw `--format` value, or `undefined` to autodetect by content.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param op - The wrapping operation the caller will run; the resolved format is confirmed to support\n * it (else a value-free `CLI_FORMAT_UNSUPPORTED` naming the supporting formats). Pass `null` when\n * the caller answers for capability itself: `redact` delegates to `@cosyte/deid`, whose per-format\n * coverage is a different matrix with its own two distinct refusals, so applying the parser\n * registry's matrix first would answer with the wrong code.\n * @returns `{ ok: true, input }` when the bytes read and the format resolved to a parser supporting\n * `op`; else `{ ok: false, result }` with a value-free usage/no-input/data-error {@link RunResult}.\n * @throws Propagates a **non-`CliError`** read failure unchanged, so the dispatcher maps it to\n * `CLI_INTERNAL` (a `CliError` read failure, e.g. a missing file, is caught and returned).\n * @example\n * ```ts\n * import { resolveInput } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await resolveInput(\"patient.json\", undefined, deps, \"parse\");\n * if (r.ok) r.input.format; // => \"fhir\"\n * ```\n */\nexport async function resolveInput(\n source: string | undefined,\n formatOverride: string | undefined,\n deps: RunDeps,\n op: Op | null,\n): Promise<InputResolution> {\n if (source === undefined) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <file> argument; pass a path or `-` to read stdin\",\n ),\n );\n }\n\n let bytes: Uint8Array;\n try {\n bytes = source === \"-\" ? await deps.readStdin() : await deps.readFile(source);\n } catch (e) {\n if (e instanceof CliError) return fail(e);\n throw e;\n }\n\n if (bytes.length === 0) {\n return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n const format = resolveFormat(bytes, formatOverride, op);\n if (format instanceof CliError) return fail(format);\n\n return { ok: true, input: { format, bytes } };\n}\n\n/**\n * A successfully-resolved **streaming** input: the format, plus the input as a stream of chunks with\n * the leading bytes detection consumed put back in front, so the consumer still sees the whole input\n * in order.\n */\nexport interface ResolvedInputStream {\n /** The resolved format: guaranteed to satisfy `supportsOp(format, op)` for the requested op. */\n readonly format: CosyteFormat;\n /** The whole input as chunks, size-limited: reading past the limit raises `CLI_INPUT_TOO_LARGE`. */\n readonly chunks: ByteChunks;\n}\n\n/**\n * The outcome of {@link resolveInputStream}: the resolved streaming input, or a ready-to-return\n * value-free {@link RunResult}. The same discriminated-union shape as {@link InputResolution}.\n */\nexport type InputStreamResolution =\n | { readonly ok: true; readonly input: ResolvedInputStream }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Resolve the input as a **stream of chunks** rather than one buffer, for a command that can act on a\n * record before the whole input has arrived.\n *\n * It reads only as far as the detection window ({@link DETECT_PREFIX_BYTES}) before deciding the\n * format, then hands back those bytes followed by the rest of the stream, unread. The size limit is\n * applied to the running total from the first chunk, so an over-limit input is refused while it is\n * still arriving and never assembled.\n *\n * When the caller's {@link RunDeps} carry no chunk readers, the whole-input readers are wrapped as a\n * single chunk: the same code path, the same output, only the granularity differs.\n *\n * @param source - The positional `<file|->` argument (or `undefined` when it was omitted).\n * @param formatOverride - The raw `--format` value, or `undefined` to autodetect by content.\n * @param deps - Injected readers ({@link RunDeps}); the chunk readers are used when present.\n * @param op - The wrapping operation the caller will run; the resolved format is confirmed to support it.\n * @param limit - The maximum number of input bytes to accept. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns `{ ok: true, input }` with the format and the chunk stream, else `{ ok: false, result }`\n * carrying the value-free usage / no-input / data-error {@link RunResult}.\n * @throws Propagates a **non-`CliError`** read failure unchanged, so the dispatcher maps it to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { resolveInputStream } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await resolveInputStream(\"patient.json\", undefined, deps, \"parse\");\n * if (r.ok) r.input.format; // => \"fhir\"\n * ```\n */\nexport async function resolveInputStream(\n source: string | undefined,\n formatOverride: string | undefined,\n deps: RunDeps,\n op: Op,\n limit: number = MAX_INPUT_BYTES,\n): Promise<InputStreamResolution> {\n if (source === undefined) {\n return fail(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <file> argument; pass a path or `-` to read stdin\",\n ),\n );\n }\n\n const iterator = withinLimit(openChunks(source, deps), limit)[Symbol.asyncIterator]();\n\n // Read just far enough to decide the format, and no further: the detection window when the format\n // is autodetected, a single byte (the empty-input check) when `--format` already decided it. Those\n // chunks are put back in front below, so nothing is consumed twice.\n const need = formatOverride === undefined ? DETECT_PREFIX_BYTES : 1;\n const head: Uint8Array[] = [];\n let headBytes = 0;\n try {\n while (headBytes < need) {\n const step = await iterator.next();\n if (step.done === true) break;\n head.push(step.value);\n headBytes += step.value.length;\n }\n } catch (e) {\n if (e instanceof CliError) return fail(e);\n throw e;\n }\n\n if (headBytes === 0) {\n return fail(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n const prefix = Buffer.concat(\n head.map((c) => Buffer.from(c.buffer, c.byteOffset, c.length)),\n Math.min(headBytes, DETECT_PREFIX_BYTES),\n );\n const format = resolveFormat(prefix, formatOverride, op);\n if (format instanceof CliError) {\n await iterator.return(undefined);\n return fail(format);\n }\n\n return { ok: true, input: { format, chunks: rejoin(head, iterator) } };\n}\n\n/** The chunk stream for `<file|->`: the injected chunk reader, or the whole-input reader as one chunk. */\nfunction openChunks(source: string, deps: RunDeps): ByteChunks {\n if (source === \"-\") {\n return deps.openStdin === undefined ? readerAsChunks(() => deps.readStdin()) : deps.openStdin();\n }\n return deps.openFile === undefined\n ? readerAsChunks(() => deps.readFile(source))\n : deps.openFile(source);\n}\n\n/** Adapt a whole-input reader to the chunk-stream shape (one chunk, or none when it is empty). */\nasync function* readerAsChunks(read: () => Promise<Uint8Array>): AsyncGenerator<Uint8Array> {\n yield* oneChunk(await read());\n}\n\n/** Re-attach the chunks detection consumed to the front of the unread remainder. */\nasync function* rejoin(\n head: readonly Uint8Array[],\n rest: AsyncIterator<Uint8Array>,\n): AsyncGenerator<Uint8Array> {\n for (const chunk of head) yield chunk;\n for (;;) {\n const step = await rest.next();\n if (step.done === true) return;\n yield step.value;\n }\n}\n\n/**\n * Resolve the format for an input from its **leading bytes**: an explicit `--format` override\n * (validated), else conservative content autodetection, then a check that the format supports the\n * requested operation. Shared by the buffered and streaming resolvers so the exit-code contract for a\n * bad `--format`, an undetectable input and an unwired (format, op) is applied in exactly one place.\n * A `null` op skips only that last check: the caller has its own capability matrix (see\n * {@link resolveInput}), and the read, the empty-input refusal and the `--format` validation are\n * unchanged.\n */\nfunction resolveFormat(\n prefix: Uint8Array,\n formatOverride: string | undefined,\n op: Op | null,\n): CosyteFormat | CliError {\n let format: CosyteFormat;\n if (formatOverride !== undefined) {\n const narrowed = asCosyteFormat(formatOverride);\n if (narrowed === null) {\n return new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"unknown --format value; expected one of hl7, fhir, dicom, x12, ccda, ncpdp, astm, mllp\",\n );\n }\n format = narrowed;\n } else {\n const detected = detectFormat(prefix);\n // `format` is non-null iff detection is `certain`; `none`/`ambiguous` become a value-free data error.\n if (detected.format === null) return detectionError(detected);\n format = detected.format;\n }\n\n if (op !== null && !supportsOp(format, op)) {\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' does not support \\`${op}\\` in this CLI build ` +\n `(${op} supports: ${formatsSupporting(op).join(\", \")})`,\n );\n }\n return format;\n}\n\n/** Wrap a {@link CliError} as a failed resolution (either shape). */\nfunction fail(e: CliError): { readonly ok: false; readonly result: RunResult } {\n return { ok: false, result: errorResult(e) };\n}\n","/**\n * The CLI's **global PHI display posture**: the single mechanism that gates whether *any* input\n * value may appear on a **secondary surface** (stderr, a diagnostic, a warning, a log line). The CLI\n * is **value-free by default**: every secondary surface carries only positional/structural context\n * (a stable code, a segment/field index, a byte offset, a file path, a format name), never a name, a\n * DOB, an MRN, or a field value. `stdout` is the **data channel** (the user's explicit request) and\n * is exempt: the posture governs everything *but* stdout.\n *\n * `--unsafe-show-values` is the **single, explicit, loud door** to a value on a secondary surface. It\n * is off by default, PHI-exposing by design, and its effect flows through exactly one chokepoint here\n * ({@link unsafeInputSuffix}) so the \"a value appears on a secondary surface **iff** the flag is set\"\n * property is provable in one place rather than scattered across commands.\n *\n * @packageDocumentation\n */\n\n/**\n * The resolved PHI display posture for one invocation. `showValues` is `true` **only** when the user\n * passed `--unsafe-show-values`; every value-echoing decision reads this one flag.\n */\nexport interface PhiPosture {\n /** `true` iff `--unsafe-show-values` was given: a value may appear on a secondary surface. */\n readonly showValues: boolean;\n}\n\n/** The default, safe posture: no value ever reaches a secondary surface. */\nexport const VALUE_FREE: PhiPosture = { showValues: false };\n\n/** The opted-in, PHI-exposing posture selected by `--unsafe-show-values`. */\nexport const SHOW_VALUES: PhiPosture = { showValues: true };\n\n/** The single global flag token that opts into showing values on secondary surfaces. */\nexport const UNSAFE_SHOW_VALUES_FLAG = \"--unsafe-show-values\";\n\n/**\n * The maximum number of leading input bytes an `--unsafe-show-values` diagnostic may echo. Bounded so\n * an unsafe excerpt stays a single, readable diagnostic line rather than dumping a whole message.\n */\nexport const UNSAFE_EXCERPT_MAX = 200;\n\n/**\n * Resolve the global `--unsafe-show-values` flag out of an argument vector, **order-independently**\n * (it may appear before or after the subcommand), and return the posture plus the argv with every\n * occurrence of the flag removed, so each command's own `parseArgs` never sees it and cannot reject\n * it as unknown. This is the one place the flag is recognised.\n *\n * @param argv - The raw arguments (after the program name).\n * @returns The resolved {@link PhiPosture} and the flag-stripped argv.\n * @example\n * ```ts\n * import { extractPhiPosture } from \"@cosyte/cli\";\n *\n * extractPhiPosture([\"parse\", \"x.hl7\"]).posture.showValues; // => false\n * extractPhiPosture([\"--unsafe-show-values\", \"parse\", \"x.hl7\"]).posture.showValues; // => true\n * extractPhiPosture([\"parse\", \"x.hl7\", \"--unsafe-show-values\"]).argv; // => [\"parse\", \"x.hl7\"]\n * ```\n */\nexport function extractPhiPosture(argv: readonly string[]): {\n posture: PhiPosture;\n argv: string[];\n} {\n const showValues = argv.includes(UNSAFE_SHOW_VALUES_FLAG);\n const cleaned = argv.filter((a) => a !== UNSAFE_SHOW_VALUES_FLAG);\n return { posture: showValues ? SHOW_VALUES : VALUE_FREE, argv: cleaned };\n}\n\n/**\n * Build the **only** value-bearing addition the CLI ever appends to a secondary (stderr) surface: a\n * bounded, single-line excerpt of the offending input, shown **iff** `--unsafe-show-values` is set.\n * Under the default value-free posture it returns the empty string, so a diagnostic stays value-free\n * unless the user explicitly opted in. This is the single chokepoint the PHI-leak matrix pins.\n *\n * @param bytes - The input the CLI is operating on (only the leading {@link UNSAFE_EXCERPT_MAX} bytes\n * are considered).\n * @param posture - The resolved {@link PhiPosture}.\n * @returns `\"\"` under the value-free default; otherwise a ` [unsafe-show-values] …` suffix carrying a\n * bounded, newline-flattened prefix of `bytes`.\n * @example\n * ```ts\n * import { unsafeInputSuffix, VALUE_FREE, SHOW_VALUES } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"bad message\");\n * unsafeInputSuffix(bytes, VALUE_FREE); // => \"\"\n * unsafeInputSuffix(bytes, SHOW_VALUES); // => \" [unsafe-show-values] offending input …: bad message\"\n * ```\n */\nexport function unsafeInputSuffix(bytes: Uint8Array, posture: PhiPosture): string {\n if (!posture.showValues) return \"\";\n const text = new TextDecoder(\"utf-8\", { fatal: false })\n .decode(bytes.subarray(0, UNSAFE_EXCERPT_MAX))\n .replace(/[\\r\\n\\t]+/g, \" \")\n .trim();\n if (text.length === 0) return \"\";\n return ` [unsafe-show-values] offending input (first ${String(UNSAFE_EXCERPT_MAX)} bytes): ${text}`;\n}\n","/**\n * The **wrapped-parser failure boundary**: the single, value-free way every command turns a thrown\n * parser/codec exception into a {@link RunResult}. A wrapped library raises a fatal on genuinely\n * unparseable input; its message (and, for HL7, its `snippet`) can embed the offending bytes, so the\n * CLI **never** surfaces that message. It surfaces only a stable, PHI-free code token (via\n * {@link extractStableCode}) plus the format name: the parsers' \"warning = code + position, never a\n * value\" rule at the CLI edge.\n *\n * The one, opt-in exception is `--unsafe-show-values`, whose bounded excerpt is appended through the\n * lone chokepoint in `core/phi.ts` ({@link unsafeInputSuffix}), so the \"a value appears on a\n * secondary surface **iff** the flag is set\" property stays provable in one place, uniformly across\n * `parse`/`validate`/`inspect`/`fmt`.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { CosyteFormat } from \"./format.js\";\nimport { unsafeInputSuffix, type PhiPosture } from \"./phi.js\";\nimport type { RunResult } from \"./result.js\";\n\n/**\n * Pull a `code` off a thrown value **only** when it is a PHI-free constant token\n * (`^[A-Z][A-Z0-9_]*$`: a letter-led UPPER_SNAKE code like `MALFORMED_JSON`), e.g. a wrapped\n * parser's stable fatal code. Anything else (no `code`, a non-string, a non-token, or a **pure-digit**\n * value that could be a raw identifier) yields `null`, so a parser exception that embedded input bytes\n * in a `code`-shaped field can never reach a diagnostic.\n *\n * @param e - A caught value.\n * @returns The stable code token, or `null`.\n * @example\n * ```ts\n * import { extractStableCode } from \"@cosyte/cli\";\n *\n * extractStableCode({ code: \"MALFORMED_JSON\" }); // => \"MALFORMED_JSON\"\n * extractStableCode(new Error(\"boom\")); // => null\n * ```\n */\nexport function extractStableCode(e: unknown): string | null {\n if (typeof e === \"object\" && e !== null && \"code\" in e) {\n const raw: unknown = e.code;\n if (typeof raw === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(raw)) return raw;\n }\n return null;\n}\n\n/**\n * Build the value-free {@link RunResult} for a **wrapped-parser rejection**: a `CLI_PARSE_FAILED`\n * data error (exit `65`). The stderr line names the format and, when the thrown value carried one, a\n * stable code token in parentheses; it **never** echoes the parser's message or the input bytes. Under\n * `--unsafe-show-values` (and only then) a bounded excerpt of the offending input is appended via the\n * single {@link unsafeInputSuffix} chokepoint.\n *\n * @param format - The format whose parser rejected the input.\n * @param bytes - The offending input (only consulted for the opt-in unsafe excerpt).\n * @param posture - The resolved {@link PhiPosture}; the excerpt is appended only when it opts in.\n * @param e - The caught exception (its `code`, if a stable token, is surfaced: nothing else).\n * @returns A value-free `CLI_PARSE_FAILED` / exit-`65` {@link RunResult}.\n * @example\n * ```ts\n * import { parseFailureResult, VALUE_FREE } from \"@cosyte/cli\";\n *\n * const bytes = new TextEncoder().encode(\"not hl7\");\n * parseFailureResult(\"hl7\", bytes, VALUE_FREE, { code: \"MISSING_MSH\" }).exit; // => 65\n * ```\n */\nexport function parseFailureResult(\n format: CosyteFormat,\n bytes: Uint8Array,\n posture: PhiPosture,\n e: unknown,\n): RunResult {\n const code = extractStableCode(e);\n const detail = code === null ? \"\" : ` (${code})`;\n const suffix = unsafeInputSuffix(bytes, posture);\n return {\n stdout: \"\",\n stderr: `cosyte: ${CLI_CODES.CLI_PARSE_FAILED}: the ${format} parser rejected the input${detail}${suffix}\\n`,\n exit: EXIT.DATAERR,\n };\n}\n","/**\n * Input I/O for the CLI: read the bytes to operate on from a **file argument** or from **stdin**\n * (`-`), with a value-free failure mode. The CLI never writes a temp file and never logs to a file;\n * this module only *reads*.\n *\n * Reading comes in two shapes. The **whole-input** readers ({@link readFileBytes},\n * {@link readStreamBytes}) hand a command one buffer, which is what a single-message command wants.\n * The **chunk** readers ({@link fileChunks}, {@link streamChunks}) hand it an async stream of chunks,\n * which is what a multi-record command wants: it can emit a record's output before the rest of the\n * input has arrived, and the CLI's own size limit can be enforced against the **running total**\n * rather than after an oversized input has already been assembled.\n *\n * The reader functions are injected into the command layer as {@link RunDeps} so the whole dispatch\n * path is testable without touching `process`: the real `process.stdin` wiring lives in the thin\n * `bin` entry, and so does the one function in {@link RunDeps} that writes rather than reads.\n *\n * @packageDocumentation\n */\n\nimport { open } from \"node:fs/promises\";\nimport type { Readable } from \"node:stream\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport { inputTooLargeError, MAX_INPUT_BYTES } from \"./limits.js\";\n\n/**\n * The injectable I/O side-effects the dispatcher needs. Kept tiny and pure-ish so tests drive the\n * CLI end to end with in-memory fakes and no real filesystem, stdin or stdout.\n *\n * The two whole-input readers are required; the chunk readers and the output sink are **optional**,\n * and a caller that omits them still gets identical output. They are the difference between reading\n * a stream as it arrives and being handed one buffer: with them, a multi-record `parse` emits each\n * record as it is produced and refuses an over-limit input while it is still arriving; without them,\n * the same code path runs over a single chunk and returns its output on the result's `stdout` as\n * before.\n */\nexport interface RunDeps {\n /** Read a file's bytes, or raise a `CLI_NO_INPUT` {@link CliError} if it cannot be read. */\n readonly readFile: (path: string) => Promise<Uint8Array>;\n /** Read all of stdin's bytes. */\n readonly readStdin: () => Promise<Uint8Array>;\n /** Optional: open a file as a stream of byte chunks (see {@link fileChunks}). */\n readonly openFile?: (path: string) => AsyncIterable<Uint8Array>;\n /** Optional: open stdin as a stream of byte chunks (see {@link streamChunks}). */\n readonly openStdin?: () => AsyncIterable<Uint8Array>;\n /**\n * Optional: write one piece of the data channel **as it is produced**. When present, a multi-record\n * `parse` writes each record's NDJSON line through here instead of accumulating them, and the\n * returned result's `stdout` is empty because the output has already been delivered. May throw (a\n * consumer that closed the pipe); the caller turns that into a value-free\n * `CLI_OUTPUT_WRITE_FAILED`.\n */\n readonly writeStdout?: (chunk: string) => void;\n}\n\n/** The value-free failure for a file that is missing, a directory, or otherwise unreadable. */\nfunction noInputError(path: string): CliError {\n return new CliError(\n CLI_CODES.CLI_NO_INPUT,\n EXIT.NOINPUT,\n `cannot read input file: ${path} (does it exist and is it readable?)`,\n );\n}\n\n/**\n * Read a file into bytes, mapping any read failure to a **value-free** `CLI_NO_INPUT` /\n * {@link EXIT.NOINPUT} error. The path is structural context (the user supplied it), so it may appear\n * in the message; the file *contents* never do.\n *\n * A file whose size already exceeds `limit` is refused **before it is read**, with the value-free\n * over-limit data error, so an oversized file is never allocated in the first place. The size is read\n * from the **open descriptor** rather than from the path, so what is measured and what is read are the\n * same file even if the path is replaced in between.\n *\n * @param path - The file path to read.\n * @param limit - The maximum number of bytes to accept. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns The file bytes.\n * @throws {CliError} `CLI_NO_INPUT` (exit `66`) when the file is missing, a directory, or unreadable;\n * `CLI_INPUT_TOO_LARGE` (exit `65`) when it is larger than `limit`.\n * @example\n * ```ts throws\n * import { readFileBytes } from \"@cosyte/cli\";\n *\n * await readFileBytes(\"/no/such/file\"); // throws CliError CLI_NO_INPUT\n * ```\n */\nexport async function readFileBytes(\n path: string,\n limit: number = MAX_INPUT_BYTES,\n): Promise<Uint8Array> {\n let handle;\n try {\n handle = await open(path, \"r\");\n } catch {\n throw noInputError(path);\n }\n try {\n const info = await handle.stat();\n if (info.isFile() && info.size > limit) throw inputTooLargeError(limit);\n return await handle.readFile();\n } catch (e) {\n // The over-limit refusal is final; anything else is an unreadable input, reported value-free.\n if (e instanceof CliError) throw e;\n throw noInputError(path);\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Drain a readable stream (e.g. `process.stdin`) into a single byte buffer, refusing an over-limit\n * stream against the **running total**: the read is abandoned the moment the accumulated size passes\n * `limit`, so the bytes past it are never allocated and no platform allocation ceiling is ever\n * reached.\n *\n * @param stream - The readable stream to drain.\n * @param limit - The maximum number of bytes to accept. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns The concatenated bytes.\n * @throws {CliError} `CLI_INPUT_TOO_LARGE` (exit `65`) as soon as the running total passes `limit`.\n * @example\n * ```ts\n * import { Readable } from \"node:stream\";\n * import { readStreamBytes } from \"@cosyte/cli\";\n *\n * const bytes = await readStreamBytes(Readable.from([Buffer.from(\"MSH|\")]));\n * bytes.length; // => 4\n * ```\n */\nexport async function readStreamBytes(\n stream: Readable,\n limit: number = MAX_INPUT_BYTES,\n): Promise<Uint8Array> {\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of stream as AsyncIterable<Buffer | string>) {\n const buf = typeof chunk === \"string\" ? Buffer.from(chunk, \"utf-8\") : chunk;\n total += buf.length;\n if (total > limit) throw inputTooLargeError(limit);\n chunks.push(buf);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Open a readable stream (e.g. `process.stdin`) as a stream of byte **chunks**, in arrival order.\n * Unlike {@link readStreamBytes} this never concatenates: the consumer decides what to keep, which is\n * what lets a multi-record command emit a record before the rest of the input has been read.\n *\n * @param stream - The readable stream to iterate.\n * @returns An async iterable of the stream's chunks, string chunks encoded as UTF-8.\n * @example\n * ```ts\n * import { Readable } from \"node:stream\";\n * import { streamChunks } from \"@cosyte/cli\";\n *\n * const seen: number[] = [];\n * for await (const c of streamChunks(Readable.from([Buffer.from(\"MS\"), Buffer.from(\"H|\")]))) {\n * seen.push(c.length);\n * }\n * seen.length; // => 2\n * ```\n */\nexport async function* streamChunks(stream: Readable): AsyncGenerator<Uint8Array> {\n for await (const chunk of stream as AsyncIterable<Buffer | string>) {\n yield typeof chunk === \"string\" ? Buffer.from(chunk, \"utf-8\") : chunk;\n }\n}\n\n/**\n * Open a file as a stream of byte **chunks**, with the same value-free failure mode as\n * {@link readFileBytes}: a missing, unreadable or non-file path is a `CLI_NO_INPUT` error, never a\n * raw filesystem exception.\n *\n * @param path - The file path to read.\n * @returns An async iterable of the file's chunks.\n * @throws {CliError} `CLI_NO_INPUT` (exit `66`) when the file cannot be opened or read.\n * @example\n * ```ts throws\n * import { fileChunks } from \"@cosyte/cli\";\n *\n * for await (const chunk of fileChunks(\"/no/such/file\")) chunk.length; // throws CLI_NO_INPUT\n * ```\n */\nexport async function* fileChunks(path: string): AsyncGenerator<Uint8Array> {\n let handle;\n try {\n handle = await open(path, \"r\");\n } catch {\n throw noInputError(path);\n }\n try {\n const stream = handle.createReadStream();\n try {\n for await (const chunk of stream as AsyncIterable<Buffer>) yield chunk;\n } catch {\n throw noInputError(path);\n }\n } finally {\n await handle.close();\n }\n}\n","/**\n * The **de-identification seam**: the single, documented plug-in point where the `redact` / `deid`\n * command delegates to **`@cosyte/deid`**. Everything the CLI knows about de-identification lives\n * here, and it is deliberately little: which formats the delegate covers, how to reach it, and how to\n * turn its result into the CLI's own value-free shapes.\n *\n * ## The CLI ships no redactor of its own (the boundary decision)\n *\n * A \"minimal built-in Safe-Harbor pass over the obvious PHI loci\" (the HL7 `PID` segment,\n * `Patient.name`/`Patient.address` in FHIR) is **deliberately rejected**. Real messages carry PHI far\n * beyond those loci: HL7 `NK1`/`GT1`/`IN1`/`OBX`/`NTE`, FHIR extensions and contained resources,\n * free-text notes. A redactor that scrubs the obvious fields and emits output that *looks*\n * de-identified while silently leaving PHI behind is a **false-safety impression**. A `redact` that\n * under-redacts is worse than no `redact`. So the CLI adds no policy, no locus map, no transform and\n * no fallback scrub: it delegates, or it refuses.\n *\n * ## What \"covered\" means, per format\n *\n * A format is covered when the delegate ships an adapter for the standard this CLI actually resolves\n * **and** the CLI can carry the de-identified result on its text data channel. Both halves bite:\n *\n * - `ncpdp`: the delegate's adapter is NCPDP **Telecom**, while this CLI resolves NCPDP **SCRIPT**.\n * The subpath exists; the coverage does not.\n * - `dicom`: the delegate covers it, but its result is a Part 10 **byte** stream and this CLI's data\n * channel is a `string`. That is the CLI's own limit, so it is reported as the CLI's own\n * unsupported (format, operation) cell rather than blamed on the delegate.\n * - `astm`, `mllp`: no adapter at all.\n *\n * ## The key context, and why it is ephemeral\n *\n * The delegate's default policy removes MRN / account / member identifiers rather than replacing\n * them with a keyed surrogate, so a default run needs no key. The CLI binds a key context anyway,\n * because a keyed transform with no key context is a fatal there, never an unkeyed fallback, and the\n * CLI holds no key material and offers no key surface. So it creates a **per-invocation ephemeral\n * key**: any surrogate the delegate mints is consistent within one output and deliberately **not**\n * stable across runs (no cross-run linkage). That property is disclosed on the diagnostic channel\n * rather than left to be discovered.\n *\n * @packageDocumentation\n */\n\nimport { randomBytes } from \"node:crypto\";\n\n// TYPE-ONLY, and the word `type` is load-bearing: dropping it turns this into an eager load of an\n// optional package, which would break every command in an install that does not have it.\nimport type * as CosyteDeid from \"@cosyte/deid\";\n\nimport { CLI_CODES, CliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { CosyteFormat } from \"./format.js\";\nimport { loadFhir, loadOptional, loadOptionalPackage } from \"./parsers.js\";\nimport { extractStableCode } from \"./wrap.js\";\n\n/** The npm package the whole de-identification capability is delegated to. */\nexport const DEID_PACKAGE = \"@cosyte/deid\";\n\n/** The delegate's root module, as this file consumes it (kept off the published surface). */\ntype DeidCore = typeof CosyteDeid;\n\n/**\n * What the delegate can do for one format, from this CLI's point of view:\n *\n * - `covered`: an adapter for the standard this CLI resolves, serializable onto the text channel.\n * - `no-adapter`: the delegate does not de-identify this format (`CLI_NOT_IMPLEMENTED`, exit `69`).\n * - `unserializable`: the delegate covers it, but the result cannot ride a text stdout\n * (`CLI_FORMAT_UNSUPPORTED`, exit `65`: the CLI's own limit, not the delegate's).\n */\nexport type DeidCoverage = \"covered\" | \"no-adapter\" | \"unserializable\";\n\n/** A format the delegate de-identifies and the CLI can serialize. */\nexport type DeidCoveredFormat = \"hl7\" | \"fhir\" | \"x12\" | \"ccda\";\n\n/**\n * The honest per-format de-identification matrix, the `redact` analogue of the parser registry's\n * operation matrix. Every one of the eight formats has an entry, so a new format cannot be added\n * without answering for it here.\n *\n * @example\n * ```ts\n * import { DEID_COVERAGE } from \"@cosyte/cli\";\n *\n * DEID_COVERAGE.hl7; // => \"covered\"\n * DEID_COVERAGE.dicom; // => \"unserializable\"\n * ```\n */\nexport const DEID_COVERAGE: Readonly<Record<CosyteFormat, DeidCoverage>> = {\n hl7: \"covered\",\n fhir: \"covered\",\n x12: \"covered\",\n ccda: \"covered\",\n // The delegate's NCPDP adapter is Telecom; this CLI resolves SCRIPT.\n ncpdp: \"no-adapter\",\n astm: \"no-adapter\",\n mllp: \"no-adapter\",\n // Covered by the delegate, but its result is Part 10 bytes and stdout here is text.\n dicom: \"unserializable\",\n};\n\n/**\n * What the delegate can do for `format`.\n *\n * @param format - The resolved format.\n * @returns That format's {@link DeidCoverage}.\n * @example\n * ```ts\n * import { deidCoverage } from \"@cosyte/cli\";\n *\n * deidCoverage(\"ncpdp\"); // => \"no-adapter\"\n * ```\n */\nexport function deidCoverage(format: CosyteFormat): DeidCoverage {\n return DEID_COVERAGE[format];\n}\n\n/**\n * Whether `format` is one the delegate de-identifies and the CLI can serialize.\n *\n * @param format - The resolved format.\n * @returns `true` iff `redact` produces output for it.\n * @example\n * ```ts\n * import { isDeidCovered } from \"@cosyte/cli\";\n *\n * isDeidCovered(\"x12\"); // => true\n * ```\n */\nexport function isDeidCovered(format: CosyteFormat): format is DeidCoveredFormat {\n return DEID_COVERAGE[format] === \"covered\";\n}\n\n/**\n * The formats `redact` produces output for, sorted: the single source the help text, the published\n * documentation and the tests all read, so the three cannot drift.\n *\n * @returns The covered format names, sorted.\n * @example\n * ```ts\n * import { deidCoveredFormats } from \"@cosyte/cli\";\n *\n * deidCoveredFormats(); // => [\"ccda\", \"fhir\", \"hl7\", \"x12\"]\n * ```\n */\nexport function deidCoveredFormats(): readonly CosyteFormat[] {\n return (Object.keys(DEID_COVERAGE) as CosyteFormat[]).filter(isDeidCovered).sort();\n}\n\n/**\n * One entry of the delegate's value-free manifest, narrowed to the fields the CLI renders. The\n * `locus` is a **path, never a value**, by the delegate's own contract; nothing here carries an input\n * value, which is what lets the manifest go on the diagnostic channel at all.\n */\nexport interface DeidManifestRecord {\n /** The identifier category acted on. */\n readonly category: string;\n /** The transform applied. */\n readonly transform: string;\n /** The structural path acted on: never a value. */\n readonly locus: string;\n /** How many values at this locus were acted on. */\n readonly count: number;\n /** What happened: `transformed`, `removed`, or the fail-closed `blocked`. */\n readonly disposition: string;\n /** The delegate's stable disposition code. */\n readonly code: string;\n}\n\n/** The fail-closed disposition: the delegate reports it could not handle the element. */\nexport const DEID_BLOCKED = \"blocked\";\n\n/** A completed de-identification pass: the serialized document plus the delegate's manifest. */\nexport interface RedactOutcome {\n /** The de-identified document, serialized exactly as this format's wrapped serializer emits it. */\n readonly output: string;\n /** The delegate's value-free manifest, in locus order. */\n readonly manifest: readonly DeidManifestRecord[];\n}\n\n/**\n * The delegate, reduced to what the command needs: its own published honesty label and version, and\n * one call that de-identifies an input. Deliberately CLI-owned shapes, so the delegate's types never\n * reach this package's published surface.\n */\nexport interface DeidDelegate {\n /** The delegate's own output label, quoted verbatim; the CLI asserts no standard of its own. */\n readonly label: string;\n /** The delegate's own version string. */\n readonly version: string;\n /**\n * De-identify one input under the delegate's default policy.\n *\n * @param format - A covered format.\n * @param bytes - The input bytes.\n * @returns The serialized de-identified document and the value-free manifest.\n */\n readonly redact: (format: DeidCoveredFormat, bytes: Uint8Array) => Promise<RedactOutcome>;\n}\n\n/**\n * The value-free reason `redact`/`deid` reports when the de-identification library is absent from the\n * install. It is an `optionalDependency`, so a copy without it degrades rather than crashing.\n */\nexport const DEID_UNAVAILABLE_REASON =\n `the ${DEID_PACKAGE} de-identification library is not installed; install it to use ` +\n `redact/deid (it is an optional dependency). The CLI ships no built-in redactor: a partial ` +\n `Safe-Harbor scrub over only the obvious PHI loci would leave PHI behind and present a ` +\n `false-safety impression, so nothing is emitted`;\n\n/** The value-free reason a covered format's own de-identification adapter could not be loaded. */\nfunction adapterUnavailable(format: DeidCoveredFormat): string {\n return (\n `the ${DEID_PACKAGE}/${format} de-identification adapter could not be loaded; it needs both ` +\n `${DEID_PACKAGE} and the @cosyte/${format} parser to be installed`\n );\n}\n\n/**\n * Run the wrapped parser, mapping a rejection to a **value-free** `CLI_PARSE_FAILED` (exit `65`):\n * the format name and, when the thrown value carried one, a stable code token. The parser's own\n * message is discarded, because it can embed the offending bytes.\n *\n * Unlike the other commands' parse boundary this appends **no** `--unsafe-show-values` excerpt: on\n * `redact` an excerpt of the input a user asked to have stripped is precisely the leak the command\n * exists to prevent.\n *\n * @param format - The format whose parser is running.\n * @param parse - The parse call.\n * @returns Whatever `parse` returned.\n * @throws {CliError} `CLI_PARSE_FAILED` (exit `65`) when `parse` rejects the input.\n * @example\n * ```ts\n * const msg = parseOrFail(\"hl7\", () => parseHL7(bytes));\n * ```\n */\nexport function parseOrFail<T>(format: DeidCoveredFormat, parse: () => T): T {\n try {\n return parse();\n } catch (e) {\n const code = extractStableCode(e);\n throw new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n `the ${format} parser rejected the input${code === null ? \"\" : ` (${code})`}`,\n );\n }\n}\n\n/**\n * Run the delegate, mapping a fatal it reports to a **value-free** `CLI_DEID_INCOMPLETE` (exit `1`):\n * its own stable code and nothing else, the exception's message discarded exactly as a parser's is.\n * An error carrying **no** stable code is not the delegate reporting a condition it recognises, so\n * it propagates untouched to the dispatcher's internal-error boundary: a bug stays a bug (`70`)\n * rather than being dressed up as an operation-level failure.\n *\n * @param run - The de-identification call.\n * @returns The completed {@link RedactOutcome}.\n * @throws {CliError} `CLI_DEID_INCOMPLETE` (exit `1`) on a fatal the delegate names; anything else\n * propagates unchanged.\n * @example\n * ```ts\n * const outcome = deidentifyOrFail(() => ({ output, manifest }));\n * ```\n */\nexport function deidentifyOrFail(run: () => RedactOutcome): RedactOutcome {\n try {\n return run();\n } catch (e) {\n const code = extractStableCode(e);\n if (code === null) throw e;\n throw new CliError(\n CLI_CODES.CLI_DEID_INCOMPLETE,\n EXIT.INVALID,\n `the ${DEID_PACKAGE} de-identifier could not complete this input (${code}); no output was emitted`,\n );\n }\n}\n\n/** Decode input bytes as tolerant UTF-8 (the text parsers accept a string). */\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n}\n\n/** Narrow the delegate's manifest to the CLI's own record shape (no delegate type escapes). */\nfunction toRecords(\n manifest: readonly {\n category: string;\n transform: string;\n locus: string;\n count: number;\n disposition: string;\n code: string;\n }[],\n): readonly DeidManifestRecord[] {\n return manifest.map((e) => ({\n category: e.category,\n transform: e.transform,\n locus: e.locus,\n count: e.count,\n disposition: e.disposition,\n code: e.code,\n }));\n}\n\n/**\n * Load the delegate and bind it to a **per-invocation ephemeral key**, returning the small surface\n * the command uses. The root import is the availability probe: the command calls this **before it\n * reads any input**, so an install without `@cosyte/deid` never touches the bytes it cannot strip.\n *\n * Every import here is dynamic and per-format, so no other command loads the delegate, and each one\n * degrades to a value-free `CLI_PARSER_UNAVAILABLE` (exit `69`) when the package is absent.\n *\n * @param importCore - The root-module import thunk; injectable so a test can force a resolver failure.\n * @returns The bound {@link DeidDelegate}.\n * @throws {CliError} `CLI_PARSER_UNAVAILABLE` (exit `69`) when the library is absent.\n * @example\n * ```ts\n * const delegate = await loadDeidDelegate();\n * delegate.label; // the delegate's own output label\n * ```\n */\nexport async function loadDeidDelegate(\n importCore: () => Promise<DeidCore> = () => import(\"@cosyte/deid\"),\n): Promise<DeidDelegate> {\n const core = await loadOptionalPackage(DEID_UNAVAILABLE_REASON, importCore);\n // The key never leaves this scope, is never written anywhere, and is discarded when the process\n // exits: within one output the surrogates are consistent, across runs they are unlinkable.\n const context = core.createDeidContext({ key: randomBytes(32) });\n\n return {\n label: core.OUTPUT_LABEL,\n version: core.VERSION,\n redact: async (format, bytes) => {\n switch (format) {\n case \"hl7\": {\n const { parseHL7 } = await import(\"@cosyte/hl7\");\n const { deidentifyHl7 } = await loadOptionalPackage(\n adapterUnavailable(\"hl7\"),\n () => import(\"@cosyte/deid/hl7\"),\n );\n const msg = parseOrFail(\"hl7\", () => parseHL7(Buffer.from(bytes)));\n return deidentifyOrFail(() => {\n const { document, manifest } = deidentifyHl7(msg, { context });\n return { output: document.toString(), manifest: toRecords(manifest) };\n });\n }\n case \"fhir\": {\n const { parseResource, serializeResource } = await loadFhir();\n const { deidentifyFhir } = await loadOptionalPackage(\n adapterUnavailable(\"fhir\"),\n () => import(\"@cosyte/deid/fhir\"),\n );\n const resource = parseOrFail(\"fhir\", () => parseResource(decode(bytes)).resource);\n return deidentifyOrFail(() => {\n const { document, manifest } = deidentifyFhir(resource, { context });\n return { output: serializeResource(document), manifest: toRecords(manifest) };\n });\n }\n case \"x12\": {\n const { parseX12 } = await loadOptional(\"x12\", () => import(\"@cosyte/x12\"));\n const { deidentifyX12 } = await loadOptionalPackage(\n adapterUnavailable(\"x12\"),\n () => import(\"@cosyte/deid/x12\"),\n );\n const interchange = parseOrFail(\"x12\", () => parseX12(Buffer.from(bytes)));\n return deidentifyOrFail(() => {\n const { x12, manifest } = deidentifyX12(interchange, { context });\n return { output: x12, manifest: toRecords(manifest) };\n });\n }\n case \"ccda\": {\n const { parseCcda, serializeCcda } = await loadOptional(\n \"ccda\",\n () => import(\"@cosyte/ccda\"),\n );\n const { deidentifyCcda } = await loadOptionalPackage(\n adapterUnavailable(\"ccda\"),\n () => import(\"@cosyte/deid/ccda\"),\n );\n const doc = parseOrFail(\"ccda\", () => parseCcda(decode(bytes)));\n return deidentifyOrFail(() => {\n const { document, manifest } = deidentifyCcda(doc, { context });\n return { output: serializeCcda(document), manifest: toRecords(manifest) };\n });\n }\n }\n },\n };\n}\n\n/**\n * Whether de-identification is available, and (while it is not) the value-free reason why. The one\n * function that answers \"is the ground layer here?\", consulted **before any input is read** so a\n * `redact` invocation never touches PHI it cannot strip.\n */\nexport interface DeidAvailability {\n /** `true` when `@cosyte/deid` resolves in this install. */\n readonly available: boolean;\n /** A value-free explanation: the delegate's own label and version, or why it is unavailable. */\n readonly reason: string;\n}\n\n/**\n * Report the current de-identification availability. This is the single documented flip point: it\n * resolves the delegated library rather than asserting anything about it.\n *\n * @param load - The delegate loader; injectable so a test can drive the unavailable branch.\n * @returns `{ available: true }` with the delegate's own label and version, else `{ available: false }`\n * with the value-free {@link DEID_UNAVAILABLE_REASON}.\n * @example\n * ```ts\n * import { deidStatus } from \"@cosyte/cli\";\n *\n * (await deidStatus()).available; // => true when @cosyte/deid is installed\n * ```\n */\nexport async function deidStatus(\n load: () => Promise<DeidDelegate> = loadDeidDelegate,\n): Promise<DeidAvailability> {\n try {\n const delegate = await load();\n return {\n available: true,\n reason: `${DEID_PACKAGE} ${delegate.version}: ${delegate.label}`,\n };\n } catch (e) {\n if (e instanceof CliError) return { available: false, reason: DEID_UNAVAILABLE_REASON };\n throw e;\n }\n}\n","/**\n * `cosyte completion <bash|zsh|fish>`\n *\n * Print a shell completion script for `cosyte`, generated from the command tree, to **stdout**: the\n * user pipes it into their shell (`source <(cosyte completion bash)`) or saves it to their completions\n * directory. The script is static and value-free: it names commands, subcommand tokens, and flags,\n * never any input. An unknown or missing shell is a usage error (exit `2`), never a silent no-op.\n *\n * @packageDocumentation\n */\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunResult } from \"../core/result.js\";\n\n/** The subcommands offered for completion (mirrors the dispatcher in `core/run.ts`). */\nconst COMMANDS = [\n \"parse\",\n \"validate\",\n \"inspect\",\n \"fmt\",\n \"convert\",\n \"map-codes\",\n \"redact\",\n \"deid\",\n \"mcp\",\n \"completion\",\n] as const;\n\n/** The common flags offered across the file-consuming commands. */\nconst FLAGS = [\n \"--format\",\n \"--json\",\n \"--ndjson\",\n \"--quiet\",\n \"--no-color\",\n \"--unsafe-show-values\",\n \"--help\",\n \"--version\",\n] as const;\n\n/** The shells `completion` can emit a script for. */\nconst SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\ntype Shell = (typeof SHELLS)[number];\n\n/**\n * Run the `completion` command.\n *\n * @param args - The arguments after the `completion` subcommand token; the first is the shell name.\n * @returns A {@link RunResult}: the completion script on `stdout` (exit `0`), or a value-free usage\n * error (exit `2`) when the shell is missing or unrecognised.\n * @example\n * ```ts\n * import { completionCommand } from \"@cosyte/cli\";\n *\n * completionCommand([\"bash\"]).exit; // => 0\n * completionCommand([\"powershell\"]).exit; // => 2\n * ```\n */\nexport function completionCommand(args: string[]): RunResult {\n const shell = args[0];\n if (shell === undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `missing shell; usage: cosyte completion <${SHELLS.join(\"|\")}>`,\n ),\n );\n }\n if (!isShell(shell)) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unknown shell '${shell}'; supported: ${SHELLS.join(\", \")}`,\n ),\n );\n }\n return { stdout: SCRIPTS[shell](), stderr: \"\", exit: EXIT.OK };\n}\n\n/** Narrow an arbitrary string to a supported {@link Shell}. */\nfunction isShell(value: string): value is Shell {\n return (SHELLS as readonly string[]).includes(value);\n}\n\n/** The per-shell script generators. Each is static text built from {@link COMMANDS} + {@link FLAGS}. */\nconst SCRIPTS: Readonly<Record<Shell, () => string>> = {\n bash: () => `# cosyte bash completion: source <(cosyte completion bash)\n_cosyte() {\n local cur prev cmds flags\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n cmds=\"${COMMANDS.join(\" \")}\"\n flags=\"${FLAGS.join(\" \")}\"\n if [ \"\\${COMP_CWORD}\" -eq 1 ]; then\n COMPREPLY=( $(compgen -W \"\\${cmds}\" -- \"\\${cur}\") )\n else\n COMPREPLY=( $(compgen -W \"\\${flags}\" -f -- \"\\${cur}\") )\n fi\n}\ncomplete -F _cosyte cosyte\n`,\n zsh: () => `#compdef cosyte\n# cosyte zsh completion: source <(cosyte completion zsh)\n_cosyte() {\n local -a cmds flags\n cmds=(${COMMANDS.map((c) => `'${c}'`).join(\" \")})\n flags=(${FLAGS.map((f) => `'${f}'`).join(\" \")})\n if (( CURRENT == 2 )); then\n _describe 'command' cmds\n else\n _describe 'flag' flags\n _files\n fi\n}\ncompdef _cosyte cosyte\n`,\n fish: () => {\n const lines = COMMANDS.map(\n (c) => `complete -c cosyte -n '__fish_use_subcommand' -a '${c}' -d 'cosyte ${c}'`,\n );\n const flagLines = FLAGS.filter((f) => f.startsWith(\"--\")).map(\n (f) => `complete -c cosyte -l '${f.slice(2)}'`,\n );\n return `# cosyte fish completion: cosyte completion fish | source\n${lines.join(\"\\n\")}\n${flagLines.join(\"\\n\")}\n`;\n },\n};\n","/**\n * `cosyte convert <file|-> --to fhir [--json] [--quiet] [--no-color]`\n *\n * Convert an **HL7 v2** message to **FHIR R4** via **`@cosyte/transform`**: the\n * consumer-of-consumers command. The CLI adds **no** mapping logic of its own: it parses the input\n * with `@cosyte/hl7`, hands the parsed message to `transform`'s `toFhir`, and serializes the resulting\n * FHIR `Bundle` with `@cosyte/fhir`. The mapping guarantees are the library's, graded by *its* gate;\n * `cosyte convert` equals `transform`'s programmatic output.\n *\n * The converted FHIR `Bundle` is the user's explicit request, so it goes to **stdout** (the data\n * channel). Every conversion problem is one of `transform`'s value-free {@link TransformIssue}s: a\n * stable code, a severity, and a positional locator (a v2 index and an optional FHIRPath), **never** a\n * field value: surfaced on stderr (or as value-free JSON under `--json`). The load-bearing rule\n * (mirroring `validate`): a conversion that produces an **error-severity** issue exits **`1`**, never\n * `0`: the tool worked, but the conversion has a real problem a CI gate must see.\n *\n * `--to fhir` is required and is the only supported target (HL7 v2 → FHIR R4). The source must be\n * HL7 v2: a recognised-but-non-HL7 input (e.g. a FHIR document) is a value-free\n * `CLI_FORMAT_UNSUPPORTED` data error (`65`), never a fake conversion.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { Finding } from \"../core/findings.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { loadFhir, loadOptionalPackage } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `convert` understands. */\nconst CONVERT_OPTIONS = {\n to: { type: \"string\" },\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** The only conversion target this build supports (HL7 v2 → FHIR R4). */\nconst SUPPORTED_TARGET = \"fhir\";\n\n/** Transform severities that make a conversion a **failure** (exit `1`). `transform` has no `fatal`. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/** The value-free result of a conversion: the serialized FHIR bundle text + the library's findings. */\ninterface Conversion {\n readonly bundleText: string;\n readonly findings: readonly Finding[];\n}\n\n/**\n * Run the `convert` command.\n *\n * @param args - The arguments after the `convert` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on an HL7\n * parse-failure diagnostic; the converted bundle and the value-free findings are unaffected).\n * @returns A {@link RunResult}: the converted FHIR `Bundle` on `stdout` (the data channel), value-free\n * findings on `stderr` (or JSON under `--json`), and an exit code that carries the outcome: `0`\n * clean · `1` an error-severity conversion issue · `65` the HL7 input could not be parsed or is not\n * an HL7 v2 source · `66` no input · `2` usage.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { convertCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode(\"MSH|^~\\\\&|A|B|C|D|20240101||ADT^A01|1|P|2.5\\r\"),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await convertCommand([\"adt.hl7\", \"--to\", \"fhir\"], deps)).exit; // => 0\n * ```\n */\nexport async function convertCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n to?: string;\n format?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: CONVERT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `convert` (see `cosyte convert --help`)\",\n ),\n );\n }\n\n // `--to` is required and names the conversion target. Only `fhir` is supported today; requiring it\n // (rather than defaulting) keeps the surface explicit and future-proof for other targets.\n if (values.to === undefined) {\n return errorResult(\n new CliError(CLI_CODES.CLI_USAGE, EXIT.USAGE, \"convert requires --to fhir (the only target)\"),\n );\n }\n if (values.to !== SUPPORTED_TARGET) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unsupported --to '${values.to}'; only --to fhir is supported (HL7 v2 → FHIR R4)`,\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n // convert reads HL7 v2 and writes FHIR R4. A recognised-but-non-HL7 source (e.g. a FHIR document) is\n // not a convertible input: a value-free data error, never a fake or identity \"conversion\".\n if (format !== \"hl7\") {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `convert reads HL7 v2 and writes FHIR R4; the input is '${format}', not an HL7 v2 source`,\n ),\n );\n }\n\n const outcome = await runConvert(bytes, posture);\n if (!outcome.ok) return outcome.result;\n const conversion = outcome.conversion;\n\n const { hasError, report } = convertOutcome(conversion.findings);\n const exit = hasError ? EXIT.INVALID : EXIT.OK;\n\n if (values.json === true) {\n // Machine output on the data channel: the converted bundle plus the value-free findings.\n const body = {\n format: SUPPORTED_TARGET,\n bundle: JSON.parse(conversion.bundleText) as unknown,\n findings: conversion.findings,\n };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n // Default: the converted FHIR Bundle (the library's canonical serialization) IS the stdout data\n // channel; the value-free findings + a summary go to stderr unless suppressed by --quiet.\n const stderr = values.quiet === true ? \"\" : report;\n return { stdout: `${conversion.bundleText}\\n`, stderr, exit };\n}\n\n/** Either a completed conversion, or a ready value-free parse-failure {@link RunResult}. */\ntype ConvertOutcome =\n | { readonly ok: true; readonly conversion: Conversion }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Why `@cosyte/transform` is absent, in words a user can act on. **It deliberately does not say\n * \"install it\"**: `npm install @cosyte/transform` fails too (`E404` on its own `@cosyte/fhir` peer),\n * so telling someone to install it would send them at a command that cannot succeed. That is the same\n * defect the `@cosyte/fhir` diagnostic exists to avoid, and it is why neither goes through\n * `loadOptional()`, whose stock wording is exactly \"install it (it is an optional dependency)\".\n * Value-free by construction: package names and a statement of fact, no input echoed.\n */\nconst TRANSFORM_UNAVAILABLE =\n \"the @cosyte/transform conversion library is not installed, so convert is unavailable; it \" +\n \"requires @cosyte/fhir, which is not currently on the npm registry, so npm skips transform as \" +\n \"an unresolvable optional dependency and installing it directly fails for the same reason\";\n\n/**\n * Parse the HL7 v2 bytes and convert to FHIR: every library **lazy-loaded** so this code loads only\n * when `convert` runs. Only the `parseHL7` call is inside the failure boundary: a genuine parser\n * rejection becomes a value-free `CLI_PARSE_FAILED` (65), with the single opt-in excerpt (under\n * `--unsafe-show-values`) flowing through the shared core/wrap chokepoint. The `toFhir` + serialize\n * step is deliberately outside it: `toFhir` never throws for a well-formed message, so any throw there\n * is an unexpected bug the dispatcher maps to `CLI_INTERNAL` (70), never mislabelled as a rejection.\n *\n * Two of the three libraries are **not guaranteed present in an installed copy**, so both loads go\n * through the optional-package boundary and an absent one becomes a value-free\n * `CLI_PARSER_UNAVAILABLE` (69) rather than an unhandled resolver error. `@cosyte/hl7` is a hard\n * dependency and needs no such treatment.\n */\nasync function runConvert(bytes: Uint8Array, posture: PhiPosture): Promise<ConvertOutcome> {\n const [{ parseHL7 }, { toFhir }, { serializeResource }] = await Promise.all([\n import(\"@cosyte/hl7\"),\n loadOptionalPackage(TRANSFORM_UNAVAILABLE, () => import(\"@cosyte/transform\")),\n loadFhir(),\n ]);\n\n let msg: ReturnType<typeof parseHL7>;\n try {\n msg = parseHL7(Buffer.from(bytes));\n } catch (e) {\n return { ok: false, result: parseFailureResult(\"hl7\", bytes, posture, e) };\n }\n\n const { bundle, issues } = toFhir(msg);\n return {\n ok: true,\n conversion: {\n bundleText: serializeResource(bundle),\n findings: issues.map((i) => toFinding(i.code, i.severity, i.v2Location, i.fhirPath)),\n },\n };\n}\n\n/** Build one value-free {@link Finding} from a transform issue: v2 locator, and the FHIRPath if any. */\nfunction toFinding(code: string, severity: string, v2Location: string, fhirPath?: string): Finding {\n const location = fhirPath !== undefined ? `${v2Location} → ${fhirPath}` : v2Location;\n return { code, severity, location };\n}\n\n/**\n * Decide the conversion outcome from the library's value-free findings: whether any is\n * **error-severity** (which drives a non-zero exit: the load-bearing \"a conversion error is never\n * exit 0\" rule) and the value-free human report. The severity classification is\n * the library's: `@cosyte/transform` fixes each issue's severity; the CLI only reads it. Exported so\n * the exit-verdict and report logic is unit-testable with synthetic findings, independent of which HL7\n * message happens to produce an error.\n *\n * @param findings - The value-free {@link Finding}s the conversion produced.\n * @returns `hasError` (true iff any finding is error/fatal severity) and the rendered value-free\n * `report` (one line per finding + a summary line).\n * @example\n * ```ts\n * import { convertOutcome } from \"@cosyte/cli\";\n *\n * convertOutcome([{ code: \"TRANSFORM_RESOURCE_INVALID\", severity: \"error\", location: \"PID\" }])\n * .hasError; // => true\n * convertOutcome([{ code: \"TRANSFORM_ELEMENT_DROPPED\", severity: \"information\", location: \"PID.13\" }])\n * .hasError; // => false\n * ```\n */\nexport function convertOutcome(findings: readonly Finding[]): {\n readonly hasError: boolean;\n readonly report: string;\n} {\n const lines = findings.map((f) => `cosyte: convert: ${f.severity} ${f.code} at ${f.location}\\n`);\n const errors = findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = findings.length - errors;\n const summary =\n errors > 0\n ? `cosyte: convert: hl7 → fhir produced ${String(errors)} error(s), ${String(others)} other finding(s)\\n`\n : `cosyte: convert: hl7 → fhir OK (${String(findings.length)} finding(s))\\n`;\n return { hasError: errors > 0, report: lines.join(\"\") + summary };\n}\n","/**\n * `cosyte fmt <file|-> [--format …] [--quiet] [--no-color]`\n *\n * **Canonical re-serialization.** Parse the input and emit it back through the wrapped library's\n * **conservative, spec-clean serializer**: HL7 via `Hl7Message.toString()` (CR-separated, spec-clean\n * HL7), FHIR via `serializeResource` (canonical JSON, decimals byte-exact). The CLI **never\n * re-canonicalizes on its own**: the output is exactly the wrapped serializer's, so\n * `fmt` round-trips a spec-clean input through the parser.\n *\n * `fmt`'s stdout **is** the data channel: a re-serialization of the message, values included, going to\n * the sink the user chose. Every *secondary* surface stays value-free: a warning-count note on stderr\n * (suppressible with `--quiet`), and an unparseable input is a data error (`65`) with **no partial\n * emit**, never a half-serialized message.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { fmtFormat, type FmtResult } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `fmt` understands. `fmt`'s output shape is the library serializer's, so there is no `--json`. */\nconst FMT_OPTIONS = {\n format: { type: \"string\" },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `fmt` command.\n *\n * @param args - The arguments after the `fmt` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic).\n * @returns A {@link RunResult}: the canonical re-serialization on `stdout` (exit `0`), a value-free\n * warning-count note on `stderr` unless `--quiet`; an unparseable input is a data error (`65`) with\n * no partial emit, an unreadable file `66`, a bad flag `2`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { fmtCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{ \"resourceType\":\"Patient\" , \"id\":\"x\" }'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await fmtCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function fmtCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: { format?: string; quiet?: boolean; \"no-color\"?: boolean };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: FMT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `fmt` (see `cosyte fmt --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"fmt\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let result: FmtResult;\n try {\n result = await fmtFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n // No partial emit: an unparseable input yields a value-free data error, never half a message.\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const stderr =\n result.warningCount > 0 && values.quiet !== true\n ? `cosyte: fmt: re-serialized ${format} with ${String(result.warningCount)} parse warning(s)\\n`\n : \"\";\n return { stdout: `${result.output}\\n`, stderr, exit: EXIT.OK };\n}\n","/**\n * `cosyte inspect <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * A human-readable, **value-free-by-default** structural summary of a message: its type, structural\n * counts, and a warning count: the \"what shape is this?\" answer, without ever printing a field\n * value. Unlike `parse`, whose stdout is the parsed model (the data channel), `inspect`'s\n * stdout is a *structural* summary composed only of counts and structural type **codes** (an HL7 message\n * type like `ADT^A01`, a FHIR `resourceType` like `Patient`, an X12 transaction-set id like `834`, a\n * DICOM SOP Class UID, an NCPDP `NewRx`): classification, never PHI. `--json` emits the same value-free\n * summary as machine JSON. The per-format summaries are built by the shared registry (`core/parsers.ts`).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { inspectFormat, type InspectSummary } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `inspect` understands. */\nconst INSPECT_OPTIONS = {\n format: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `inspect` command.\n *\n * @param args - The arguments after the `inspect` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; the summary itself is always value-free).\n * @returns A {@link RunResult}: the value-free structural summary on `stdout` (human, or JSON under\n * `--json`), exit `0`; a parse failure is a data error (`65`), an unreadable file `66`, a bad flag `2`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { inspectCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await inspectCommand([\"patient.json\", \"--json\"], deps)).exit; // => 0\n * ```\n */\nexport async function inspectCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: { format?: string; json?: boolean; quiet?: boolean; \"no-color\"?: boolean };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: INSPECT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `inspect` (see `cosyte inspect --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"inspect\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let summary: InspectSummary;\n try {\n summary = await inspectFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const stdout = values.json === true ? `${JSON.stringify(summary)}\\n` : renderSummary(summary);\n return { stdout, stderr: \"\", exit: EXIT.OK };\n}\n\n/**\n * Render a value-free human structural summary. Only counts and structural type codes, never a value.\n * Exported for direct branch testing of the per-format render (not re-exported from the package root).\n *\n * @param summary - The value-free {@link InspectSummary} to render.\n * @returns The human-readable, value-free summary text.\n * @example\n * ```ts\n * import { renderSummary } from \"@cosyte/cli/dist/commands/inspect.js\";\n *\n * renderSummary({ format: \"mllp\", frameCount: 2, warningCount: 0 }).includes(\"frames\"); // => true\n * ```\n */\nexport function renderSummary(summary: InspectSummary): string {\n const lines: string[] = [];\n const countLines = (label: string, counts: Readonly<Record<string, number>>): void => {\n if (label.length > 0) lines.push(label);\n for (const key of Object.keys(counts).sort()) lines.push(` ${key}: ${String(counts[key])}`);\n };\n\n switch (summary.format) {\n case \"hl7\":\n lines.push(`format: hl7`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n countLines(\"\", summary.segments);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"fhir\":\n lines.push(`format: fhir`);\n lines.push(`resource type: ${summary.resourceType ?? \"(unknown)\"}`);\n if (summary.entryCount !== undefined) {\n lines.push(`bundle type: ${summary.bundleType ?? \"(unknown)\"}`);\n lines.push(`entries: ${String(summary.entryCount)}`);\n countLines(\"\", summary.entryResourceTypes ?? {});\n }\n lines.push(`issues: ${String(summary.issueCount)}`);\n break;\n case \"x12\":\n lines.push(`format: x12`);\n lines.push(`groups: ${String(summary.groupCount)}`);\n lines.push(`transactions: ${String(summary.transactionCount)}`);\n countLines(\"transaction sets:\", summary.transactionSetIds);\n lines.push(`segments: ${String(summary.segmentCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"astm\":\n lines.push(`format: astm`);\n lines.push(`message kind: ${summary.messageKind}`);\n lines.push(`records: ${String(summary.recordCount)}`);\n countLines(\"\", summary.recordTypes);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ccda\":\n lines.push(`format: ccda`);\n lines.push(`document type: ${summary.documentType ?? \"(unknown)\"}`);\n lines.push(`sections: ${String(summary.sectionCount)}`);\n if (summary.sectionCodes.length > 0) {\n lines.push(`section codes: ${summary.sectionCodes.join(\", \")}`);\n }\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"dicom\":\n lines.push(`format: dicom`);\n lines.push(`sop class uid: ${summary.sopClassUid ?? \"(unknown)\"}`);\n lines.push(`transfer syntax:${summary.transferSyntaxUid ?? \" (unknown)\"}`);\n lines.push(`elements: ${String(summary.elementCount)}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"ncpdp\":\n lines.push(`format: ncpdp`);\n lines.push(`standard: SCRIPT`);\n lines.push(`message type: ${summary.messageType ?? \"(unknown)\"}`);\n lines.push(`version: ${summary.version ?? \"(unknown)\"}`);\n lines.push(`warnings: ${String(summary.warningCount)}`);\n break;\n case \"mllp\":\n lines.push(`format: mllp`);\n lines.push(`frames: ${String(summary.frameCount)}`);\n lines.push(`warnings:${String(summary.warningCount)}`);\n break;\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n","/**\n * `cosyte map-codes <conceptmap|-> --code <code> [--system <uri>] [--version <v>] [--display <d>]\n * [--json] [--quiet]`\n *\n * Translate a single source coding through a **BYO FHIR R4 ConceptMap** via\n * **`@cosyte/terminology`**. The positional argument is the ConceptMap document (a file, or `-` for\n * stdin); `--system` + `--code` (and optional `--version`/`--display`) name the source coding to\n * translate. The CLI adds **no** mapping content of its own: `terminology` is content-free and\n * never fabricates a target; the CLI loads the user's map and forwards the translation faithfully.\n *\n * A ConceptMap and a terminology code are **reference data, not PHI**, so the translation result\n * (the matched target coding(s), or the value-free \"unmapped\" signal) is the user's explicit request\n * and goes to **stdout**. The exit code carries the outcome so it is usable as a gate: **`0`** at\n * least one match · **`1`** no mapping found (the never-fabricate `TERM_TRANSLATE_UNMAPPED` outcome) ·\n * `65` the supplied ConceptMap is not valid JSON / not a loadable ConceptMap · `66` no input · `2`\n * usage. stderr stays value-free (stable codes and counts only).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport type { Coding, TranslateResult } from \"@cosyte/terminology\";\n\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { extractStableCode } from \"../core/wrap.js\";\n\n/** The flags `map-codes` understands. */\nconst MAP_CODES_OPTIONS = {\n code: { type: \"string\" },\n system: { type: \"string\" },\n version: { type: \"string\" },\n display: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `map-codes` command.\n *\n * @param args - The arguments after the `map-codes` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}); the positional argument (or `-`) is the BYO\n * ConceptMap document.\n * @returns A {@link RunResult}: the translation result on `stdout` (matched target coding(s) or the\n * value-free unmapped signal), a value-free note on `stderr` (unless `--quiet`), and an exit code\n * carrying the outcome: `0` mapped · `1` unmapped · `65` unloadable ConceptMap · `66` no input ·\n * `2` usage.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map to\n * `CLI_INTERNAL`.\n * @example\n * ```ts\n * import { mapCodesCommand } from \"@cosyte/cli\";\n *\n * const cm = JSON.stringify({\n * resourceType: \"ConceptMap\",\n * group: [\n * {\n * source: \"http://hl7.org/fhir/administrative-gender\",\n * target: \"http://terminology.hl7.org/CodeSystem/v2-0001\",\n * element: [{ code: \"male\", target: [{ code: \"M\", equivalence: \"equivalent\" }] }],\n * },\n * ],\n * });\n * const deps = {\n * readFile: async () => new TextEncoder().encode(cm),\n * readStdin: async () => new Uint8Array(),\n * };\n * const r = await mapCodesCommand(\n * [\"gender.json\", \"--system\", \"http://hl7.org/fhir/administrative-gender\", \"--code\", \"male\"],\n * deps,\n * );\n * r.exit; // => 0\n * ```\n */\nexport async function mapCodesCommand(args: string[], deps: RunDeps): Promise<RunResult> {\n let values: {\n code?: string;\n system?: string;\n version?: string;\n display?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: MAP_CODES_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `map-codes` (see `cosyte map-codes --help`)\",\n ),\n );\n }\n\n const source = positionals[0];\n if (source === undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"missing <conceptmap> argument; pass a FHIR ConceptMap path or `-` to read stdin\",\n ),\n );\n }\n if (values.code === undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"map-codes requires --code (the source code to translate)\",\n ),\n );\n }\n\n // Read the ConceptMap bytes (a missing/unreadable file is a value-free no-input error, 66).\n let bytes: Uint8Array;\n try {\n bytes = source === \"-\" ? await deps.readStdin() : await deps.readFile(source);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n throw e;\n }\n if (bytes.length === 0) {\n return errorResult(new CliError(CLI_CODES.CLI_EMPTY_INPUT, EXIT.DATAERR, \"input is empty\"));\n }\n\n const coding: Coding = {\n code: values.code,\n ...(values.system !== undefined ? { system: values.system } : {}),\n ...(values.version !== undefined ? { version: values.version } : {}),\n ...(values.display !== undefined ? { display: values.display } : {}),\n };\n\n const outcome = await translateVia(bytes, coding);\n if (!outcome.ok) return outcome.result;\n const { result } = outcome;\n\n const exit = result.unmapped ? EXIT.INVALID : EXIT.OK;\n const body = { source: coding, result };\n\n if (values.json === true) {\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n const stderr = values.quiet === true ? \"\" : renderNote(result);\n return { stdout: `${JSON.stringify(body, null, 2)}\\n`, stderr, exit };\n}\n\n/** The result of loading + translating: either the translate result, or a ready value-free error. */\ntype TranslateOutcome =\n | { readonly ok: true; readonly result: TranslateResult }\n | { readonly ok: false; readonly result: RunResult };\n\n/**\n * Load the BYO ConceptMap (lazy-loading `@cosyte/terminology`) and translate the source coding.\n * Malformed JSON and an unloadable ConceptMap both resolve to a value-free `CLI_MAP_INVALID` data\n * error: the map's bytes are never echoed, only the stable terminology-loader code (when the thrown\n * value carried one, e.g. `TERM_CONCEPTMAP_MALFORMED`).\n */\nasync function translateVia(bytes: Uint8Array, coding: Coding): Promise<TranslateOutcome> {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return mapInvalid(\"the ConceptMap input is not valid JSON\");\n }\n\n const { loadConceptMap, translate } = await import(\"@cosyte/terminology\");\n let map: ReturnType<typeof loadConceptMap>;\n try {\n map = loadConceptMap(json);\n } catch (e) {\n const code = extractStableCode(e);\n const detail = code === null ? \"\" : ` (${code})`;\n return mapInvalid(`the supplied ConceptMap could not be loaded${detail}`);\n }\n return { ok: true, result: translate(coding, map) };\n}\n\n/** Build a value-free `CLI_MAP_INVALID` (exit `65`) failure outcome. */\nfunction mapInvalid(message: string): TranslateOutcome {\n return {\n ok: false,\n result: errorResult(new CliError(CLI_CODES.CLI_MAP_INVALID, EXIT.DATAERR, message)),\n };\n}\n\n/** Render the value-free stderr note: a mapped count, or the stable unmapped code + fallback mode. */\nfunction renderNote(result: TranslateResult): string {\n if (result.unmapped) {\n return `cosyte: map-codes: ${result.code} (fallback mode: ${result.mode})\\n`;\n }\n return `cosyte: map-codes: ${String(result.matches.length)} match(es)\\n`;\n}\n","/**\n * `cosyte parse <file|-> [--format …] [--ndjson] [--json] [--quiet] [--no-color]`\n *\n * Read a file (or stdin via `-`), **autodetect the format by content** (or honour `--format`), route to\n * the wrapped parser via the lazy per-format registry (`core/parsers.ts`) (so `cosyte parse msg.hl7`\n * never loads the DICOM or X12 code) and emit the parsed model as **typed JSON on stdout**. Every\n * failure is a value-free diagnostic on stderr with a stable `CLI_*` code and the documented exit code.\n *\n * **Multi-message / streaming.** A single message emits one pretty (or compact under `--json`)\n * JSON envelope, exactly as before. A **multi-record** input emits **NDJSON** (one compact envelope\n * per line) with per-record isolation: a record that fails to parse becomes a value-free\n * `{ record, error }` line and the stream continues, and the overall exit is a data error (`65`) if any\n * record failed. Two inputs are multi-record: an **MLLP** stream (each VT-framed frame is an enclosed\n * HL7 message) and any input under **`--ndjson`** (each non-empty line is a record: the FHIR bulk-data\n * convention). Multi-record output is emitted **record by record, as each is parsed**, so the first\n * line reaches the data channel long before the last byte of input has been read.\n *\n * **The size limit.** One invocation reads at most the documented number of input bytes (see\n * `core/limits.ts`), counted against the running total as the input arrives. A larger input is a\n * value-free `CLI_INPUT_TOO_LARGE` **data error**, never the internal-error code, and never a partial\n * record stream presented as a complete one: whatever reached stdout before the refusal stands, and\n * the invocation still resolves to the failure's own non-zero exit code.\n *\n * The CLI adds **no** parsing of its own: it routes, reads, and shapes output; `cosyte parse` equals the\n * wrapped library's programmatic parse.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport { CLI_CODES, CliError, errorResult, formatDiagnostic } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { resolveInputStream } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { parseFormat, type ParseWarning } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport { collectChunks, mllpFrames, ndjsonRecords, type ByteChunks } from \"../core/records.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { extractStableCode, parseFailureResult } from \"../core/wrap.js\";\n\n// Re-exported from the shared wrapper boundary so the historical `@cosyte/cli` import path stays stable.\nexport { extractStableCode } from \"../core/wrap.js\";\n\n/** The typed JSON envelope a single `parse` emits on stdout: the format, the parsed model, warnings. */\ninterface ParseEnvelope {\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n}\n\n/** One line of NDJSON multi-record output: a parsed record, or a value-free per-record parse error. */\ntype RecordLine =\n | {\n readonly record: number;\n readonly format: CosyteFormat;\n readonly model: unknown;\n readonly warnings: readonly ParseWarning[];\n }\n | { readonly record: number; readonly format: CosyteFormat; readonly error: string };\n\n/** The flags `parse` understands, parsed by {@link parseArgs}. */\nconst PARSE_OPTIONS = {\n format: { type: \"string\" },\n ndjson: { type: \"boolean\", default: false },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/**\n * Run the `parse` command.\n *\n * @param args - The arguments after the `parse` subcommand token.\n * @param deps - Injected I/O ({@link RunDeps}). When it carries the chunk readers and the output\n * sink, a multi-record input is read and emitted incrementally; when it does not, the same path\n * runs over one chunk and the output comes back on `stdout` instead.\n * @param posture - The resolved {@link PhiPosture}. Defaults to {@link VALUE_FREE}; under\n * `--unsafe-show-values` a bounded excerpt of the offending input is appended to a `CLI_PARSE_FAILED`\n * diagnostic (the single, opt-in value-echoing surface): single-record mode only.\n * @returns A {@link RunResult}: the typed-JSON model (or NDJSON records) on `stdout`, a value-free note\n * (or nothing) on `stderr`, and the resolved exit code. An input past the documented size limit is a\n * value-free data error naming the limit. Never throws a {@link CliError}: it resolves it to a\n * result; unexpected exceptions are caught by the dispatcher and mapped to `CLI_INTERNAL`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { parseCommand } from \"@cosyte/cli\";\n *\n * const enc = new TextEncoder();\n * const deps = {\n * readFile: async () => enc.encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await parseCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function parseCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n ndjson?: boolean;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: PARSE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `parse` (see `cosyte parse --help`)\",\n ),\n );\n }\n\n const resolved = await resolveInputStream(positionals[0], values.format, deps, \"parse\");\n if (!resolved.ok) return resolved.result;\n const { format, chunks } = resolved.input;\n\n // MLLP is a transport container and `--ndjson` is explicit batch mode: both are multi-record.\n if (format === \"mllp\" || values.ndjson === true) {\n return await parseMulti(\n format,\n chunks,\n values.ndjson === true,\n values.quiet === true,\n deps.writeStdout,\n );\n }\n\n // A single message is parsed whole, so the rest of the input is drained here (still size-limited).\n let bytes: Uint8Array;\n try {\n bytes = await collectChunks(chunks);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n throw e;\n }\n return await parseSingle(format, bytes, values.json === true, values.quiet === true, posture);\n}\n\n/** Parse a single message → one JSON envelope (pretty, or compact under `--json`). Preserves the\n * value-free failure boundary and the opt-in `--unsafe-show-values` excerpt. */\nasync function parseSingle(\n format: CosyteFormat,\n bytes: Uint8Array,\n json: boolean,\n quiet: boolean,\n posture: PhiPosture,\n): Promise<RunResult> {\n let result: { model: unknown; warnings: readonly ParseWarning[] };\n try {\n result = await parseFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n return parseFailureResult(format, bytes, posture, e);\n }\n const envelope: ParseEnvelope = { format, model: result.model, warnings: result.warnings };\n const stdout = (json ? JSON.stringify(envelope) : JSON.stringify(envelope, null, 2)) + \"\\n\";\n\n const n = envelope.warnings.length;\n const stderr =\n n > 0 && !quiet\n ? `cosyte: parsed ${format} with ${String(n)} warning(s) (see .warnings in output)\\n`\n : \"\";\n return { stdout, stderr, exit: EXIT.OK };\n}\n\n/**\n * Parse a multi-record input (MLLP frames, or `--ndjson` lines) → NDJSON, with per-record isolation\n * and **per-record emission**: each line reaches the data channel as soon as its record is parsed,\n * while the rest of the input is still arriving.\n *\n * Failure isolation is unchanged by that move: a record the parser rejects becomes a value-free\n * `{ record, error }` line, the stream continues, and any failed record resolves the invocation to\n * the data-error exit. A **fatal** condition (the over-limit refusal, a truncated MLLP stream, a\n * parser that is not installed, a downstream consumer closing the pipe) ends the stream and resolves\n * to that failure's own non-zero code, **keeping** whatever already reached stdout: a partial record\n * stream is never dressed up as a complete one, and never reported as a success.\n */\nasync function parseMulti(\n format: CosyteFormat,\n chunks: ByteChunks,\n ndjson: boolean,\n quiet: boolean,\n writeStdout: ((chunk: string) => void) | undefined,\n): Promise<RunResult> {\n // MLLP de-frames to enclosed HL7 payloads; every other multi-record input is one record per line.\n const recordFormat: CosyteFormat = format === \"mllp\" ? \"hl7\" : format;\n const records = format === \"mllp\" ? mllpFrames(chunks) : ndjsonRecords(chunks);\n\n const held: string[] = [];\n const emit = (line: string): void => {\n if (writeStdout === undefined) {\n held.push(line);\n return;\n }\n try {\n writeStdout(line);\n } catch {\n // The consumer went away part way through the stream (a closed pipe). Value-free, and never\n // an unhandled platform error reaching the terminal.\n throw new CliError(\n CLI_CODES.CLI_OUTPUT_WRITE_FAILED,\n EXIT.IOERR,\n \"could not write to the output stream; it closed before the record stream finished\",\n );\n }\n };\n const written = (): string => held.join(\"\");\n\n let total = 0;\n let failed = 0;\n let warnings = 0;\n\n try {\n for await (const record of records) {\n let line: RecordLine;\n try {\n const { model, warnings: ws } = await parseFormat(recordFormat, record);\n warnings += ws.length;\n line = { record: total, format: recordFormat, model, warnings: ws };\n } catch (e) {\n if (e instanceof CliError) throw e; // a parser-unavailable is fatal for the whole stream\n failed += 1;\n // Value-free per-record error: a stable code (if the throw carried one), never the bytes.\n line = {\n record: total,\n format: recordFormat,\n error: extractStableCode(e) ?? \"CLI_PARSE_FAILED\",\n };\n }\n total += 1;\n emit(JSON.stringify(line) + \"\\n\");\n }\n } catch (e) {\n // Fatal, part way through: the exit code is the failure's own, and the lines already emitted stay.\n if (e instanceof CliError) {\n return { stdout: written(), stderr: `${formatDiagnostic(e)}\\n`, exit: e.exit };\n }\n const rejected = parseFailureResult(format, new Uint8Array(), VALUE_FREE, e);\n return { stdout: written(), stderr: rejected.stderr, exit: rejected.exit };\n }\n\n if (total === 0) {\n // A framed/ndjson input that yielded no record is a data error, never a silent success.\n return errorResult(\n new CliError(\n CLI_CODES.CLI_PARSE_FAILED,\n EXIT.DATAERR,\n `no ${format === \"mllp\" ? \"MLLP frame\" : \"record\"} found in the input`,\n ),\n );\n }\n\n const exit = failed > 0 ? EXIT.DATAERR : EXIT.OK;\n const stderr = quiet\n ? \"\"\n : `cosyte: parsed ${String(total)} ${recordFormat} record(s)` +\n ` (${String(warnings)} warning(s), ${String(failed)} failed)` +\n (ndjson ? \" [ndjson]\" : format === \"mllp\" ? \" [mllp]\" : \"\") +\n \"\\n\";\n return { stdout: written(), stderr, exit };\n}\n","/**\n * `cosyte redact <file|-> [--format …]` (alias `cosyte deid …`): the command whose *job* is to strip\n * identifiers, emitting a de-identified copy of the message on the data channel.\n *\n * **It delegates; it never approximates.** The whole policy belongs to **`@cosyte/deid`** (the seam in\n * `core/deid.ts`): the CLI adds no locus map, no transform and no fallback scrub, because a partial\n * pass over only the obvious PHI loci would leave PHI behind and present a **false-safety\n * impression**, the cardinal hazard this command exists to avoid. So anything short of a clean,\n * fully-handled pass is a non-zero exit with **empty stdout**:\n *\n * - the delegate ships no adapter for the resolved format: `CLI_NOT_IMPLEMENTED`, exit `69`;\n * - the delegate covers it but the CLI cannot carry the result on a text stdout (DICOM's Part 10\n * bytes): `CLI_FORMAT_UNSUPPORTED`, exit `65`, the CLI's own limit rather than the delegate's;\n * - the delegate reports it could not handle an element: `CLI_DEID_INCOMPLETE`, exit `1`;\n * - the library is absent from the install: `CLI_PARSER_UNAVAILABLE`, exit `69`, decided **before any\n * input is read**.\n *\n * The diagnostic channel carries the delegate's own value-free manifest (category, transform, the\n * structural locus, count, disposition code) and the delegate's own published label and version. The\n * CLI claims no de-identification standard of its own, and never echoes an input value here: not even\n * under `--unsafe-show-values`, whose bounded excerpt is deliberately not honoured by *this* command,\n * because an excerpt of the un-stripped input is exactly what `redact` exists to prevent.\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport {\n DEID_BLOCKED,\n DEID_PACKAGE,\n deidCoverage,\n isDeidCovered,\n loadDeidDelegate,\n type DeidDelegate,\n type DeidManifestRecord,\n type RedactOutcome,\n} from \"../core/deid.js\";\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport type { RunResult } from \"../core/result.js\";\n\n/** The flags `redact`/`deid` honours: the positional `<file|->` plus the shared `--format` override. */\nconst REDACT_OPTIONS = {\n format: { type: \"string\" },\n} as const;\n\n/**\n * Render one manifest entry as a value-free stderr line. Every field is the delegate's own: the\n * `locus` is a structural path by its contract, never an input value.\n */\nfunction manifestLine(entry: DeidManifestRecord): string {\n return (\n `cosyte: redact: ${entry.category} ${entry.transform} ${entry.locus} ` +\n `x${String(entry.count)} ${entry.disposition} ${entry.code}\\n`\n );\n}\n\n/** The delegate's attribution: its own package, version and published label, quoted, nothing added. */\nfunction attribution(delegate: DeidDelegate): string {\n return `cosyte: redact: delegated to ${DEID_PACKAGE} ${delegate.version}: ${delegate.label}\\n`;\n}\n\n/** The whole manifest, one value-free line per entry, in the delegate's own locus order. */\nfunction manifestLines(outcome: RedactOutcome): string {\n return outcome.manifest.map(manifestLine).join(\"\");\n}\n\n/** Count the entries of one disposition. */\nfunction countOf(outcome: RedactOutcome, disposition: string): number {\n return outcome.manifest.filter((e) => e.disposition === disposition).length;\n}\n\n/** The value-free tally line: how many loci were acted on, and how. */\nfunction tally(format: CosyteFormat, outcome: RedactOutcome): string {\n const transformed = countOf(outcome, \"transformed\");\n const removed = countOf(outcome, \"removed\");\n const blocked = countOf(outcome, DEID_BLOCKED);\n return (\n `cosyte: redact: ${format}: ${String(outcome.manifest.length)} loci acted on ` +\n `(${String(transformed)} transformed, ${String(removed)} removed, ${String(blocked)} blocked)\\n`\n );\n}\n\n/**\n * The ephemeral-key disclosure. The delegate's default policy removes MRN / account / member\n * identifiers rather than replacing them with a keyed surrogate, but the CLI binds every run to a key\n * context so that any keyed transform the delegate applies is never unkeyed; it holds no key\n * material and offers no key surface, so it keys each invocation with a fresh random value. Stated\n * rather than left to be discovered, because \"the same identifier maps to the same surrogate\" is true\n * *within* one output and deliberately false *across* runs. The line stays even when the manifest\n * shows no keyed transform: it then overstates, which is the safe direction.\n */\nconst EPHEMERAL_KEY_NOTE =\n \"cosyte: redact: identifier surrogates are keyed with a per-invocation ephemeral key: \" +\n \"consistent within this output, not stable across runs\\n\";\n\n/**\n * Run the `redact` / `deid` command.\n *\n * @param args - The arguments after the `redact`/`deid` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param loadDelegate - The de-identification delegate loader; injectable so a test can drive the\n * library-absent path without uninstalling it.\n * @returns A {@link RunResult}. A clean pass over a covered format: the de-identified document on\n * `stdout`, the delegate's attribution and value-free manifest on `stderr`, exit `0`. Otherwise\n * empty `stdout` and a typed non-zero exit: `1` when the delegate could not handle an element, `69`\n * when it has no adapter for the format or is absent, `65` when the format cannot ride a text\n * stdout or the input did not parse, `66` for an unreadable file, `2` for a bad flag.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { redactCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\",\"id\":\"x\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await redactCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function redactCommand(\n args: string[],\n deps: RunDeps,\n loadDelegate: () => Promise<DeidDelegate> = loadDeidDelegate,\n): Promise<RunResult> {\n let values: { format?: string };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: REDACT_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `redact` (see `cosyte --help`)\",\n ),\n );\n }\n\n // The ground layer FIRST, before a byte is read: an install without the library must never touch\n // the input it cannot strip. An absent package is a value-free CLI_PARSER_UNAVAILABLE (69).\n let delegate: DeidDelegate;\n try {\n delegate = await loadDelegate();\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n throw e;\n }\n\n // No operation gate here: `redact`'s capability matrix is the delegate's, applied below, and it\n // answers an uncovered format with a different code than the parser registry would.\n const resolved = await resolveInput(positionals[0], values.format, deps, null);\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n if (!isDeidCovered(format)) return errorResult(uncovered(format));\n\n let outcome: RedactOutcome;\n try {\n outcome = await delegate.redact(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e);\n throw e;\n }\n\n const blocked = outcome.manifest.filter((e) => e.disposition === DEID_BLOCKED);\n if (blocked.length > 0) {\n // Fail closed. The loci and their codes are reported so the gap is visible, and nothing is\n // offered as a de-identified copy: no output at all.\n const incomplete = new CliError(\n CLI_CODES.CLI_DEID_INCOMPLETE,\n EXIT.INVALID,\n `${DEID_PACKAGE} blocked ${String(blocked.length)} of ` +\n `${String(outcome.manifest.length)} loci in this ${format} input; no output was emitted`,\n );\n return {\n stdout: \"\",\n stderr:\n attribution(delegate) +\n manifestLines(outcome) +\n tally(format, outcome) +\n `cosyte: ${incomplete.code}: ${incomplete.message}\\n`,\n exit: incomplete.exit,\n };\n }\n\n return {\n stdout: `${outcome.output}\\n`,\n stderr:\n attribution(delegate) + manifestLines(outcome) + tally(format, outcome) + EPHEMERAL_KEY_NOTE,\n exit: EXIT.OK,\n };\n}\n\n/**\n * The value-free refusal for a format `redact` produces no output for. Two distinct facts get two\n * distinct codes: the delegate having no adapter for the standard this CLI resolves is an\n * unavailable capability (`69`), while DICOM is covered by the delegate and refused by the **CLI**,\n * whose data channel is text and cannot carry a Part 10 byte stream (`65`, the same answer `parse`\n * and `fmt` already give for the same reason). Blaming the delegate for the CLI's own channel would\n * be a false attribution.\n */\nfunction uncovered(format: CosyteFormat): CliError {\n if (deidCoverage(format) === \"unserializable\") {\n return new CliError(\n CLI_CODES.CLI_FORMAT_UNSUPPORTED,\n EXIT.DATAERR,\n `format '${format}' cannot be redacted onto this CLI's text output channel ` +\n `(its de-identified form is a binary stream, so \\`parse\\` and \\`fmt\\` are unwired too)`,\n );\n }\n return new CliError(\n CLI_CODES.CLI_NOT_IMPLEMENTED,\n EXIT.UNAVAILABLE,\n `${DEID_PACKAGE} does not de-identify the ${format} standard this CLI resolves, and the CLI ` +\n `ships no redactor of its own, so nothing is emitted`,\n );\n}\n","/**\n * `cosyte validate <file|-> [--format …] [--json] [--quiet] [--no-color]`\n *\n * Parse the input, run the **wrapped parser's own validation/conformance surface**, and let the\n * **exit code carry the verdict** so `cosyte validate` is usable as a CI gate: **`0` valid, `1`\n * invalid** (parseable but non-conformant), `65` unparseable, `66` no input, `2` usage. The\n * load-bearing rule: the CLI never prints a reassuring line and exits `0` on an invalid message.\n *\n * Findings are **value-free**: a stable code, a severity, and a positional locator (a FHIRPath, or an\n * HL7 segment/field index), never a field value. By default they render on **stderr**; `--json`\n * emits the same value-free verdict + findings as machine JSON on stdout. The CLI invents **no**\n * verdict of its own: FHIR validity is `@cosyte/fhir`'s `validateResource().valid` (plus any\n * error-severity read issue); HL7 validity is \"parseable\": its parser is Postel's-Law lenient and its\n * warnings are, by the library's design, non-fatal deviations (surfaced, never failing).\n *\n * @packageDocumentation\n */\n\nimport { parseArgs } from \"node:util\";\n\nimport type { CosyteFormat } from \"../core/format.js\";\nimport { CLI_CODES, CliError, errorResult } from \"../core/diagnostics.js\";\nimport { EXIT } from \"../core/exit-codes.js\";\nimport { resolveInput } from \"../core/input.js\";\nimport type { RunDeps } from \"../core/io.js\";\nimport { validateFormat, type Verdict } from \"../core/parsers.js\";\nimport { VALUE_FREE, type PhiPosture } from \"../core/phi.js\";\nimport type { RunResult } from \"../core/result.js\";\nimport { parseFailureResult } from \"../core/wrap.js\";\n\n/** The flags `validate` understands. */\nconst VALIDATE_OPTIONS = {\n format: { type: \"string\" },\n profile: { type: \"string\" },\n json: { type: \"boolean\", default: false },\n quiet: { type: \"boolean\", default: false },\n \"no-color\": { type: \"boolean\", default: false },\n} as const;\n\n/** Severities that make a resource **invalid** (exit `1`). Warnings/information never fail a verdict. */\nconst ERROR_SEVERITIES: ReadonlySet<string> = new Set([\"error\", \"fatal\"]);\n\n/**\n * Run the `validate` command.\n *\n * @param args - The arguments after the `validate` subcommand token.\n * @param deps - Injected input readers ({@link RunDeps}).\n * @param posture - The resolved {@link PhiPosture} (governs only the opt-in unsafe excerpt on a\n * parse-failure diagnostic; a validation verdict is always value-free).\n * @returns A {@link RunResult} whose **exit code carries the verdict** (`0` valid / `1` invalid /\n * `65` unparseable / `66` no input / `2` usage). Value-free findings on `stderr`, or value-free\n * JSON on stdout under `--json`.\n * @throws Never {@link CliError}; may propagate a truly unexpected error for the dispatcher to map.\n * @example\n * ```ts\n * import { validateCommand } from \"@cosyte/cli\";\n *\n * const deps = {\n * readFile: async () => new TextEncoder().encode('{\"resourceType\":\"Patient\",\"gender\":\"male\"}'),\n * readStdin: async () => new Uint8Array(),\n * };\n * (await validateCommand([\"patient.json\"], deps)).exit; // => 0\n * ```\n */\nexport async function validateCommand(\n args: string[],\n deps: RunDeps,\n posture: PhiPosture = VALUE_FREE,\n): Promise<RunResult> {\n let values: {\n format?: string;\n profile?: string;\n json?: boolean;\n quiet?: boolean;\n \"no-color\"?: boolean;\n };\n let positionals: string[];\n try {\n const parsed = parseArgs({ args, options: VALIDATE_OPTIONS, allowPositionals: true });\n values = parsed.values;\n positionals = parsed.positionals;\n } catch {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n \"invalid arguments to `validate` (see `cosyte validate --help`)\",\n ),\n );\n }\n\n // Profile-based validation is a pass-through to the wrapped library's profile surface, but the CLI\n // bundles no profiles and cannot yet load one, so honouring `--profile` today would either fake a\n // verdict or silently ignore the flag (falsely implying a profile was applied). Both are forbidden\n // (ADR 0018): report a value-free \"unavailable\" and exit 69, without reading the input.\n if (values.profile !== undefined) {\n return errorResult(\n new CliError(\n CLI_CODES.CLI_NOT_IMPLEMENTED,\n EXIT.UNAVAILABLE,\n \"profile-based validation is not yet available: the CLI bundles no profiles and cannot yet \" +\n \"load one; validating against `--profile` is gated on that surface. Re-run without --profile \" +\n \"for base validation.\",\n ),\n );\n }\n\n const resolved = await resolveInput(positionals[0], values.format, deps, \"validate\");\n if (!resolved.ok) return resolved.result;\n const { format, bytes } = resolved.input;\n\n let verdict: Verdict;\n try {\n verdict = await validateFormat(format, bytes);\n } catch (e) {\n if (e instanceof CliError) return errorResult(e); // e.g. an absent optional parser (69)\n // Unparseable input is a data error (65), NOT an invalid verdict (1): the tool could not run the\n // check at all. Value-free; the opt-in excerpt flows through the single core/wrap chokepoint.\n return parseFailureResult(format, bytes, posture, e);\n }\n\n const exit = verdict.valid ? EXIT.OK : EXIT.INVALID;\n\n if (values.json === true) {\n // Machine output on the data channel: value-free (codes/severities/locations only).\n const body = { format, valid: verdict.valid, findings: verdict.findings };\n return { stdout: `${JSON.stringify(body)}\\n`, stderr: \"\", exit };\n }\n\n if (values.quiet === true) {\n // CI mode: the exit code is the whole signal. No stderr noise.\n return { stdout: \"\", stderr: \"\", exit };\n }\n\n return { stdout: \"\", stderr: renderReport(format, verdict), exit };\n}\n\n/** Render the value-free human report: one line per finding + a verdict summary line. */\nfunction renderReport(format: CosyteFormat, verdict: Verdict): string {\n const lines = verdict.findings.map(\n (f) => `cosyte: validate: ${f.severity} ${f.code} at ${f.location}\\n`,\n );\n const errors = verdict.findings.filter((f) => ERROR_SEVERITIES.has(f.severity)).length;\n const others = verdict.findings.length - errors;\n const summary = verdict.valid\n ? `cosyte: validate: ${format} is valid (${String(verdict.findings.length)} finding(s))\\n`\n : `cosyte: validate: ${format} is INVALID (${String(errors)} error(s), ${String(others)} other finding(s))\\n`;\n return lines.join(\"\") + summary;\n}\n","/**\n * The top-level **subcommand dispatcher**: a small hand-rolled router over Node's built-in\n * `util.parseArgs`, deliberately **third-party-framework-free** so the CLI core keeps zero third-party\n * runtime dependencies. It maps `argv[0]` to a command handler, serves `--help`\n * and `--version`, and turns any unexpected exception into a value-free `CLI_INTERNAL` result so a\n * stack trace carrying input can never reach the terminal.\n *\n * @packageDocumentation\n */\n\nimport { completionCommand } from \"../commands/completion.js\";\nimport { convertCommand } from \"../commands/convert.js\";\nimport { fmtCommand } from \"../commands/fmt.js\";\nimport { inspectCommand } from \"../commands/inspect.js\";\nimport { mapCodesCommand } from \"../commands/map-codes.js\";\nimport { parseCommand } from \"../commands/parse.js\";\nimport { redactCommand } from \"../commands/redact.js\";\nimport { validateCommand } from \"../commands/validate.js\";\nimport { deidCoveredFormats } from \"./deid.js\";\nimport { CLI_CODES, CliError, toCliError } from \"./diagnostics.js\";\nimport { EXIT } from \"./exit-codes.js\";\nimport type { RunDeps } from \"./io.js\";\nimport { describeByteLimit, MAX_INPUT_BYTES } from \"./limits.js\";\nimport { extractPhiPosture } from \"./phi.js\";\nimport type { RunResult } from \"./result.js\";\nimport { VERSION } from \"./version.js\";\n\n/**\n * Build the value-free `--help` text. Names commands, flags, the input-size limit, and exit codes,\n * never any input.\n *\n * The limit is **rendered from the constant the code enforces**, not typed in: the help output and\n * the published command reference state one number because there is only one number to state.\n *\n * @param limitBytes - The input-size limit to state. Defaults to {@link MAX_INPUT_BYTES}.\n * @returns The full help text.\n * @example\n * ```ts\n * import { helpText } from \"@cosyte/cli\";\n *\n * helpText(1024).includes(\"1024 bytes\"); // => true\n * ```\n */\nexport function helpText(limitBytes: number = MAX_INPUT_BYTES): string {\n return `cosyte: a PHI-safe developer CLI over the @cosyte/* healthcare parsers\n\nUsage:\n cosyte <command> [options]\n\nCommands:\n parse <file|-> Parse a healthcare message to typed JSON (format autodetected)\n validate <file|-> Validate a message; exit code carries the verdict (0 valid / 1 invalid)\n inspect <file|-> Print a value-free structural summary (segment/resource counts, type)\n fmt <file|-> Canonically re-serialize via the parser's spec-clean serializer\n convert <file|-> Convert HL7 v2 → FHIR R4 via @cosyte/transform (use --to fhir)\n map-codes <cmap|-> Translate a code through a BYO FHIR ConceptMap via @cosyte/terminology\n redact <file|-> De-identify a message via @cosyte/deid (alias: deid): ${deidCoveredFormats().join(\" \")}\n mcp Start the stdio MCP server (agent front door; also the cosyte-mcp bin)\n completion <shell> Print a shell completion script (bash | zsh | fish)\n\nGlobal:\n -h, --help Show this help\n -V, --version Show the CLI version\n --unsafe-show-values Permit input values on stderr/diagnostics (PHI-exposing; off by default)\n\nCommon options (parse / validate / inspect / fmt):\n --format <fmt> Override autodetection: hl7 | fhir | dicom | x12 | ccda | ncpdp | astm | mllp\n (parse: hl7 fhir x12 astm ncpdp mllp · inspect: all · fmt: hl7 fhir x12 astm\n ccda ncpdp · validate: all but mllp; dicom/ccda parse & mllp fmt are deferred)\n --json Machine-readable JSON output (parse / validate / inspect / convert / map-codes)\n --ndjson Treat each non-empty input line as a record; emit NDJSON (parse; FHIR bulk data)\n --quiet Suppress value-free notes on stderr\n --no-color Disable ANSI colour\n\nconvert options:\n --to fhir The conversion target (required; only HL7 v2 → FHIR R4 today)\n\nredact / deid (de-identification is delegated to @cosyte/deid; the CLI adds no policy of its own):\n Covered formats: ${deidCoveredFormats().join(\", \")}. Every other format is refused rather than\n approximated: astm, mllp and ncpdp have no adapter (69), and dicom is covered by the library but\n its de-identified form is a binary stream this text stdout cannot carry (65). If the library\n reports it could not handle an element, the run exits 1 and emits no output at all: a partial\n scrub presented as de-identified is the one outcome this command exists to prevent.\n stdout carries the de-identified document; stderr carries the library's own value-free manifest\n (category, transform, locus, count, disposition code) plus its published label and version.\n Identifier surrogates are keyed with a per-invocation ephemeral key: consistent within one\n output, not stable across runs.\n\nmap-codes options (the positional is a BYO FHIR ConceptMap; a code is not PHI):\n --code <code> The source code to translate (required)\n --system <uri> The source code system (optional; selects the ConceptMap group)\n --version <v> The source code system version (optional)\n --display <d> The source display (optional)\n\nInput size:\n parse reads at most ${describeByteLimit(limitBytes)} of input per invocation. A larger input is\n refused with CLI_INPUT_TOO_LARGE and the data-error exit code (65), never the internal-error\n code; split the input and re-run. Multi-record output (--ndjson, MLLP) is written record by\n record as it is parsed, so a refusal can arrive after some records have already been emitted:\n the exit code, not the output, is the signal that the run did not complete.\n\nExit codes:\n 0 success / valid 65 data error (unparseable / undetected format / input too large)\n 1 invalid (validate) 66 no input (missing/unreadable file)\n or de-identification incomplete (redact)\n 2 usage error 69 unavailable (a capability is not wired here, e.g. redact on a\n format @cosyte/deid has no adapter for)\n 70 internal error\n\nPHI posture: the parsed model goes to stdout (the data channel you chose); every diagnostic on\nstderr is value-free (codes and positions only, never a field value) unless you pass the loud,\nopt-in --unsafe-show-values (which permits a bounded input excerpt in a failure diagnostic).\n`;\n}\n\n/** The rendered help text for this build: the one place the default limit is stated. */\nconst HELP = helpText();\n\n/** True if `argv` requests help (`-h`/`--help` anywhere). */\nfunction wantsHelp(argv: readonly string[]): boolean {\n return argv.includes(\"--help\") || argv.includes(\"-h\");\n}\n\n/**\n * Run a full `cosyte` invocation as data.\n *\n * @param argv - The arguments after the program name (i.e. `process.argv.slice(2)`).\n * @param deps - Injected input readers ({@link RunDeps}).\n * @returns The {@link RunResult} to write to the process streams and exit with.\n * @example\n * ```ts\n * import { run } from \"@cosyte/cli\";\n *\n * const deps = { readFile: async () => new Uint8Array(), readStdin: async () => new Uint8Array() };\n * const { exit } = await run([\"--version\"], deps);\n * exit; // => 0\n * ```\n */\nexport async function run(argv: string[], deps: RunDeps): Promise<RunResult> {\n // Resolve the global, order-independent --unsafe-show-values flag once, and dispatch on the argv\n // with it removed so each command's own parseArgs never sees it (core/phi.ts).\n const { posture, argv: rest0 } = extractPhiPosture(argv);\n const [command, ...rest] = rest0;\n if (command === undefined || wantsHelp(rest0)) {\n return { stdout: HELP, stderr: \"\", exit: EXIT.OK };\n }\n if (command === \"--version\" || command === \"-V\") {\n return { stdout: `${VERSION}\\n`, stderr: \"\", exit: EXIT.OK };\n }\n\n try {\n switch (command) {\n case \"parse\":\n return await parseCommand(rest, deps, posture);\n case \"validate\":\n return await validateCommand(rest, deps, posture);\n case \"inspect\":\n return await inspectCommand(rest, deps, posture);\n case \"fmt\":\n return await fmtCommand(rest, deps, posture);\n case \"convert\":\n return await convertCommand(rest, deps, posture);\n case \"map-codes\":\n return await mapCodesCommand(rest, deps);\n case \"redact\":\n case \"deid\":\n return await redactCommand(rest, deps);\n case \"completion\":\n return completionCommand(rest);\n default:\n return resolve(\n new CliError(\n CLI_CODES.CLI_USAGE,\n EXIT.USAGE,\n `unknown command '${command}'; run \\`cosyte --help\\``,\n ),\n );\n }\n } catch (e) {\n return resolve(toCliError(e));\n }\n}\n\n/** Render a {@link CliError} as a value-free {@link RunResult}. */\nfunction resolve(e: CliError): RunResult {\n return { stdout: \"\", stderr: `cosyte: ${e.code}: ${e.message}\\n`, exit: e.exit };\n}\n"]}
|