@cosyte/synth 0.0.1
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 +414 -0
- package/LICENSE +21 -0
- package/README.md +325 -0
- package/dist/astm/index.cjs +847 -0
- package/dist/astm/index.cjs.map +1 -0
- package/dist/astm/index.d.cts +418 -0
- package/dist/astm/index.d.ts +418 -0
- package/dist/astm/index.mjs +828 -0
- package/dist/astm/index.mjs.map +1 -0
- package/dist/ccda/index.cjs +1103 -0
- package/dist/ccda/index.cjs.map +1 -0
- package/dist/ccda/index.d.cts +380 -0
- package/dist/ccda/index.d.ts +380 -0
- package/dist/ccda/index.mjs +1077 -0
- package/dist/ccda/index.mjs.map +1 -0
- package/dist/deid/index.cjs +2809 -0
- package/dist/deid/index.cjs.map +1 -0
- package/dist/deid/index.d.cts +464 -0
- package/dist/deid/index.d.ts +464 -0
- package/dist/deid/index.mjs +2793 -0
- package/dist/deid/index.mjs.map +1 -0
- package/dist/example-codes-DeXcnCSK.d.cts +105 -0
- package/dist/example-codes-DeXcnCSK.d.ts +105 -0
- package/dist/fhir/index.cjs +1429 -0
- package/dist/fhir/index.cjs.map +1 -0
- package/dist/fhir/index.d.cts +772 -0
- package/dist/fhir/index.d.ts +772 -0
- package/dist/fhir/index.mjs +1384 -0
- package/dist/fhir/index.mjs.map +1 -0
- package/dist/hl7/index.cjs +1012 -0
- package/dist/hl7/index.cjs.map +1 -0
- package/dist/hl7/index.d.cts +548 -0
- package/dist/hl7/index.d.ts +548 -0
- package/dist/hl7/index.mjs +990 -0
- package/dist/hl7/index.mjs.map +1 -0
- package/dist/index.cjs +535 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +407 -0
- package/dist/index.d.ts +407 -0
- package/dist/index.mjs +488 -0
- package/dist/index.mjs.map +1 -0
- package/dist/ncpdp/index.cjs +714 -0
- package/dist/ncpdp/index.cjs.map +1 -0
- package/dist/ncpdp/index.d.cts +432 -0
- package/dist/ncpdp/index.d.ts +432 -0
- package/dist/ncpdp/index.mjs +695 -0
- package/dist/ncpdp/index.mjs.map +1 -0
- package/dist/providers-OLz3zAc-.d.cts +343 -0
- package/dist/providers-OLz3zAc-.d.ts +343 -0
- package/dist/quirk-DmkgoZdh.d.cts +239 -0
- package/dist/quirk-JLyO1Ncj.d.ts +239 -0
- package/dist/x12/index.cjs +920 -0
- package/dist/x12/index.cjs.map +1 -0
- package/dist/x12/index.d.cts +484 -0
- package/dist/x12/index.d.ts +484 -0
- package/dist/x12/index.mjs +892 -0
- package/dist/x12/index.mjs.map +1 -0
- package/package.json +210 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/rng/splitmix32.ts","../../src/rng/sfc32.ts","../../src/rng/rng.ts","../../src/hl7/field.ts","../../src/safe/reserved.ts","../../src/safe/names-pool.ts","../../src/safe/providers.ts","../../src/safe/index.ts","../../src/hl7/common.ts","../../src/hl7/adt.ts","../../src/hl7/example-codes.ts","../../src/hl7/oru.ts","../../src/hl7/orm.ts","../../src/hl7/siu.ts","../../src/hl7/vxu.ts","../../src/hl7/index.ts","../../src/fhir/us-core.ts","../../src/fhir/builder.ts","../../src/fhir/example-codes.ts","../../src/fhir/patient.ts","../../src/fhir/condition.ts","../../src/fhir/observation.ts","../../src/fhir/medication-request.ts","../../src/fhir/encounter.ts","../../src/fhir/immunization.ts","../../src/fhir/allergy-intolerance.ts","../../src/fhir/procedure.ts","../../src/fhir/diagnostic-report.ts","../../src/fhir/composition.ts","../../src/fhir/bundle.ts","../../src/x12/money.ts","../../src/x12/identity.ts","../../src/x12/example-codes.ts","../../src/x12/claim-837.ts","../../src/x12/remit-835.ts","../../src/x12/eligibility-271.ts","../../src/ncpdp/identity.ts","../../src/ncpdp/example-codes.ts","../../src/ncpdp/telecom.ts","../../src/ccda/example-codes.ts","../../src/ccda/identity.ts","../../src/ccda/ccd.ts","../../src/deid/loop.ts","../../src/deid/index.ts"],"names":["address","phone","name","email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SAAA,EAAW,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,SAAA,CAAU,MAAA,EAAQ,CAAC,CAAA;AAAA,MAC1D,cAAA,EAAgB,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,cAAA,CAAe,MAAA,EAAQ,CAAC,CAAA;AAAA,MACpE,gBAAA,EAAkB,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,gBAAA,CAAiB,MAAA,EAAQ,CAAC,CAAA;AAAA,MACxE,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,KAAM,EAAE,IAAI;AAAA,KAC/B,CAAA;AAAA,EACH;AACA,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,YAAA,EAAc,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,CAAC,CAAA;AAAA,IAC9D,cAAA,EAAgB,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,SAAA,CAAU,MAAA,EAAQ,CAAC,CAAA;AAAA,IAClE,qBAAA,EAAuB,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,EAAG,MAAM,CAAA,GAAI,CAAA,CAAE,gBAAA,CAAiB,MAAA,EAAQ,CAAC,CAAA;AAAA,IAChF,SAAS,OAAA,CAAQ,KAAA,CAAM,CAAC,CAAA,KAAM,EAAE,IAAI,CAAA;AAAA,IACpC,OAAA,EAAS;AAAA,GACX;AACF","file":"index.mjs","sourcesContent":["/**\n * `splitmix32` — a tiny, well-studied 32-bit mixing PRNG used **only** to expand a single integer\n * seed into the four 32-bit state words that seed {@link ../rng/sfc32.sfc32}. It is not the corpus\n * generator itself (that is `sfc32`); it exists so that a one-number seed deterministically produces a\n * well-distributed 128-bit `sfc32` state, avoiding the poor low-bit behavior of naive\n * `state = seed`-style initialization.\n *\n * Zero-dependency, `Math.random`-free (lint-enforced): the whole point of the library is that a seed —\n * and only the seed — determines the output, on any machine, any run.\n *\n * @module\n */\n\n/**\n * A stateful `splitmix32` step function. Each call advances the internal 32-bit state and returns the\n * next unsigned 32-bit integer. Deterministic for a given seed.\n *\n * @param seed - The 32-bit seed. Coerced to a 32-bit integer via `| 0`.\n * @returns A nullary function returning the next `uint32` in the stream.\n * @example\n * ```ts\n * import { splitmix32 } from \"@cosyte/synth\";\n * const next = splitmix32(12345);\n * const a = next(); // deterministic uint32\n * ```\n */\nexport function splitmix32(seed: number): () => number {\n let a = seed | 0;\n return function next(): number {\n a = (a + 0x9e3779b9) | 0;\n let t = a ^ (a >>> 16);\n t = Math.imul(t, 0x21f0aaad);\n t = t ^ (t >>> 15);\n t = Math.imul(t, 0x735a2d97);\n t = t ^ (t >>> 15);\n return t >>> 0;\n };\n}\n","/**\n * `sfc32` (Small Fast Counter, 32-bit, 128-bit state) — the deterministic, non-cryptographic PRNG that\n * drives every value `@cosyte/synth` generates. Chosen over `mulberry32` (whose author flags that it\n * skips ~1/3 of 32-bit outputs) and over a CSPRNG (`node:crypto`, which is **not seedable** and would\n * defeat reproducibility). A synthetic-fixture generator has **no secrets** — statistical quality plus\n * byte-for-byte reproducibility is exactly the right trade.\n *\n * The state is four 32-bit words. This module exposes the raw step function; {@link ../rng/rng.Rng}\n * wraps it with a seed-expansion ({@link ./splitmix32.splitmix32}) and the ergonomic draw helpers.\n *\n * @module\n */\n\n/**\n * The mutable four-word `sfc32` state. Threaded explicitly (never global) by {@link ../rng/rng.Rng}.\n */\nexport interface Sfc32State {\n /** State word `a`. */\n a: number;\n /** State word `b`. */\n b: number;\n /** State word `c`. */\n c: number;\n /** Counter word `d`. */\n d: number;\n}\n\n/**\n * Advance an {@link Sfc32State} in place by one step and return the next unsigned 32-bit integer.\n *\n * This is the canonical `sfc32` step. The state object is mutated (the counter `d` increments and the\n * mixing words rotate); callers that need reproducible independence hold their own state and never\n * share it — {@link ../rng/rng.Rng} creates a fresh state per seed so two runs from the same seed are\n * identical.\n *\n * @param s - The state to advance. Mutated in place.\n * @returns The next `uint32` in the stream.\n * @example\n * ```ts\n * import { sfc32Next, type Sfc32State } from \"@cosyte/synth\";\n * const s: Sfc32State = { a: 1, b: 2, c: 3, d: 4 };\n * const x = sfc32Next(s); // uint32\n * ```\n */\nexport function sfc32Next(s: Sfc32State): number {\n s.a |= 0;\n s.b |= 0;\n s.c |= 0;\n s.d |= 0;\n const t = (((s.a + s.b) | 0) + s.d) | 0;\n s.d = (s.d + 1) | 0;\n s.a = s.b ^ (s.b >>> 9);\n s.b = (s.c + (s.c << 3)) | 0;\n s.c = (s.c << 21) | (s.c >>> 11);\n s.c = (s.c + t) | 0;\n return t >>> 0;\n}\n","/**\n * `Rng` — the seeded, deterministic random source every `@cosyte/synth` provider draws from.\n *\n * **The reproducibility contract.** A seed — and only the seed — determines the output.\n * `createRng(seed)` expands the integer seed through {@link ./splitmix32.splitmix32} into the four\n * `sfc32` state words, then every draw advances that state via {@link ./sfc32.sfc32Next}. Two `Rng`s\n * created from the same seed emit the **identical** sequence on any machine, any run — the property\n * the parsers', `transform`'s, and `deid`'s regression suites depend on.\n *\n * **Explicit, never global.** An `Rng` is a value you thread through a build; there is no ambient\n * shared generator and **`Math.random` is lint-banned** in `src/` (it is not seedable — its seed is\n * engine-chosen and cannot be reset, so a corpus built on it is not reproducible). Because each\n * generation creates a fresh `Rng` from its seed, generations are independent and parallel-safe.\n *\n * The `Rng` object is stateful by nature (a PRNG advances). Immutability in this library lives where it\n * is testable and matters: the generated **artifacts and the `Corpus` are deep-frozen** (see\n * `../corpus.ts`). Determinism, not object-immutability, is the `Rng`'s guarantee.\n *\n * @module\n */\n\nimport { splitmix32 } from \"./splitmix32.js\";\nimport { sfc32Next, type Sfc32State } from \"./sfc32.js\";\n\n/**\n * A seeded, deterministic random source. Created via {@link createRng}; passed explicitly to every\n * provider. All draw methods advance the internal state deterministically.\n */\nexport interface Rng {\n /** The integer seed this generator was created from (part of the `Corpus` manifest). */\n readonly seed: number;\n /** The next unsigned 32-bit integer. */\n nextUint32(): number;\n /** The next float in `[0, 1)`. */\n float(): number;\n /**\n * A uniformly-distributed integer in the inclusive range `[min, max]`.\n *\n * @param min - Inclusive lower bound (integer).\n * @param max - Inclusive upper bound (integer, `>= min`).\n */\n int(min: number, max: number): number;\n /** `true` with probability `p` (default `0.5`). */\n bool(p?: number): boolean;\n /**\n * Pick one element from a non-empty array.\n *\n * @param items - A non-empty readonly array.\n */\n pick<T>(items: readonly T[]): T;\n /**\n * A string of `n` decimal digits (`0`–`9`), each drawn uniformly.\n *\n * @param n - The number of digits (`>= 0`).\n */\n digits(n: number): string;\n}\n\n/**\n * The concrete {@link Rng}. Holds the mutable `sfc32` state; every method advances it deterministically.\n */\nclass Sfc32Rng implements Rng {\n public readonly seed: number;\n readonly #state: Sfc32State;\n\n public constructor(seed: number) {\n this.seed = seed | 0;\n // Expand the single seed into four well-distributed state words. Seeding sfc32 directly from the\n // raw seed gives poor low-bit behavior; splitmix32 is the standard fix (bryc / roadmap §5).\n const mix = splitmix32(this.seed);\n this.#state = { a: mix(), b: mix(), c: mix(), d: mix() };\n // A short warm-up so nearby seeds diverge immediately.\n for (let i = 0; i < 8; i += 1) sfc32Next(this.#state);\n }\n\n public nextUint32(): number {\n return sfc32Next(this.#state);\n }\n\n public float(): number {\n return this.nextUint32() / 0x1_0000_0000;\n }\n\n public int(min: number, max: number): number {\n if (max < min) throw new RangeError(`Rng.int: max (${String(max)}) < min (${String(min)})`);\n const span = max - min + 1;\n return min + Math.floor(this.float() * span);\n }\n\n public bool(p = 0.5): boolean {\n return this.float() < p;\n }\n\n public pick<T>(items: readonly T[]): T {\n if (items.length === 0) throw new RangeError(\"Rng.pick: empty array\");\n // `int(0, length-1)` is always in-bounds on a non-empty array, so this access cannot be a hole;\n // the cast discharges `noUncheckedIndexedAccess`'s `T | undefined` without a runtime re-check.\n return items[this.int(0, items.length - 1)] as T;\n }\n\n public digits(n: number): string {\n let out = \"\";\n for (let i = 0; i < n; i += 1) out += String(this.int(0, 9));\n return out;\n }\n}\n\n/**\n * Create a seeded, deterministic {@link Rng}. The same `seed` yields the same sequence everywhere.\n *\n * @param seed - The integer seed. Coerced to a 32-bit integer.\n * @returns A fresh, independent {@link Rng}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * const rng = createRng(12345);\n * rng.int(1, 6); // deterministic for seed 12345\n * ```\n */\nexport function createRng(seed: number): Rng {\n return new Sfc32Rng(seed);\n}\n","/**\n * Thin helpers that build `@cosyte/hl7` `RawField` objects with **components** for `addSegment`.\n *\n * Why this exists: `Hl7Message.addSegment` accepts a field as either a plain string or a structured\n * `RawField`. A plain string is emitted **verbatim** — a literal `^` in it is escaped to `\\S\\`, not\n * treated as a component separator (the parser re-escapes on serialize, by design). To place true\n * components (a name's family/given, a CX's id/authority/type) we must hand `addSegment` a `RawField`\n * with explicit `components`, so the parser's own conservative serializer lays out the separators.\n * That is the whole point of building *through* the parser.\n *\n * @module\n */\n\nimport type { RawField } from \"@cosyte/hl7\";\n\n/**\n * Build a `RawField` from a flat list of component strings (single repetition, single subcomponent\n * per component). Empty strings become empty components (absent at the wire level).\n *\n * @param components - The component values, in HL7 component order.\n * @returns A `RawField` the hl7 serializer lays out with `^` separators.\n * @example\n * ```ts\n * import { componentsField } from \"@cosyte/synth/hl7\";\n * componentsField([\"Testerson\", \"Quilliam\"]); // family^given\n * ```\n */\nexport function componentsField(components: readonly string[]): RawField {\n return {\n repetitions: [{ components: components.map((c) => ({ subcomponents: [c] })) }],\n isNull: false,\n };\n}\n","/**\n * The reserved / never-collide identifier facts that make a `@cosyte/synth` value **provably\n * synthetic** — the ground truth behind the synthetic-safety invariant.\n *\n * These are **facts**, not copyrighted prose: authoritative ranges published by SSA, NANPA, and the\n * IETF that are guaranteed never to denote a real person or a real routable resource. Every provider\n * draws only from these; the predicates here are the executable half of the CI synthetic-safety gate —\n * they let a test assert that no emitted value falls **outside** a reserved source.\n *\n * Sources:\n * - **SSN** — SSA never issues area numbers `000`, `666`, or `900–999`; the `987-65-4320…4329` block\n * is SSA's explicitly-reserved advertising range. (ssa.gov)\n * - **Phone** — NANP reserves `555-0100…555-0199` as the fictional/non-working line range. (nanpa.com)\n * - **Email/domain** — RFC 2606 / RFC 6761 reserved: `example.com`/`.net`/`.org` and the `.example`,\n * `.test`, `.invalid`, `.localhost` TLDs.\n * - **IP** — RFC 5737 IPv4 TEST-NET-1/2/3 (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`) and\n * RFC 3849 IPv6 documentation prefix `2001:db8::/32`.\n * - **NPI** — a real National Provider Identifier is a 10-digit number whose last digit is a Luhn\n * check digit computed over the `80840` prefix + the 9-digit base (CMS NPI check-digit rule, ISO\n * 7812). A number whose check digit is **wrong** therefore cannot be a NPPES-issued NPI. `synth`\n * emits NPIs with a deliberately-invalid check digit, so no generated NPI can collide with a real\n * provider.\n *\n * @module\n */\n\n/**\n * The synthetic **assigning authority** `@cosyte/synth` mints MRNs / account / member identifiers\n * under. There is **no** reserved MRN range (an MRN is unique only within its assigning-authority /\n * OID namespace), so — a documented design decision — every synthetic identifier\n * is scoped to a namespace that clearly cannot be a real facility's: a `SYNTH`-labelled authority whose\n * OID lives under HL7's designated **example** root `2.16.840.1.113883.19`. A value under this AA can\n * never collide with a real record because the *namespace itself* is synthetic.\n */\nexport const SYNTHETIC_ASSIGNING_AUTHORITY = Object.freeze({\n /** The human-readable assigning-authority namespace id (HL7 HD.1). */\n namespaceId: \"COSYTE-SYNTH\",\n /** The universal id — an OID under HL7's example arc `2.16.840.1.113883.19` (HD.2). */\n universalId: \"2.16.840.1.113883.19.999\",\n /** The universal id type (HD.3). */\n universalIdType: \"ISO\",\n});\n\n/** RFC 2606 / 6761 reserved email domains `@cosyte/synth` draws from. */\nexport const RESERVED_EMAIL_DOMAINS: readonly string[] = Object.freeze([\n \"example.com\",\n \"example.org\",\n \"example.net\",\n]);\n\n/** RFC 5737 IPv4 documentation (TEST-NET) `/24` network prefixes. */\nexport const TEST_NET_V4_PREFIXES: readonly string[] = Object.freeze([\n \"192.0.2\", // TEST-NET-1\n \"198.51.100\", // TEST-NET-2\n \"203.0.113\", // TEST-NET-3\n]);\n\n/** RFC 3849 IPv6 documentation prefix. */\nexport const DOC_V6_PREFIX = \"2001:db8\";\n\n/**\n * The `80840` prefix prepended to a 10-digit NPI before the Luhn check (the CMS NPI check-digit\n * rule — `80840` is the ISO 7812 issuer identifier for the US health-application namespace). A real\n * NPI satisfies `luhn(\"80840\" + npi) ≡ 0 (mod 10)`.\n */\nexport const NPI_LUHN_PREFIX = \"80840\";\n\n/**\n * The Luhn sum (mod 10) of a numeric string, doubling every second digit from the right. Used to\n * verify (or deliberately break) an NPI check digit.\n *\n * @param digits - A string of decimal digits.\n * @returns The Luhn sum modulo 10 (0 ⇒ the string passes the Luhn check).\n * @internal\n */\nexport function luhnMod10(digits: string): number {\n let sum = 0;\n // Standard Luhn: the RIGHTMOST digit is never doubled; doubling starts one position in and\n // alternates. For a full payload+check string this makes a Luhn-valid string sum to 0 (mod 10);\n // for a payload with a `0` placeholder in the check position it yields the complement of the\n // correct check digit.\n let double = false;\n for (let i = digits.length - 1; i >= 0; i -= 1) {\n let d = digits.charCodeAt(i) - 48;\n if (d < 0 || d > 9) continue;\n if (double) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n double = !double;\n }\n return sum % 10;\n}\n\n/**\n * The correct NPI check digit for a 9-digit base — the value that makes `80840` + base + check pass\n * the Luhn check.\n *\n * @param base9 - The 9-digit NPI base (positions 1–9).\n * @returns The check digit (`0`–`9`) a real NPI would carry for this base.\n * @example\n * ```ts\n * import { npiCheckDigit } from \"@cosyte/synth\";\n * npiCheckDigit(\"123456789\"); // 3 — so 1234567893 is a Luhn-valid NPI shape\n * ```\n */\nexport function npiCheckDigit(base9: string): number {\n // Luhn over \"80840\" + base9 with a trailing 0 check placeholder; the check digit closes the sum.\n const partial = luhnMod10(`${NPI_LUHN_PREFIX}${base9}0`);\n return (10 - partial) % 10;\n}\n\n/**\n * The DEA-registration prefix letters `@cosyte/synth` draws a synthetic DEA number's first character\n * from. A real DEA number is `<registrant-type><last-name-initial>` + 7 digits; the first letter is the\n * registrant type (A/B/F/G/M/P/R/X are the widely-published values; the second letter is the\n * registrant's last-name initial). These letters are a **fact** about the number's shape, not\n * copyrighted prose — they only shape the value; the synthetic guarantee is the deliberately-**invalid\n * checksum** (see {@link dea} / {@link isSyntheticDea}).\n */\nexport const DEA_REGISTRANT_TYPES: readonly string[] = Object.freeze([\n \"A\",\n \"B\",\n \"F\",\n \"G\",\n \"M\",\n \"P\",\n \"R\",\n \"X\",\n]);\n\n/**\n * The correct DEA check digit for a 7-digit numeric base. The published DEA checksum is\n * `(d1 + d3 + d5) + 2·(d2 + d4 + d6)`, whose **units digit** is the 7th (check) digit. A real DEA\n * number satisfies this; a number whose 7th digit differs cannot be a validly-issued DEA registration.\n *\n * @param base6 - The first 6 digits of the DEA number (positions 1–6).\n * @returns The check digit (`0`–`9`) a real DEA number would carry for this base.\n * @example\n * ```ts\n * import { deaCheckDigit } from \"@cosyte/synth\";\n * deaCheckDigit(\"123456\"); // the units digit of (1+3+5) + 2·(2+4+6)\n * ```\n */\nexport function deaCheckDigit(base6: string): number {\n let odd = 0;\n let even = 0;\n for (let i = 0; i < 6; i += 1) {\n const digit = base6.charCodeAt(i) - 48;\n if (i % 2 === 0) odd += digit;\n else even += digit;\n }\n return (odd + 2 * even) % 10;\n}\n\n/**\n * Whether a DEA number (`XX` + 7 digits, case-insensitive) is **provably synthetic** — its check digit\n * (the 7th digit) does **not** match the published DEA checksum, so it cannot be a validly-issued DEA\n * registration. A checksum-valid DEA number (which *could* denote a real prescriber) returns `false`; a\n * value that is not the DEA shape returns `false`.\n *\n * @param value - The candidate DEA number (with or without incidental separators).\n * @returns `true` when the DEA number's checksum is wrong (never a real DEA registration).\n * @example\n * ```ts\n * import { isSyntheticDea } from \"@cosyte/synth\";\n * isSyntheticDea(\"AF1234561\"); // depends on the base — true when the 7th digit is wrong\n * ```\n */\nexport function isSyntheticDea(value: string): boolean {\n const compact = value.replace(/[\\s-]/g, \"\").toUpperCase();\n if (!/^[A-Z]{2}\\d{7}$/.test(compact)) return false;\n const digits = compact.slice(2);\n const check = digits.charCodeAt(6) - 48;\n return deaCheckDigit(digits.slice(0, 6)) !== check;\n}\n\n/**\n * Whether a 10-digit NPI is **provably synthetic** — i.e. its check digit is invalid, so it cannot be\n * a NPPES-issued NPI. A Luhn-valid 10-digit NPI (which *could* denote a real registered provider)\n * returns `false`; a non-10-digit value returns `false` (not an NPI shape).\n *\n * @param value - The candidate NPI (digits only, or with incidental separators).\n * @returns `true` when the NPI's check digit is wrong (never a real NPI).\n * @example\n * ```ts\n * import { isSyntheticNpi } from \"@cosyte/synth\";\n * isSyntheticNpi(\"1234567894\"); // true — invalid check digit (valid would be 1234567893)\n * isSyntheticNpi(\"1234567893\"); // false — Luhn-valid, could be a real NPI\n * ```\n */\nexport function isSyntheticNpi(value: string): boolean {\n const digits = value.replace(/\\D/g, \"\");\n if (digits.length !== 10) return false;\n return luhnMod10(`${NPI_LUHN_PREFIX}${digits}`) !== 0;\n}\n\n/**\n * Whether a `ddd-dd-dddd` (or `ddddddddd`) SSN string is drawn from an SSA never-issued / reserved\n * space — area `000`, `666`, or `900–999`. A real, issuable SSN returns `false`.\n *\n * @param value - The candidate SSN (dashes optional).\n * @returns `true` when the SSN is provably synthetic.\n * @example\n * ```ts\n * import { isSyntheticSsn } from \"@cosyte/synth\";\n * isSyntheticSsn(\"900-12-3456\"); // true (never issued)\n * isSyntheticSsn(\"123456789\"); // false (issuable area 123)\n * ```\n */\nexport function isSyntheticSsn(value: string): boolean {\n const digits = value.replace(/\\D/g, \"\");\n if (digits.length !== 9) return false;\n const area = Number(digits.slice(0, 3));\n return area === 0 || area === 666 || area >= 900;\n}\n\n/**\n * Whether a phone string contains the NANP `555-0100…555-0199` reserved fictional line range.\n *\n * @param value - The candidate phone (any formatting).\n * @returns `true` when the number is in the reserved fictional block.\n * @example\n * ```ts\n * import { isSyntheticPhone } from \"@cosyte/synth\";\n * isSyntheticPhone(\"(202) 555-0142\"); // true\n * ```\n */\nexport function isSyntheticPhone(value: string): boolean {\n const digits = value.replace(/\\D/g, \"\");\n // The reserved guarantee is the 7-digit tail: exchange 555 + line 01NN.\n const tail = digits.slice(-7);\n return /^555 ?01\\d\\d$/.test(tail) || /^55501\\d\\d$/.test(tail);\n}\n\n/**\n * Whether an email's domain is an RFC 2606 / 6761 reserved / test domain.\n *\n * @param value - The candidate email address.\n * @returns `true` when the domain is reserved (never real).\n * @example\n * ```ts\n * import { isSyntheticEmail } from \"@cosyte/synth\";\n * isSyntheticEmail(\"faux.testerson@example.com\"); // true\n * ```\n */\nexport function isSyntheticEmail(value: string): boolean {\n const at = value.lastIndexOf(\"@\");\n if (at < 0) return false;\n const domain = value.slice(at + 1).toLowerCase();\n if (RESERVED_EMAIL_DOMAINS.includes(domain)) return true;\n return /\\.(example|test|invalid|localhost)$/.test(domain);\n}\n\n/**\n * Whether an IP string is in an RFC 5737 (IPv4 TEST-NET) or RFC 3849 (IPv6 documentation) reserved\n * block. A real routable address returns `false`.\n *\n * @param value - The candidate IPv4 or IPv6 address.\n * @returns `true` when the address is a reserved documentation address.\n * @example\n * ```ts\n * import { isSyntheticIp } from \"@cosyte/synth\";\n * isSyntheticIp(\"192.0.2.44\"); // true (TEST-NET-1)\n * isSyntheticIp(\"8.8.8.8\"); // false (real)\n * ```\n */\nexport function isSyntheticIp(value: string): boolean {\n if (value.toLowerCase().startsWith(`${DOC_V6_PREFIX}:`)) return true;\n return TEST_NET_V4_PREFIXES.some((prefix) => value.startsWith(`${prefix}.`));\n}\n","/**\n * The shipped **clearly-fake name pool** — `@cosyte/synth`'s own license-clean synthetic data.\n *\n * Deliberately **not** a `faker`-style realistic-name corpus (which could match a real person at a real\n * address — the exact hazard the synthetic-safety invariant forbids). Every token is\n * an obviously-invented, fixture-flavoured word: a reader can tell at a glance it names no one. The pool\n * is small on purpose — structural coverage, not demographic realism, is the goal.\n *\n * `# synthetic: true`\n *\n * @module\n */\n\n/** Obviously-synthetic given names. None is a plausible real person's name. */\nexport const SYNTHETIC_GIVEN_NAMES: readonly string[] = Object.freeze([\n \"Testina\",\n \"Fixtura\",\n \"Synthos\",\n \"Placeholda\",\n \"Sampleton\",\n \"Prototius\",\n \"Stubbina\",\n \"Exampla\",\n \"Quilliam\",\n \"Fabrica\",\n \"Simula\",\n \"Testry\",\n \"Seedwin\",\n \"Corpora\",\n \"Reprodo\",\n \"Mocktavia\",\n \"Dummett\",\n \"Voidwin\",\n \"Deteria\",\n \"Randomir\",\n]);\n\n/** Obviously-synthetic family names. None is a plausible real surname at a real address. */\nexport const SYNTHETIC_FAMILY_NAMES: readonly string[] = Object.freeze([\n \"Testerson\",\n \"Fauxman\",\n \"Placeholt\",\n \"Mockridge\",\n \"Fixtingham\",\n \"Synthwell\",\n \"Dummerton\",\n \"Examplewood\",\n \"Fabricant\",\n \"Simulacre\",\n \"Nonesuch\",\n \"Seedman\",\n \"Corpusworth\",\n \"Reprodus\",\n \"Voidmark\",\n \"Deterwood\",\n \"Randomson\",\n \"Quillfeather\",\n \"Notreal\",\n \"Genfield\",\n]);\n\n/** Obviously-synthetic street names for structured address fields. */\nexport const SYNTHETIC_STREET_NAMES: readonly string[] = Object.freeze([\n \"Fixture Lane\",\n \"Sample Street\",\n \"Placeholder Avenue\",\n \"Synthetic Way\",\n \"Example Boulevard\",\n \"Testing Terrace\",\n \"Mock Road\",\n \"Prototype Court\",\n]);\n\n/**\n * Obviously-synthetic city names. Combined only ever with a synthetic street + a fake name (the\n * *combination* is what identifies, and the combination is always synthetic).\n */\nexport const SYNTHETIC_CITY_NAMES: readonly string[] = Object.freeze([\n \"Faketon\",\n \"Synthville\",\n \"Exampleburg\",\n \"Testford\",\n \"Mockhaven\",\n \"Fixtureton\",\n]);\n","/**\n * The synthetic-safety provider layer — every identifier, contact point, name, and date\n * `@cosyte/synth` emits is minted here, and **only** from a guaranteed-non-colliding source. There is no code\n * path that returns a value not drawn from a reserved range or the\n * shipped fake-name pool. This is the inverse of a parser's liberality: the generator is *closed-world*\n * on its data sources, so no output *can* be real or plausibly-real PHI.\n *\n * All providers are pure functions of an explicit {@link ../rng/rng.Rng} — same seed, same values.\n *\n * @module\n */\n\nimport type { Rng } from \"../rng/rng.js\";\n\nimport {\n RESERVED_EMAIL_DOMAINS,\n TEST_NET_V4_PREFIXES,\n DOC_V6_PREFIX,\n SYNTHETIC_ASSIGNING_AUTHORITY,\n npiCheckDigit,\n deaCheckDigit,\n DEA_REGISTRANT_TYPES,\n} from \"./reserved.js\";\nimport {\n SYNTHETIC_GIVEN_NAMES,\n SYNTHETIC_FAMILY_NAMES,\n SYNTHETIC_STREET_NAMES,\n SYNTHETIC_CITY_NAMES,\n} from \"./names-pool.js\";\n\n/** A synthetic person name drawn from the shipped fake-name pool. */\nexport interface SyntheticName {\n /** A clearly-fake given name. */\n readonly given: string;\n /** A clearly-fake family name. */\n readonly family: string;\n}\n\n/** A synthetic postal address — synthetic street + city, a fixed non-real ZIP. */\nexport interface SyntheticAddress {\n /** A clearly-fake street line. */\n readonly street: string;\n /** A clearly-fake city. */\n readonly city: string;\n /** A US state abbreviation (structural only; never combined with a real street + name + DOB). */\n readonly state: string;\n /** A reserved non-real ZIP (`00000`). */\n readonly zip: string;\n}\n\n/** A synthetic identifier scoped to the synthetic assigning authority. */\nexport interface SyntheticIdentifier {\n /** The identifier value (digits) — unique only within the synthetic namespace. */\n readonly value: string;\n /** HL7 identifier type code (`MR` = medical record, `AN` = account, `MB` = member). */\n readonly typeCode: \"MR\" | \"AN\" | \"MB\";\n /** The synthetic assigning-authority namespace id. */\n readonly assigningAuthority: string;\n /** The synthetic assigning-authority OID (HL7 example arc). */\n readonly assigningAuthorityOid: string;\n}\n\n/** Which SSN reserved space to draw from. */\nexport type SsnBlock = \"never-issued\" | \"advertising\";\n\n/**\n * A **synthetic SSN** — dashed `AAA-GG-SSSS`. Default draws the SSA never-issued area space\n * (`900–999`); `block: \"advertising\"` draws SSA's reserved advertising block (`987-65-4320…4329`).\n * A value from this function can never be a real SSN.\n *\n * @param rng - The seeded generator.\n * @param block - Which reserved space to draw from. Defaults to `\"never-issued\"`.\n * @returns A dashed synthetic SSN string.\n * @example\n * ```ts\n * import { createRng, ssn } from \"@cosyte/synth\";\n * ssn(createRng(1)); // e.g. a 900-area, never-issued SSN\n * ```\n */\nexport function ssn(rng: Rng, block: SsnBlock = \"never-issued\"): string {\n if (block === \"advertising\") {\n // SSA's explicitly-reserved advertising block: last digit 0..9 within -4320..-4329.\n return `987-65-432${String(rng.int(0, 9))}`;\n }\n const area = rng.int(900, 999); // SSA never issues 900-999.\n const group = rng.digits(2);\n const serial = rng.digits(4);\n return `${String(area)}-${group}-${serial}`;\n}\n\n/**\n * A **synthetic phone** in the NANP reserved fictional block — `(AAA) 555-01NN`. The reserved\n * guarantee is the `555-01NN` tail (exchange 555, line 0100–0199); the area code is any NANP-valid\n * `NXX`. Can never be a working number.\n *\n * @param rng - The seeded generator.\n * @returns A formatted synthetic phone string.\n * @example\n * ```ts\n * import { createRng, phone } from \"@cosyte/synth\";\n * phone(createRng(1)); // e.g. \"(2XX) 555-01NN\"\n * ```\n */\nexport function phone(rng: Rng): string {\n const area = `${String(rng.int(2, 9))}${rng.digits(2)}`; // NXX area code.\n const line = `01${rng.digits(2)}`; // reserved 0100-0199.\n return `(${area}) 555-${line}`;\n}\n\n/**\n * A **synthetic name** drawn from the shipped clearly-fake pool.\n *\n * @param rng - The seeded generator.\n * @returns A {@link SyntheticName}.\n * @example\n * ```ts\n * import { createRng, name } from \"@cosyte/synth\";\n * const { given, family } = name(createRng(1));\n * ```\n */\nexport function name(rng: Rng): SyntheticName {\n return { given: rng.pick(SYNTHETIC_GIVEN_NAMES), family: rng.pick(SYNTHETIC_FAMILY_NAMES) };\n}\n\n/**\n * A **synthetic email** at an RFC 2606 / 6761 reserved domain — `<slug>@example.com`.\n *\n * @param rng - The seeded generator.\n * @param person - Optional name to derive the local-part slug from; otherwise a random slug is used.\n * @returns A synthetic email address.\n * @example\n * ```ts\n * import { createRng, email, name } from \"@cosyte/synth\";\n * email(createRng(1), name(createRng(1))); // \"<given>.<family>@example.com\"\n * ```\n */\nexport function email(rng: Rng, person?: SyntheticName): string {\n const domain = rng.pick(RESERVED_EMAIL_DOMAINS);\n const slug = person ? `${person.given}.${person.family}`.toLowerCase() : `synth${rng.digits(6)}`;\n return `${slug}@${domain}`;\n}\n\n/**\n * A **synthetic IPv4** in an RFC 5737 TEST-NET block — never routable.\n *\n * @param rng - The seeded generator.\n * @returns A TEST-NET IPv4 address string.\n * @example\n * ```ts\n * import { createRng, ipv4 } from \"@cosyte/synth\";\n * ipv4(createRng(1)); // e.g. \"192.0.2.NN\"\n * ```\n */\nexport function ipv4(rng: Rng): string {\n return `${rng.pick(TEST_NET_V4_PREFIXES)}.${String(rng.int(1, 254))}`;\n}\n\n/**\n * A **synthetic IPv6** in the RFC 3849 documentation prefix `2001:db8::/32` — never routable.\n *\n * @param rng - The seeded generator.\n * @returns A documentation-prefix IPv6 address string.\n * @example\n * ```ts\n * import { createRng, ipv6 } from \"@cosyte/synth\";\n * ipv6(createRng(1)); // e.g. \"2001:db8::NNNN\"\n * ```\n */\nexport function ipv6(rng: Rng): string {\n const tail = rng.nextUint32().toString(16).padStart(4, \"0\").slice(-4);\n return `${DOC_V6_PREFIX}::${tail}`;\n}\n\n/**\n * A **deterministic UUIDv4-shaped** surrogate key from the seeded generator. Because it is seeded (not\n * from `node:crypto`, which is not reproducible), the cryptographic non-collision argument is weaker —\n * acceptable because the identifier namespace is synthetic anyway, and noted honestly.\n *\n * @param rng - The seeded generator.\n * @returns A canonical `8-4-4-4-12` lowercase-hex UUID string with version `4` and RFC 4122 variant.\n * @example\n * ```ts\n * import { createRng, uuid } from \"@cosyte/synth\";\n * uuid(createRng(1)); // \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\"\n * ```\n */\nexport function uuid(rng: Rng): string {\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i += 1) bytes[i] = rng.int(0, 255);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40; // version 4\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // variant 10xx\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10, 16).join(\"\")}`;\n}\n\n/**\n * A **synthetic NPI** — a 10-digit National Provider Identifier with a **deliberately-invalid Luhn\n * check digit**, so it can never be a NPPES-issued NPI (a real NPI must satisfy the `80840`-prefixed\n * Luhn check). The 9-digit base is drawn from the seeded generator; the check digit is\n * set to `(correct + 1) mod 10`, guaranteeing the full value fails validation.\n *\n * @param rng - The seeded generator.\n * @returns A 10-digit NPI-shaped string that is provably not a real NPI.\n * @example\n * ```ts\n * import { createRng, npi, isSyntheticNpi } from \"@cosyte/synth\";\n * isSyntheticNpi(npi(createRng(1))); // true — invalid check digit by construction\n * ```\n */\nexport function npi(rng: Rng): string {\n const base9 = rng.digits(9);\n const wrongCheck = (npiCheckDigit(base9) + 1) % 10;\n return `${base9}${String(wrongCheck)}`;\n}\n\n/**\n * A **synthetic DEA number** — `<registrant-type><initial>` + 7 digits with a **deliberately-invalid\n * checksum**, so it can never be a validly-issued DEA registration (a real DEA number's 7th digit\n * satisfies the published DEA checksum). The first letter is a registrant-type letter, the\n * second is derived from `person` (its family initial) when supplied so the number reads plausibly; the\n * 6-digit base is seeded and the check digit is set to `(correct + 1) mod 10`, guaranteeing the value\n * fails validation. NCPDP carries prescriber DEA, and this is the identity locus a refuter attacks\n * hardest, so — like {@link npi} — non-collision is a construction-level guarantee, not a heuristic.\n *\n * @param rng - The seeded generator.\n * @param person - Optional name whose family initial becomes the DEA's second letter.\n * @returns A DEA-shaped string that is provably not a real DEA registration.\n * @example\n * ```ts\n * import { createRng, dea, isSyntheticDea } from \"@cosyte/synth\";\n * isSyntheticDea(dea(createRng(1))); // true — invalid checksum by construction\n * ```\n */\nexport function dea(rng: Rng, person?: SyntheticName): string {\n const type = rng.pick(DEA_REGISTRANT_TYPES);\n const initialSource = person?.family ?? rng.pick(SYNTHETIC_FAMILY_NAMES);\n const initial = initialSource.slice(0, 1).toUpperCase();\n const base6 = rng.digits(6);\n const wrongCheck = (deaCheckDigit(base6) + 1) % 10;\n return `${type}${initial}${base6}${String(wrongCheck)}`;\n}\n\n/**\n * A **synthetic identifier** (MRN / account / member id) scoped to the synthetic assigning authority.\n * There is no reserved MRN range, so non-collision is guaranteed by the *namespace*, not the value: the\n * identifier lives under a `SYNTH` authority no real facility uses.\n *\n * @param rng - The seeded generator.\n * @param typeCode - The HL7 identifier type: `MR` (default), `AN`, or `MB`.\n * @returns A {@link SyntheticIdentifier}.\n * @example\n * ```ts\n * import { createRng, identifier } from \"@cosyte/synth\";\n * identifier(createRng(1), \"MR\"); // { value, typeCode: \"MR\", assigningAuthority: \"COSYTE-SYNTH\", ... }\n * ```\n */\nexport function identifier(\n rng: Rng,\n typeCode: SyntheticIdentifier[\"typeCode\"] = \"MR\",\n): SyntheticIdentifier {\n return {\n value: rng.digits(8),\n typeCode,\n assigningAuthority: SYNTHETIC_ASSIGNING_AUTHORITY.namespaceId,\n assigningAuthorityOid: SYNTHETIC_ASSIGNING_AUTHORITY.universalId,\n };\n}\n\n/**\n * A **synthetic address** — a fake street + city, a reserved non-real ZIP (`00000`). A real state\n * abbreviation may appear (structural only) but is never combined with a real street + name + DOB.\n *\n * @param rng - The seeded generator.\n * @returns A {@link SyntheticAddress}.\n * @example\n * ```ts\n * import { createRng, address } from \"@cosyte/synth\";\n * address(createRng(1)); // { street, city, state, zip: \"00000\" }\n * ```\n */\nexport function address(rng: Rng): SyntheticAddress {\n const number = rng.int(1, 9999);\n return {\n street: `${String(number)} ${rng.pick(SYNTHETIC_STREET_NAMES)}`,\n city: rng.pick(SYNTHETIC_CITY_NAMES),\n state: rng.pick(US_STATES),\n zip: \"00000\",\n };\n}\n\n/**\n * A **synthetic date** in HL7 `YYYYMMDD` form, drawn uniformly within an inclusive year range. Comes\n * from the seeded generator (never wall-clock), so it is reproducible and implies no real event.\n *\n * @param rng - The seeded generator.\n * @param minYear - Inclusive lower year bound (default `1930`).\n * @param maxYear - Inclusive upper year bound (default `2010`).\n * @returns An `YYYYMMDD` date string (always a valid calendar day).\n * @example\n * ```ts\n * import { createRng, dateYmd } from \"@cosyte/synth\";\n * dateYmd(createRng(1), 1970, 2000); // \"YYYYMMDD\"\n * ```\n */\nexport function dateYmd(rng: Rng, minYear = 1930, maxYear = 2010): string {\n const year = rng.int(minYear, maxYear);\n const month = rng.int(1, 12);\n const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();\n const day = rng.int(1, daysInMonth);\n return `${String(year).padStart(4, \"0\")}${String(month).padStart(2, \"0\")}${String(day).padStart(2, \"0\")}`;\n}\n\n/** US state abbreviations — structural only (see {@link address}). */\nconst US_STATES: readonly string[] = Object.freeze([\n \"AL\",\n \"AK\",\n \"AZ\",\n \"AR\",\n \"CA\",\n \"CO\",\n \"CT\",\n \"DE\",\n \"FL\",\n \"GA\",\n \"HI\",\n \"ID\",\n \"IL\",\n \"IN\",\n \"IA\",\n \"KS\",\n \"KY\",\n \"LA\",\n \"ME\",\n \"MD\",\n \"MA\",\n \"MI\",\n \"MN\",\n \"MS\",\n \"MO\",\n \"MT\",\n \"NE\",\n \"NV\",\n \"NH\",\n \"NJ\",\n \"NM\",\n \"NY\",\n \"NC\",\n \"ND\",\n \"OH\",\n \"OK\",\n \"OR\",\n \"PA\",\n \"RI\",\n \"SC\",\n \"SD\",\n \"TN\",\n \"TX\",\n \"UT\",\n \"VT\",\n \"VA\",\n \"WA\",\n \"WV\",\n \"WI\",\n \"WY\",\n]);\n","/**\n * The `safe` namespace — the single entry point for every synthetic-by-construction value provider.\n *\n * Grouped under one object so a consumer reads `safe.ssn(rng)` / `safe.phone(rng)` and it is\n * self-evident that the value is drawn from a guaranteed-non-colliding synthetic source.\n * The individual functions and the reserved-range predicates are also exported by name from the\n * package root for direct import.\n *\n * @module\n */\n\nimport {\n ssn,\n phone,\n name,\n email,\n ipv4,\n ipv6,\n uuid,\n identifier,\n address,\n dateYmd,\n npi,\n dea,\n} from \"./providers.js\";\n\nexport * from \"./providers.js\";\nexport * from \"./reserved.js\";\nexport * from \"./names-pool.js\";\n\n/**\n * The synthetic-safety provider namespace. Every function draws only from a reserved range or the\n * shipped fake-name pool — no value it returns can be real or plausibly-real PHI.\n *\n * @example\n * ```ts\n * import { createRng, safe } from \"@cosyte/synth\";\n * const rng = createRng(42);\n * safe.ssn(rng); // never-issued SSN\n * safe.phone(rng); // reserved 555-01NN number\n * ```\n */\nexport const safe = Object.freeze({\n ssn,\n phone,\n name,\n email,\n ipv4,\n ipv6,\n uuid,\n identifier,\n address,\n dateYmd,\n npi,\n dea,\n});\n","/**\n * Shared HL7 v2 building blocks for every message family `@cosyte/synth` generates — the MSH scaffold,\n * the seeded timestamp, and the patient-identity bundle + its `PID` segment. Factored out so `ADT`,\n * `ORU`, `ORM`, `SIU`, and `VXU` all mint identity from the **same** synthetic-safety providers in the\n * **same** draw order, and all emit through `@cosyte/hl7`'s conservative serializer. Nothing here draws a\n * value that is not sourced from `../safe` — the synthetic-by-construction\n * invariant holds by construction for every family.\n *\n * @module\n */\n\nimport { buildMessage, type Hl7Message, type RawField } from \"@cosyte/hl7\";\n\nimport { type Rng } from \"../rng/rng.js\";\nimport {\n safe,\n type SyntheticName,\n type SyntheticAddress,\n type SyntheticIdentifier,\n} from \"../safe/index.js\";\n\nimport { componentsField } from \"./field.js\";\n\n/**\n * A seeded HL7 `YYYYMMDDHHMMSS` timestamp (message/event time; recent-year range). Strict HL7 DTM, so\n * `@cosyte/hl7` parses it back with no `TIMESTAMP_FALLBACK_FORMAT` warning.\n *\n * @param rng - The seeded generator.\n * @returns A 14-digit `YYYYMMDDHHMMSS` timestamp string.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * // \"20230714…\"\n * ```\n */\nexport function seededTimestamp(rng: Rng): string {\n const date = safe.dateYmd(rng, 2020, 2025);\n const hh = String(rng.int(0, 23)).padStart(2, \"0\");\n const mm = String(rng.int(0, 59)).padStart(2, \"0\");\n const ss = String(rng.int(0, 59)).padStart(2, \"0\");\n return `${date}${hh}${mm}${ss}`;\n}\n\n/** The MSH scaffold shared by every generated message: the built message plus its seeded MSH values. */\nexport interface MessageScaffold {\n /** The `Hl7Message` with a complete MSH — chain `.addSegment(...)` to append the payload. */\n readonly message: Hl7Message;\n /** The seeded `YYYYMMDDHHMMSS` message timestamp (MSH-7), reused for event/observation times. */\n readonly timestamp: string;\n /** The seeded message control id (MSH-10). */\n readonly controlId: string;\n}\n\n/**\n * Build the MSH scaffold for a message of the given `MSH-9` type through `@cosyte/hl7`'s `buildMessage`,\n * so the delimiters, control id, and header layout are the parser's own conservative emit. Draws the\n * timestamp then the control id from `rng` (a fixed order — the reproducibility contract).\n *\n * @param rng - The seeded generator.\n * @param type - The `MSH-9` message type, e.g. `\"ORU^R01\"`.\n * @returns The {@link MessageScaffold}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * // mshScaffold(createRng(1), \"ORU^R01\").message.addSegment(\"PID\", […]);\n * ```\n */\nexport function mshScaffold(rng: Rng, type: string): MessageScaffold {\n const timestamp = seededTimestamp(rng);\n const controlId = `SYNTH${rng.digits(10)}`;\n const message = buildMessage({\n type,\n sendingApp: \"COSYTE-SYNTH\",\n sendingFacility: \"SYNTH-FAC\",\n receivingApp: \"RECEIVER\",\n receivingFacility: \"RECV-FAC\",\n controlId,\n timestamp,\n version: \"2.5\",\n processingId: \"P\",\n });\n return { message, timestamp, controlId };\n}\n\n/** A complete synthetic patient identity — every field drawn from `../safe`. */\nexport interface PatientIdentity {\n /** Name from the shipped fake-name pool. */\n readonly person: SyntheticName;\n /** Medical-record identifier scoped to the synthetic assigning authority. */\n readonly mrn: SyntheticIdentifier;\n /** Date of birth (`YYYYMMDD`) from the seeded generator. */\n readonly dob: string;\n /** Administrative sex. */\n readonly sex: \"M\" | \"F\";\n /** Synthetic postal address (reserved non-real ZIP). */\n readonly address: SyntheticAddress;\n /** Reserved `555-01xx` phone number. */\n readonly phone: string;\n /** Never-issued SSN as 9 digits (no dashes), for `PID-19`. */\n readonly ssnDigits: string;\n}\n\n/**\n * Mint a complete synthetic {@link PatientIdentity}. Every value comes from a synthetic-safety provider\n * — no code path here can return a real or plausibly-real identifier. The draw order is\n * fixed (name → MRN → DOB → sex → address → phone → SSN) so the same seed yields the same identity.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link PatientIdentity}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * // const id = patientIdentity(createRng(1)); // id.person, id.mrn, …\n * ```\n */\nexport function patientIdentity(rng: Rng): PatientIdentity {\n const person = safe.name(rng);\n const mrn = safe.identifier(rng, \"MR\");\n const dob = safe.dateYmd(rng, 1930, 2010);\n const sex = rng.pick([\"M\", \"F\"] as const);\n const address = safe.address(rng);\n const phone = safe.phone(rng);\n const ssnDigits = safe.ssn(rng).replace(/-/g, \"\");\n return { person, mrn, dob, sex, address, phone, ssnDigits };\n}\n\n/**\n * Lay out a fully-populated `PID` segment from a {@link PatientIdentity} as `addSegment` fields — the\n * PHI-dense segment shared by every family. Components go through {@link componentsField} so the parser\n * lays out the `^` separators (building *through* the parser).\n *\n * @param id - The synthetic identity to render.\n * @returns The `PID` field list for `Hl7Message.addSegment(\"PID\", …)`.\n * @example\n * ```ts\n * // msg.addSegment(\"PID\", pidSegment(patientIdentity(createRng(1))));\n * ```\n */\nexport function pidSegment(id: PatientIdentity): readonly (string | RawField)[] {\n return [\n \"1\", // PID-1 set id\n \"\", // PID-2 (legacy, absent)\n componentsField([id.mrn.value, \"\", \"\", id.mrn.assigningAuthority, id.mrn.typeCode]), // PID-3 CX\n \"\", // PID-4\n componentsField([id.person.family, id.person.given]), // PID-5 XPN\n \"\", // PID-6\n id.dob, // PID-7 DOB\n id.sex, // PID-8 sex\n \"\", // PID-9\n \"\", // PID-10\n componentsField([id.address.street, \"\", id.address.city, id.address.state, id.address.zip]), // PID-11 XAD\n \"\", // PID-12\n id.phone, // PID-13 phone\n \"\", // PID-14\n \"\", // PID-15\n \"\", // PID-16\n \"\", // PID-17\n \"\", // PID-18\n id.ssnDigits, // PID-19 SSN (digits)\n ];\n}\n","/**\n * Spec-clean HL7 v2 `ADT` generation, built **through `@cosyte/hl7`'s `buildMessage`** so MSH\n * delimiters, segment layout, and escaping are the parser's own conservative emit — spec-clean *by\n * construction*. Every PHI-bearing field (name, DOB, SSN, MRN,\n * address, phone) is drawn from the synthetic-safety providers (`../safe`), so no value can be real.\n *\n * `ADT^A01/A04/A08` all require the `PID` (patient) + `PV1` (visit) groups the parser's structure net\n * checks for — so a generated message round-trips through `@cosyte/hl7` with **zero warnings**.\n *\n * @module\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\n\nimport { createRng } from \"../rng/rng.js\";\n\nimport { componentsField } from \"./field.js\";\nimport { mshScaffold, patientIdentity, pidSegment } from \"./common.js\";\n\n/** The ADT trigger events this generator produces (all require the PID + PV1 groups). */\nexport type AdtTrigger = \"A01\" | \"A04\" | \"A08\";\n\n/** Options for {@link generateAdt}. */\nexport interface GenerateAdtOptions {\n /** The seed — the same seed yields a byte-identical message. Defaults to `0`. */\n readonly seed?: number;\n /** The ADT trigger event. Defaults to `\"A01\"`. */\n readonly trigger?: AdtTrigger;\n}\n\n/**\n * Generate a spec-clean `ADT` {@link Hl7Message} through `@cosyte/hl7`. Deterministic in `seed`.\n *\n * The message carries a complete MSH (seeded control id + timestamp, so the bytes are reproducible),\n * `EVN`, a fully-populated `PID` (identity from the synthetic providers), and `PV1` (the visit group),\n * so it parses back through `@cosyte/hl7` with **zero warnings** (proven by {@link ./round-trip}).\n *\n * @param options - Seed + trigger. See {@link GenerateAdtOptions}.\n * @returns A spec-clean `ADT` `Hl7Message`.\n * @example\n * ```ts\n * import { generateAdt } from \"@cosyte/synth/hl7\";\n * const msg = generateAdt({ seed: 12345, trigger: \"A01\" });\n * console.log(msg.toString());\n * ```\n */\nexport function generateAdt(options: GenerateAdtOptions = {}): Hl7Message {\n const seed = options.seed ?? 0;\n const trigger = options.trigger ?? \"A01\";\n const rng = createRng(seed);\n\n const { message, timestamp } = mshScaffold(rng, `ADT^${trigger}`);\n message.addSegment(\"EVN\", [trigger, timestamp]);\n message.addSegment(\"PID\", pidSegment(patientIdentity(rng)));\n\n const patientClass = rng.pick([\"I\", \"O\", \"E\"] as const);\n message.addSegment(\"PV1\", [\n \"1\", // PV1-1 set id\n patientClass, // PV1-2 patient class\n componentsField([\"SYNTHWARD\", String(rng.int(1, 999)).padStart(3, \"0\"), \"01\"]), // PV1-3 PL\n ]);\n\n return message;\n}\n","/**\n * A tiny, curated, **license-clean** pool of example codes used to fill coded fields in generated HL7\n * messages (`OBR`/`OBX` observations, `ORC`/`OBR` orders, `RXA` vaccines). These are **public code\n * facts** — the spec examples' own values — not copyrighted terminology tables: `@cosyte/synth` bundles\n * **no** SNOMED/CPT/LOINC/RxNorm content. The pool exists only so a generated message is *structurally*\n * realistic; a consumer who\n * needs their own codes supplies them.\n *\n * Nothing here is PHI — codes and their display text are not identifiers. The synthetic-safety\n * invariant governs identity fields (name/DOB/SSN/MRN/phone/address), which come from `../safe`.\n *\n * @module\n */\n\n/** A coded concept: an identifier code, human-readable text, and its code system (HL7 `CE`/`CWE`). */\nexport interface ExampleCode {\n /** The code value (component 1). */\n readonly code: string;\n /** The human-readable display text (component 2). */\n readonly text: string;\n /** The coding-system id (component 3), e.g. `\"LN\"` (LOINC) or `\"CVX\"`. */\n readonly system: string;\n /** Reporting units (UCUM), where the concept is a measured quantity. */\n readonly units?: string;\n}\n\n/**\n * A handful of common LOINC laboratory-observation example codes (for `OBX`). Public LOINC identifiers\n * used purely as illustrative structural fillers.\n */\nexport const EXAMPLE_LAB_OBSERVATIONS: readonly ExampleCode[] = Object.freeze([\n Object.freeze({ code: \"4548-4\", text: \"Hemoglobin A1c\", system: \"LN\", units: \"%\" }),\n Object.freeze({ code: \"718-7\", text: \"Hemoglobin\", system: \"LN\", units: \"g/dL\" }),\n Object.freeze({ code: \"2345-7\", text: \"Glucose\", system: \"LN\", units: \"mg/dL\" }),\n Object.freeze({ code: \"2951-2\", text: \"Sodium\", system: \"LN\", units: \"mmol/L\" }),\n Object.freeze({ code: \"2823-3\", text: \"Potassium\", system: \"LN\", units: \"mmol/L\" }),\n Object.freeze({ code: \"789-8\", text: \"Erythrocytes\", system: \"LN\", units: \"10*6/uL\" }),\n]);\n\n/**\n * A handful of LOINC panel/service example codes (for the `OBR`/`ORC` universal service id). Public\n * identifiers used as structural fillers.\n */\nexport const EXAMPLE_ORDER_SERVICES: readonly ExampleCode[] = Object.freeze([\n Object.freeze({ code: \"24323-8\", text: \"Comprehensive metabolic panel\", system: \"LN\" }),\n Object.freeze({ code: \"58410-2\", text: \"CBC panel\", system: \"LN\" }),\n Object.freeze({ code: \"24356-8\", text: \"Urinalysis panel\", system: \"LN\" }),\n Object.freeze({ code: \"24331-1\", text: \"Lipid panel\", system: \"LN\" }),\n]);\n\n/**\n * A handful of CDC CVX vaccine example codes (for `RXA-5`). Public CVX identifiers used as structural\n * fillers; `@cosyte/synth` bundles no vaccine terminology.\n */\nexport const EXAMPLE_VACCINES: readonly ExampleCode[] = Object.freeze([\n Object.freeze({ code: \"08\", text: \"Hep B, adolescent or pediatric\", system: \"CVX\" }),\n Object.freeze({ code: \"20\", text: \"DTaP\", system: \"CVX\" }),\n Object.freeze({ code: \"03\", text: \"MMR\", system: \"CVX\" }),\n Object.freeze({ code: \"10\", text: \"IPV\", system: \"CVX\" }),\n Object.freeze({ code: \"141\", text: \"Influenza, seasonal, injectable\", system: \"CVX\" }),\n Object.freeze({ code: \"21\", text: \"Varicella\", system: \"CVX\" }),\n]);\n","/**\n * Spec-clean HL7 v2 `ORU^R01` (unsolicited observation result) generation, built **through\n * `@cosyte/hl7`'s `buildMessage`**. The parser's structure net requires the\n * result group (`OBR`/`OBX`) for `ORU^R01`; this generator always emits both, plus a fully-populated\n * `PID`, so the message round-trips with **zero warnings**. Patient identity comes from `../safe`;\n * observation codes come from the license-clean example pool (`./example-codes`), never bundled\n * terminology. A `synth` `ORU` is *structurally* valid, not clinically coherent.\n *\n * @module\n */\n\nimport type { Hl7Message, RawField } from \"@cosyte/hl7\";\n\nimport { createRng, type Rng } from \"../rng/rng.js\";\n\nimport { componentsField } from \"./field.js\";\nimport { mshScaffold, patientIdentity, pidSegment, seededTimestamp } from \"./common.js\";\nimport { EXAMPLE_LAB_OBSERVATIONS, EXAMPLE_ORDER_SERVICES } from \"./example-codes.js\";\n\n/** Options for {@link generateOru}. */\nexport interface GenerateOruOptions {\n /** The seed — the same seed yields a byte-identical message. Defaults to `0`. */\n readonly seed?: number;\n}\n\n/** Render one `OBX` result segment (set id `n`) for a numeric example observation. */\nfunction obxSegment(rng: Rng, setId: number): readonly (string | RawField)[] {\n const obs = rng.pick(EXAMPLE_LAB_OBSERVATIONS);\n const value = `${String(rng.int(1, 300))}.${String(rng.int(0, 9))}`;\n const observedAt = seededTimestamp(rng);\n return [\n String(setId), // OBX-1 set id\n \"NM\", // OBX-2 value type (numeric)\n componentsField([obs.code, obs.text, obs.system]), // OBX-3 observation identifier (CE)\n \"\", // OBX-4 observation sub-id\n value, // OBX-5 observation value\n obs.units ?? \"\", // OBX-6 units\n \"\", // OBX-7 reference range\n \"N\", // OBX-8 abnormal flags (normal)\n \"\", // OBX-9\n \"\", // OBX-10\n \"F\", // OBX-11 observation result status (final)\n \"\", // OBX-12\n \"\", // OBX-13\n observedAt, // OBX-14 date/time of the observation\n ];\n}\n\n/**\n * Generate a spec-clean `ORU^R01` {@link Hl7Message} through `@cosyte/hl7`. Deterministic in `seed`.\n *\n * Layout: MSH, `PID` (synthetic identity), `OBR` (order/observation request), and 1–3 `OBX` result\n * rows. The `OBR`/`OBX` result group satisfies the parser's `ORU^R01` structure net, so the message\n * re-parses with **zero warnings** (proven by {@link ./round-trip}).\n *\n * @param options - Seed. See {@link GenerateOruOptions}.\n * @returns A spec-clean `ORU^R01` `Hl7Message`.\n * @example\n * ```ts\n * import { generateOru } from \"@cosyte/synth/hl7\";\n * const msg = generateOru({ seed: 12345 });\n * console.log(msg.toString());\n * ```\n */\nexport function generateOru(options: GenerateOruOptions = {}): Hl7Message {\n const seed = options.seed ?? 0;\n const rng = createRng(seed);\n\n const { message } = mshScaffold(rng, \"ORU^R01\");\n message.addSegment(\"PID\", pidSegment(patientIdentity(rng)));\n\n const service = rng.pick(EXAMPLE_ORDER_SERVICES);\n const placer = rng.digits(8);\n const filler = rng.digits(8);\n message.addSegment(\"OBR\", [\n \"1\", // OBR-1 set id\n placer, // OBR-2 placer order number\n filler, // OBR-3 filler order number\n componentsField([service.code, service.text, service.system]), // OBR-4 universal service id (CE)\n \"\", // OBR-5\n \"\", // OBR-6\n seededTimestamp(rng), // OBR-7 observation date/time\n ]);\n\n const obxCount = rng.int(1, 3);\n for (let i = 1; i <= obxCount; i += 1) {\n message.addSegment(\"OBX\", obxSegment(rng, i));\n }\n\n return message;\n}\n","/**\n * Spec-clean HL7 v2 `ORM^O01` (general order) generation, built **through `@cosyte/hl7`'s\n * `buildMessage`**. The parser's structure net requires the common-order segment\n * (`ORC`) for `ORM^O01`; this generator emits `ORC` + a matching `OBR`, plus a fully-populated `PID`,\n * so the message round-trips with **zero warnings**. Identity comes from `../safe`; the ordered service\n * comes from the license-clean example pool, never bundled terminology.\n *\n * @module\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\n\nimport { createRng } from \"../rng/rng.js\";\n\nimport { componentsField } from \"./field.js\";\nimport { mshScaffold, patientIdentity, pidSegment, seededTimestamp } from \"./common.js\";\nimport { EXAMPLE_ORDER_SERVICES } from \"./example-codes.js\";\n\n/** Options for {@link generateOrm}. */\nexport interface GenerateOrmOptions {\n /** The seed — the same seed yields a byte-identical message. Defaults to `0`. */\n readonly seed?: number;\n}\n\n/**\n * Generate a spec-clean `ORM^O01` {@link Hl7Message} through `@cosyte/hl7`. Deterministic in `seed`.\n *\n * Layout: MSH, `PID` (synthetic identity), `ORC` (common order — control `NW`, new order), and a\n * matching `OBR` (order detail). The `ORC` satisfies the parser's `ORM^O01` structure net, so the\n * message re-parses with **zero warnings** (proven by {@link ./round-trip}).\n *\n * @param options - Seed. See {@link GenerateOrmOptions}.\n * @returns A spec-clean `ORM^O01` `Hl7Message`.\n * @example\n * ```ts\n * import { generateOrm } from \"@cosyte/synth/hl7\";\n * const msg = generateOrm({ seed: 12345 });\n * console.log(msg.toString());\n * ```\n */\nexport function generateOrm(options: GenerateOrmOptions = {}): Hl7Message {\n const seed = options.seed ?? 0;\n const rng = createRng(seed);\n\n const { message } = mshScaffold(rng, \"ORM^O01\");\n message.addSegment(\"PID\", pidSegment(patientIdentity(rng)));\n\n const service = rng.pick(EXAMPLE_ORDER_SERVICES);\n const placer = rng.digits(8);\n const filler = rng.digits(8);\n const orderedAt = seededTimestamp(rng);\n\n message.addSegment(\"ORC\", [\n \"NW\", // ORC-1 order control (new order)\n placer, // ORC-2 placer order number\n filler, // ORC-3 filler order number\n \"\", // ORC-4 placer group number\n \"\", // ORC-5 order status\n \"\", // ORC-6\n \"\", // ORC-7 quantity/timing\n \"\", // ORC-8\n orderedAt, // ORC-9 date/time of transaction\n ]);\n\n message.addSegment(\"OBR\", [\n \"1\", // OBR-1 set id\n placer, // OBR-2 placer order number (matches ORC)\n filler, // OBR-3 filler order number (matches ORC)\n componentsField([service.code, service.text, service.system]), // OBR-4 universal service id (CE)\n ]);\n\n return message;\n}\n","/**\n * Spec-clean HL7 v2 `SIU^S12` (notification of new appointment booking) generation, built **through\n * `@cosyte/hl7`'s `buildMessage`**. The parser's structure net requires the schedule\n * activity segment (`SCH`) for `SIU^S12`; this generator emits `SCH` + `PID` + a resource group\n * (`RGS`/`AIL`), so the message round-trips with **zero warnings**. Identity comes from `../safe`.\n *\n * @module\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\n\nimport { createRng } from \"../rng/rng.js\";\n\nimport { componentsField } from \"./field.js\";\nimport { mshScaffold, patientIdentity, pidSegment, seededTimestamp } from \"./common.js\";\n\n/** Options for {@link generateSiu}. */\nexport interface GenerateSiuOptions {\n /** The seed — the same seed yields a byte-identical message. Defaults to `0`. */\n readonly seed?: number;\n}\n\n/**\n * Generate a spec-clean `SIU^S12` {@link Hl7Message} through `@cosyte/hl7`. Deterministic in `seed`.\n *\n * Layout: MSH, `SCH` (schedule activity — the required group), `PID` (synthetic identity), `RGS`\n * (resource group), `AIL` (location resource). The `SCH` satisfies the parser's `SIU^S12` structure\n * net, so the message re-parses with **zero warnings** (proven by {@link ./round-trip}).\n *\n * @param options - Seed. See {@link GenerateSiuOptions}.\n * @returns A spec-clean `SIU^S12` `Hl7Message`.\n * @example\n * ```ts\n * import { generateSiu } from \"@cosyte/synth/hl7\";\n * const msg = generateSiu({ seed: 12345 });\n * console.log(msg.toString());\n * ```\n */\nexport function generateSiu(options: GenerateSiuOptions = {}): Hl7Message {\n const seed = options.seed ?? 0;\n const rng = createRng(seed);\n\n const { message } = mshScaffold(rng, \"SIU^S12\");\n\n const placerAppt = rng.digits(8);\n const fillerAppt = rng.digits(8);\n const startAt = seededTimestamp(rng);\n const durationMinutes = String(rng.int(15, 90));\n\n message.addSegment(\"SCH\", [\n placerAppt, // SCH-1 placer appointment id\n fillerAppt, // SCH-2 filler appointment id\n \"\", // SCH-3 occurrence number\n \"\", // SCH-4 placer group number\n \"\", // SCH-5 schedule id\n \"\", // SCH-6 event reason\n componentsField([\"ROUTINE\", \"Routine appointment\", \"L\"]), // SCH-7 appointment reason (CE)\n \"\", // SCH-8 appointment type\n durationMinutes, // SCH-9 appointment duration\n componentsField([\"min\", \"minutes\", \"UCUM\"]), // SCH-10 appointment duration units (CE)\n componentsField([\"1\", \"\", startAt, \"\", \"\", \"\", durationMinutes]), // SCH-11 appointment timing quantity (TQ)\n ]);\n\n message.addSegment(\"PID\", pidSegment(patientIdentity(rng)));\n\n message.addSegment(\"RGS\", [\n \"1\", // RGS-1 set id\n \"A\", // RGS-2 segment action code (add)\n ]);\n\n message.addSegment(\"AIL\", [\n \"1\", // AIL-1 set id\n \"A\", // AIL-2 segment action code\n componentsField([\"SYNTHCLINIC\", \"Synthetic Clinic\", \"COSYTE-SYNTH\"]), // AIL-3 location resource id\n ]);\n\n return message;\n}\n","/**\n * Spec-clean HL7 v2 `VXU^V04` (unsolicited vaccination record update) generation, built **through\n * `@cosyte/hl7`'s `buildMessage`**. The parser's structure net requires the patient\n * group (`PID`) for `VXU^V04` (per the CDC IG, `RXA` lives in the optional order group); this generator\n * emits `PID` + `ORC` + `RXA` + `RXR`, so the message round-trips with **zero warnings**. Identity comes\n * from `../safe`; the vaccine code comes from the license-clean example pool, never bundled terminology.\n *\n * @module\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\n\nimport { createRng } from \"../rng/rng.js\";\n\nimport { componentsField } from \"./field.js\";\nimport { mshScaffold, patientIdentity, pidSegment, seededTimestamp } from \"./common.js\";\nimport { EXAMPLE_VACCINES } from \"./example-codes.js\";\n\n/** Options for {@link generateVxu}. */\nexport interface GenerateVxuOptions {\n /** The seed — the same seed yields a byte-identical message. Defaults to `0`. */\n readonly seed?: number;\n}\n\n/**\n * Generate a spec-clean `VXU^V04` {@link Hl7Message} through `@cosyte/hl7`. Deterministic in `seed`.\n *\n * Layout: MSH, `PID` (synthetic identity — the required group), `ORC` (common order), `RXA` (vaccine\n * administration, CVX example code), `RXR` (route). The `PID` satisfies the parser's `VXU^V04`\n * structure net, so the message re-parses with **zero warnings** (proven by {@link ./round-trip}).\n *\n * @param options - Seed. See {@link GenerateVxuOptions}.\n * @returns A spec-clean `VXU^V04` `Hl7Message`.\n * @example\n * ```ts\n * import { generateVxu } from \"@cosyte/synth/hl7\";\n * const msg = generateVxu({ seed: 12345 });\n * console.log(msg.toString());\n * ```\n */\nexport function generateVxu(options: GenerateVxuOptions = {}): Hl7Message {\n const seed = options.seed ?? 0;\n const rng = createRng(seed);\n\n const { message } = mshScaffold(rng, \"VXU^V04\");\n message.addSegment(\"PID\", pidSegment(patientIdentity(rng)));\n\n const placer = rng.digits(8);\n const filler = rng.digits(8);\n message.addSegment(\"ORC\", [\n \"RE\", // ORC-1 order control (observation to follow / record)\n placer, // ORC-2 placer order number\n filler, // ORC-3 filler order number\n ]);\n\n const vaccine = rng.pick(EXAMPLE_VACCINES);\n const administeredAt = seededTimestamp(rng);\n const doseAmount = String(rng.int(1, 5) / 10); // 0.1–0.5 mL, structural only\n\n message.addSegment(\"RXA\", [\n \"0\", // RXA-1 give sub-id counter\n \"1\", // RXA-2 administration sub-id counter\n administeredAt, // RXA-3 date/time start of administration\n administeredAt, // RXA-4 date/time end of administration\n componentsField([vaccine.code, vaccine.text, vaccine.system]), // RXA-5 administered code (CE)\n doseAmount, // RXA-6 administered amount\n componentsField([\"mL\", \"milliliters\", \"UCUM\"]), // RXA-7 administered units (CE)\n \"\", // RXA-8\n \"\", // RXA-9 administration notes\n \"\", // RXA-10\n \"\", // RXA-11\n \"\", // RXA-12\n \"\", // RXA-13\n \"\", // RXA-14\n \"\", // RXA-15 substance lot number\n \"\", // RXA-16\n \"\", // RXA-17\n \"\", // RXA-18\n \"\", // RXA-19\n \"CP\", // RXA-20 completion status (complete)\n ]);\n\n message.addSegment(\"RXR\", [\n componentsField([\"IM\", \"Intramuscular\", \"HL70162\"]), // RXR-1 route (CE)\n componentsField([\"LD\", \"Left Deltoid\", \"HL70163\"]), // RXR-2 administration site (CE)\n ]);\n\n return message;\n}\n","/**\n * `@cosyte/synth/hl7` — the HL7 v2 generation surface, exposed as its own subpath so importing the\n * package root does **not** pull `@cosyte/hl7`. This is the **lazy, per-format** boundary: a consumer\n * who only needs HL7 fixtures imports `@cosyte/synth/hl7`; one who needs only the core primitives\n * never loads a parser.\n * `@cosyte/hl7` is an **optional peer dependency** — present only for this subpath.\n *\n * The HL7 v2 message set is complete: `ADT` (A01/A04/A08), `ORU^R01`, `ORM^O01`, `SIU^S12`, and\n * `VXU^V04` — each built through `@cosyte/hl7`'s `buildMessage` and round-tripping with zero warnings.\n *\n * @module\n */\n\nimport type { Hl7Message } from \"@cosyte/hl7\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { makeCorpus, type Corpus } from \"../corpus.js\";\n\nimport { generateAdt, type AdtTrigger } from \"./adt.js\";\nimport { generateOru } from \"./oru.js\";\nimport { generateOrm } from \"./orm.js\";\nimport { generateSiu } from \"./siu.js\";\nimport { generateVxu } from \"./vxu.js\";\nimport { roundTrip } from \"./round-trip.js\";\n\nexport { generateAdt, type AdtTrigger, type GenerateAdtOptions } from \"./adt.js\";\nexport { generateOru, type GenerateOruOptions } from \"./oru.js\";\nexport { generateOrm, type GenerateOrmOptions } from \"./orm.js\";\nexport { generateSiu, type GenerateSiuOptions } from \"./siu.js\";\nexport { generateVxu, type GenerateVxuOptions } from \"./vxu.js\";\nexport { roundTrip, type RoundTripResult } from \"./round-trip.js\";\nexport { componentsField } from \"./field.js\";\nexport {\n seededTimestamp,\n mshScaffold,\n patientIdentity,\n pidSegment,\n type MessageScaffold,\n type PatientIdentity,\n} from \"./common.js\";\nexport {\n type ExampleCode,\n EXAMPLE_LAB_OBSERVATIONS,\n EXAMPLE_ORDER_SERVICES,\n EXAMPLE_VACCINES,\n} from \"./example-codes.js\";\nexport {\n generateHl7Quirk,\n hl7QuirkRoundTrip,\n hl7QuirkCorpus,\n hl7QuirkProfile,\n HL7_QUIRKS,\n type Hl7QuirkName,\n type Hl7QuirkKind,\n type GenerateHl7QuirkOptions,\n type Hl7QuirkCorpusOptions,\n} from \"./quirk.js\";\n\n/**\n * Every HL7 v2 message kind this subpath generates — the `MSH-9` label used as the corpus `kind`. `ADT`\n * carries its trigger; the other families have a single generated trigger each.\n */\nexport type Hl7MessageKind =\n | \"ADT^A01\"\n | \"ADT^A04\"\n | \"ADT^A08\"\n | \"ORU^R01\"\n | \"ORM^O01\"\n | \"SIU^S12\"\n | \"VXU^V04\";\n\n/** The default message mix for {@link hl7Corpus} — one of every family. */\nconst DEFAULT_MIX: readonly Hl7MessageKind[] = Object.freeze([\n \"ADT^A01\",\n \"ADT^A04\",\n \"ADT^A08\",\n \"ORU^R01\",\n \"ORM^O01\",\n \"SIU^S12\",\n \"VXU^V04\",\n]);\n\n/**\n * Generate one message of the given {@link Hl7MessageKind} from a seed, dispatching to the right\n * family generator. Every kind builds through `@cosyte/hl7` and is deterministic in `seed`.\n *\n * @param kind - The message kind to generate.\n * @param seed - The seed.\n * @returns The generated `Hl7Message`.\n * @example\n * ```ts\n * import { generateHl7 } from \"@cosyte/synth/hl7\";\n * generateHl7(\"ORU^R01\", 42).toString();\n * ```\n */\nexport function generateHl7(kind: Hl7MessageKind, seed: number): Hl7Message {\n switch (kind) {\n case \"ADT^A01\":\n return generateAdt({ seed, trigger: \"A01\" });\n case \"ADT^A04\":\n return generateAdt({ seed, trigger: \"A04\" });\n case \"ADT^A08\":\n return generateAdt({ seed, trigger: \"A08\" });\n case \"ORU^R01\":\n return generateOru({ seed });\n case \"ORM^O01\":\n return generateOrm({ seed });\n case \"SIU^S12\":\n return generateSiu({ seed });\n case \"VXU^V04\":\n return generateVxu({ seed });\n }\n}\n\n/** Options for {@link hl7Corpus}. */\nexport interface Hl7CorpusOptions {\n /** The seed for the whole corpus (deterministic). */\n readonly seed: number;\n /** How many messages to generate. Defaults to `1`. */\n readonly count?: number;\n /**\n * The message kinds to cycle through. Defaults to one of every family\n * (`ADT^A01/A04/A08`, `ORU^R01`, `ORM^O01`, `SIU^S12`, `VXU^V04`).\n */\n readonly mix?: readonly Hl7MessageKind[];\n /**\n * ADT-only convenience: the triggers to cycle through, kept for back-compat. When\n * supplied it takes precedence over `mix` and restricts the corpus to `ADT` messages.\n */\n readonly triggers?: readonly AdtTrigger[];\n}\n\n/**\n * Build a reproducible {@link Corpus} of spec-clean HL7 messages across the families. Each\n * message is generated from a distinct sub-seed derived from the corpus seed (so the set is\n * deterministic) and round-tripped through `@cosyte/hl7`; the per-artifact `warnings` record the\n * parser's verdict (empty ⇒ spec-clean).\n *\n * @param options - Seed, count, and the message mix. See {@link Hl7CorpusOptions}.\n * @returns A deep-frozen {@link Corpus}.\n * @example\n * ```ts\n * import { hl7Corpus } from \"@cosyte/synth/hl7\";\n * const corpus = hl7Corpus({ seed: 42, count: 7 });\n * corpus.artifacts.every((a) => a.warnings.length === 0); // true — spec-clean\n * ```\n */\nexport function hl7Corpus(options: Hl7CorpusOptions): Corpus {\n const { seed, count = 1 } = options;\n const kinds: readonly Hl7MessageKind[] =\n options.triggers !== undefined\n ? options.triggers.map((t): Hl7MessageKind => `ADT^${t}`)\n : (options.mix ?? DEFAULT_MIX);\n // A seed stream derives one deterministic per-message seed from the corpus seed.\n const seedStream = createRng(seed);\n const artifacts = Array.from({ length: count }, (_unused, i) => {\n const kind = kinds[i % kinds.length] ?? \"ADT^A01\";\n const messageSeed = seedStream.nextUint32();\n const rt = roundTrip(generateHl7(kind, messageSeed));\n return {\n format: \"hl7v2\" as const,\n kind,\n content: rt.content,\n warnings: rt.warnings,\n };\n });\n return makeCorpus(seed, artifacts);\n}\n","/**\n * US Core + base-FHIR **canonical URLs and code-system identifiers** — the facts `@cosyte/synth` needs\n * to emit US-Core-conformant resources, and nothing more.\n *\n * **Content-free, exactly like `@cosyte/fhir`.** These are *identifiers* — canonical URLs and code\n * `system` URIs — not the copyrighted terminology tables or the profile `StructureDefinition` content\n * they name. `@cosyte/synth` bundles **no** US Core IG: a consumer who wants to *validate* generated\n * output against US Core supplies the `StructureDefinition`s themselves (BYO), exactly as\n * `@cosyte/fhir.validateResource({ profiles })` requires. What is encoded here is only which canonical\n * URL a resource's `meta.profile` claims and which `system` a coding carries — public facts.\n *\n * The URLs target **US Core 6.1.0** (the USCDI v3 / ONC HTI-1 §170.315(g)(10) anchor, FHIR R4 4.0.1),\n * grounded firsthand against the published IG (`hl7.org/fhir/us/core/STU6.1`) — the same version the\n * test corpus validates against.\n *\n * @module\n */\n\n/** The canonical `meta.profile` URLs for the US Core 6.1.0 profiles `@cosyte/synth` generates. */\nexport const US_CORE_PROFILE = Object.freeze({\n /** US Core Patient. */\n PATIENT: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient\",\n /** US Core Condition (Problems and Health Concerns). */\n CONDITION:\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-condition-problems-health-concerns\",\n /** US Core Laboratory Result Observation. */\n OBSERVATION_LAB: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-observation-lab\",\n /** US Core Vital Signs (derived from the base FHIR vital-signs profile). */\n VITAL_SIGNS: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-vital-signs\",\n /** US Core MedicationRequest. */\n MEDICATION_REQUEST: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-medicationrequest\",\n /** US Core Encounter. */\n ENCOUNTER: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-encounter\",\n /** US Core DiagnosticReport Profile for Laboratory Results Reporting. */\n DIAGNOSTIC_REPORT_LAB:\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-diagnosticreport-lab\",\n /** US Core Immunization. */\n IMMUNIZATION: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-immunization\",\n /** US Core AllergyIntolerance. */\n ALLERGY_INTOLERANCE: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-allergyintolerance\",\n /** US Core Procedure. */\n PROCEDURE: \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-procedure\",\n} as const);\n\n/** The US Core `us-core-race` extension URL (a Patient must-support extension). */\nexport const US_CORE_RACE_EXTENSION =\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-race\";\n/** The US Core `us-core-ethnicity` extension URL (a Patient must-support extension). */\nexport const US_CORE_ETHNICITY_EXTENSION =\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity\";\n/** The US Core `us-core-birthsex` extension URL (a Patient must-support extension). */\nexport const US_CORE_BIRTHSEX_EXTENSION =\n \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex\";\n\n/**\n * The code-system `system` URIs the generators reference. Public identity URIs (HL7-published),\n * never the code-system *content* — no SNOMED/LOINC/RxNorm table is bundled.\n */\nexport const SYSTEM = Object.freeze({\n /** FHIR `administrative-gender` (`Patient.gender`). */\n ADMINISTRATIVE_GENDER: \"http://hl7.org/fhir/administrative-gender\",\n /** HL7 Terminology `observation-category`. */\n OBSERVATION_CATEGORY: \"http://terminology.hl7.org/CodeSystem/observation-category\",\n /** HL7 Terminology `condition-category`. */\n CONDITION_CATEGORY: \"http://terminology.hl7.org/CodeSystem/condition-category\",\n /** HL7 Terminology `condition-clinical`. */\n CONDITION_CLINICAL: \"http://terminology.hl7.org/CodeSystem/condition-clinical\",\n /** HL7 Terminology `condition-ver-status`. */\n CONDITION_VER_STATUS: \"http://terminology.hl7.org/CodeSystem/condition-ver-status\",\n /** HL7 v2 `0203` identifier-type (`Identifier.type.coding.code` = `MR`). */\n IDENTIFIER_TYPE: \"http://terminology.hl7.org/CodeSystem/v2-0203\",\n /** OMB race & ethnicity category system (US Core race/ethnicity `ombCategory`). */\n OMB_RACE_ETHNICITY: \"urn:oid:2.16.840.1.113883.6.238\",\n /** LOINC — `Observation.code` (lab + vital-signs). */\n LOINC: \"http://loinc.org\",\n /** SNOMED CT — `Condition.code`. */\n SNOMED: \"http://snomed.info/sct\",\n /** RxNorm — `MedicationRequest.medicationCodeableConcept` + an allergen substance. */\n RXNORM: \"http://www.nlm.nih.gov/research/umls/rxnorm\",\n /** UCUM — `Quantity.system` for units of measure. */\n UCUM: \"http://unitsofmeasure.org\",\n /** CVX (CDC vaccine administered) — `Immunization.vaccineCode`. */\n CVX: \"http://hl7.org/fhir/sid/cvx\",\n /** HL7 v3 `ActCode` — `Encounter.class`. */\n V3_ACT_CODE: \"http://terminology.hl7.org/CodeSystem/v3-ActCode\",\n /** HL7 v2 `0074` diagnostic-service-section — `DiagnosticReport.category` (`LAB`). */\n DIAGNOSTIC_SERVICE_SECTION: \"http://terminology.hl7.org/CodeSystem/v2-0074\",\n /** HL7 Terminology `allergyintolerance-clinical` — `AllergyIntolerance.clinicalStatus`. */\n ALLERGY_CLINICAL: \"http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical\",\n /** HL7 Terminology `allergyintolerance-verification` — `AllergyIntolerance.verificationStatus`. */\n ALLERGY_VERIFICATION: \"http://terminology.hl7.org/CodeSystem/allergyintolerance-verification\",\n} as const);\n\n/** A US Core profile canonical URL. */\nexport type UsCoreProfileUrl = (typeof US_CORE_PROFILE)[keyof typeof US_CORE_PROFILE];\n","/**\n * Shared FHIR model-construction helpers — the small vocabulary every resource generator uses\n * to build **through `@cosyte/fhir`'s own model constructors** (`complex` / `list` / `primitive` /\n * `decimal`). A generated resource is a `FhirComplex` tree assembled here and serialized by\n * `@cosyte/fhir`'s conservative writer, so it is **spec-clean by construction** — the same mechanism\n * that makes the parser's emit side spec-clean. Nothing here hand-writes JSON\n * bytes.\n *\n * Identity fields (`name`, `identifier`, `birthDate`, `telecom`, `address`) are minted from the\n * synthetic-safety providers in `../safe`, so no value a resource carries can be real or plausibly-real\n * PHI. The `fhirPatientIdentity` bundle draws them in a **fixed order** for the\n * reproducibility contract.\n *\n * @module\n */\n\nimport { complex, decimal, list, primitive } from \"@cosyte/fhir\";\nimport type { FhirComplex, FhirNode } from \"@cosyte/fhir\";\n\nimport type { Rng } from \"../rng/rng.js\";\nimport {\n safe,\n type SyntheticName,\n type SyntheticAddress,\n type SyntheticIdentifier,\n} from \"../safe/index.js\";\n\nimport { SYSTEM } from \"./us-core.js\";\n\n/** A named FHIR property (`{ name, value }`) — the shape `complex` consumes. */\nexport type Prop = { readonly name: string; readonly value: FhirNode };\n\n/**\n * Build a named FHIR property.\n *\n * @param name - The property name.\n * @param value - The property's node value.\n * @returns A {@link Prop}.\n * @example\n * ```ts\n * import { prop, str } from \"@cosyte/synth/fhir\";\n * prop(\"gender\", str(\"female\"));\n * ```\n */\nexport function prop(name: string, value: FhirNode): Prop {\n return { name, value };\n}\n\n/**\n * A `string`/`code`/`uri`/`date` primitive leaf.\n *\n * @param value - The lexical string value.\n * @returns A primitive `FhirNode`.\n * @example\n * ```ts\n * import { str } from \"@cosyte/synth/fhir\";\n * str(\"final\");\n * ```\n */\nexport function str(value: string): FhirNode {\n return primitive(value);\n}\n\n/**\n * A `decimal` primitive leaf, precision-preserving via `@cosyte/fhir`'s string-backed `FhirDecimal`.\n *\n * @param raw - The exact decimal lexical form (never routed through a JS `number`).\n * @returns A primitive `FhirNode`.\n * @example\n * ```ts\n * import { dec } from \"@cosyte/synth/fhir\";\n * dec(\"6.3\");\n * ```\n */\nexport function dec(raw: string): FhirNode {\n return primitive(decimal(raw));\n}\n\n/**\n * A `boolean` primitive leaf.\n *\n * @param value - The boolean value.\n * @returns A primitive `FhirNode`.\n * @example\n * ```ts\n * import { bool } from \"@cosyte/synth/fhir\";\n * bool(true);\n * ```\n */\nexport function bool(value: boolean): FhirNode {\n return primitive(value);\n}\n\n/**\n * A single `Coding` element (`system` + `code` + `display`).\n *\n * @param concept - The coding's `system`, `code`, and `display`.\n * @returns A `Coding` `FhirComplex`.\n * @example\n * ```ts\n * import { coding } from \"@cosyte/synth/fhir\";\n * coding({ system: \"http://loinc.org\", code: \"2345-7\", display: \"Glucose\" });\n * ```\n */\nexport function coding(concept: { system: string; code: string; display: string }): FhirComplex {\n return complex([\n prop(\"system\", str(concept.system)),\n prop(\"code\", str(concept.code)),\n prop(\"display\", str(concept.display)),\n ]);\n}\n\n/**\n * A `CodeableConcept` wrapping a single `Coding`.\n *\n * @param concept - The coding's `system`, `code`, and `display`.\n * @returns A `CodeableConcept` `FhirComplex`.\n * @example\n * ```ts\n * import { codeableConcept } from \"@cosyte/synth/fhir\";\n * codeableConcept({ system: \"http://snomed.info/sct\", code: \"59621000\", display: \"Essential hypertension\" });\n * ```\n */\nexport function codeableConcept(concept: {\n system: string;\n code: string;\n display: string;\n}): FhirComplex {\n return complex([prop(\"coding\", list([coding(concept)]))]);\n}\n\n/**\n * A literal `Reference` element (`{ reference: \"<Type>/<id>\" }` or a `urn:uuid:` fullUrl).\n *\n * @param ref - The reference string.\n * @returns A `Reference` `FhirComplex`.\n * @example\n * ```ts\n * import { reference } from \"@cosyte/synth/fhir\";\n * reference(\"Patient/syn-patient-1\");\n * ```\n */\nexport function reference(ref: string): FhirComplex {\n return complex([prop(\"reference\", str(ref))]);\n}\n\n/**\n * A generated `Narrative` (`text`) with `status: \"generated\"` and an XHTML `div` carrying only\n * synthetic text — satisfies the base `dom-6` best-practice constraint so a generated resource is\n * robust as well as valid. The `div` is XHTML-namespaced and carries no markup beyond a paragraph, so\n * it round-trips byte-for-byte through `@cosyte/fhir`'s codec.\n *\n * @param text - The plain synthetic summary text (no PHI — it is composed from synthetic values).\n * @returns A `Narrative` `FhirComplex`.\n * @example\n * ```ts\n * import { narrative } from \"@cosyte/synth/fhir\";\n * narrative(\"Synthetic patient summary.\");\n * ```\n */\nexport function narrative(text: string): FhirComplex {\n const escaped = text.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n return complex([\n prop(\"status\", str(\"generated\")),\n prop(\"div\", str(`<div xmlns=\"http://www.w3.org/1999/xhtml\"><p>${escaped}</p></div>`)),\n ]);\n}\n\n/**\n * A `meta.profile` element pinning the resource to one or more canonical profile URLs (US Core\n * conformance is claimed via `meta.profile`). No version is pinned, so validating against any supplied\n * version of the named profile never raises a version-mismatch.\n *\n * @param profiles - The canonical profile URLs to claim.\n * @returns A `meta` `FhirComplex`.\n * @example\n * ```ts\n * import { meta, US_CORE_PROFILE } from \"@cosyte/synth/fhir\";\n * meta([US_CORE_PROFILE.PATIENT]);\n * ```\n */\nexport function meta(profiles: readonly string[]): FhirComplex {\n return complex([prop(\"profile\", list(profiles.map((p) => str(p))))]);\n}\n\n/** A synthetic FHIR patient identity — every field drawn from `../safe`. */\nexport interface FhirPatientIdentity {\n /** A synthetic resource `id` (a seeded UUID) — never a real record key. */\n readonly id: string;\n /** Name from the shipped fake-name pool. */\n readonly person: SyntheticName;\n /** Medical-record identifier scoped to the synthetic assigning authority. */\n readonly mrn: SyntheticIdentifier;\n /** Date of birth as a FHIR `date` (`YYYY-MM-DD`) from the seeded generator. */\n readonly birthDate: string;\n /** FHIR administrative-gender code. */\n readonly gender: \"male\" | \"female\";\n /** Synthetic postal address (reserved non-real ZIP). */\n readonly address: SyntheticAddress;\n /** Reserved `555-01xx` phone number. */\n readonly phone: string;\n /** Synthetic email at a reserved (`example.*`) domain. */\n readonly email: string;\n}\n\n/**\n * Reformat a `YYYYMMDD` synthetic date (from `safe.dateYmd`) as a FHIR `date` (`YYYY-MM-DD`).\n *\n * @param ymd - The `YYYYMMDD` date string.\n * @returns The `YYYY-MM-DD` FHIR date string.\n * @example\n * ```ts\n * import { toFhirDate } from \"@cosyte/synth/fhir\";\n * toFhirDate(\"19700131\"); // \"1970-01-31\"\n * ```\n */\nexport function toFhirDate(ymd: string): string {\n return `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`;\n}\n\n/**\n * Mint a complete synthetic {@link FhirPatientIdentity}. Every value comes from a synthetic-safety\n * provider — no code path here can return a real or plausibly-real identifier. The draw\n * order is fixed (id → name → MRN → DOB → gender → address → phone → email) so the same seed yields the\n * same identity.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link FhirPatientIdentity}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * // const id = fhirPatientIdentity(createRng(1)); // id.person, id.mrn, …\n * ```\n */\nexport function fhirPatientIdentity(rng: Rng): FhirPatientIdentity {\n const id = safe.uuid(rng);\n const person = safe.name(rng);\n const mrn = safe.identifier(rng, \"MR\");\n const birthDate = toFhirDate(safe.dateYmd(rng, 1930, 2010));\n const gender = rng.pick([\"male\", \"female\"] as const);\n const address = safe.address(rng);\n const phone = safe.phone(rng);\n const email = safe.email(rng, person);\n return { id, person, mrn, birthDate, gender, address, phone, email };\n}\n\n/**\n * The US Core Patient `identifier` element for a synthetic MRN — `type` (`MR`), the synthetic\n * assigning-authority OID as `system`, and the synthetic value. Satisfies US Core Patient's required\n * `identifier.system` + `identifier.value`.\n *\n * @param mrn - The synthetic identifier from `safe.identifier`.\n * @returns An `Identifier` `FhirComplex`.\n * @example\n * ```ts\n * import { createRng, safe } from \"@cosyte/synth\";\n * import { mrnIdentifier } from \"@cosyte/synth/fhir\";\n * mrnIdentifier(safe.identifier(createRng(1), \"MR\"));\n * ```\n */\nexport function mrnIdentifier(mrn: SyntheticIdentifier): FhirComplex {\n return complex([\n prop(\n \"type\",\n complex([\n prop(\n \"coding\",\n list([\n coding({\n system: SYSTEM.IDENTIFIER_TYPE,\n code: \"MR\",\n display: \"Medical Record Number\",\n }),\n ]),\n ),\n ]),\n ),\n prop(\"system\", str(`urn:oid:${mrn.assigningAuthorityOid}`)),\n prop(\"value\", str(mrn.value)),\n ]);\n}\n","/**\n * A tiny, curated, **license-clean** pool of example codes for filling coded fields in generated FHIR\n * resources (`Observation.code`, `Condition.code`, `MedicationRequest.medication[x]`, and the OMB\n * race/ethnicity categories). These are **public code facts** — codes drawn from the published FHIR R4\n * and US Core specification examples — not copyrighted terminology tables: `@cosyte/synth` bundles\n * **no** SNOMED/LOINC/RxNorm content. The pool exists only so a\n * generated resource is *structurally* realistic; a consumer who needs their own codes supplies them.\n *\n * Nothing here is PHI — codes and their display text are not patient identifiers. The synthetic-safety\n * invariant governs identity fields (name/DOB/identifier/telecom/address), which come from `../safe`.\n *\n * @module\n */\n\n/** A coded concept: a `system` URI, a `code`, and its human-readable `display`. */\nexport interface CodeConcept {\n /** The code-system URI (`Coding.system`). */\n readonly system: string;\n /** The code value (`Coding.code`). */\n readonly code: string;\n /** The human-readable display text (`Coding.display`). */\n readonly display: string;\n}\n\n/**\n * A quantitative observation concept: a LOINC code plus the UCUM unit and a plausible synthetic value\n * range the seeded generator draws within. The range implies **no** real measurement — it only keeps a\n * generated result inside a structurally-sane band.\n */\nexport interface QuantConcept extends CodeConcept {\n /** The UCUM unit code (`Quantity.code` and, as text, `Quantity.unit`). */\n readonly unit: string;\n /** Inclusive lower bound of the synthetic value (in `unit`). */\n readonly low: number;\n /** Inclusive upper bound of the synthetic value (in `unit`). */\n readonly high: number;\n /** Decimal places to render (keeps the emitted `decimal` lexical form stable and realistic). */\n readonly decimals: number;\n}\n\nimport { SYSTEM } from \"./us-core.js\";\n\n/**\n * LOINC laboratory-result example codes (for a US Core Laboratory Result `Observation`). Public LOINC\n * identifiers used purely as illustrative structural fillers, with UCUM units and synthetic value bands.\n */\nexport const EXAMPLE_LAB_OBSERVATIONS: readonly QuantConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"2345-7\",\n display: \"Glucose [Mass/volume] in Serum or Plasma\",\n unit: \"mg/dL\",\n low: 70,\n high: 140,\n decimals: 0,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"718-7\",\n display: \"Hemoglobin [Mass/volume] in Blood\",\n unit: \"g/dL\",\n low: 12,\n high: 17,\n decimals: 1,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"2951-2\",\n display: \"Sodium [Moles/volume] in Serum or Plasma\",\n unit: \"mmol/L\",\n low: 135,\n high: 145,\n decimals: 0,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"2823-3\",\n display: \"Potassium [Moles/volume] in Serum or Plasma\",\n unit: \"mmol/L\",\n low: 4,\n high: 5,\n decimals: 1,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"4548-4\",\n display: \"Hemoglobin A1c/Hemoglobin.total in Blood\",\n unit: \"%\",\n low: 4,\n high: 9,\n decimals: 1,\n }),\n]);\n\n/**\n * LOINC vital-sign example codes (for a US Core Vital Signs `Observation`). Public LOINC identifiers\n * with their required UCUM units and synthetic value bands. Simple single-value vitals only —\n * multi-component vitals (e.g. blood-pressure panel `85354-9`) are not generated.\n */\nexport const EXAMPLE_VITAL_SIGNS: readonly QuantConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"8867-4\",\n display: \"Heart rate\",\n unit: \"/min\",\n low: 55,\n high: 100,\n decimals: 0,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"9279-1\",\n display: \"Respiratory rate\",\n unit: \"/min\",\n low: 12,\n high: 20,\n decimals: 0,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"8310-5\",\n display: \"Body temperature\",\n unit: \"Cel\",\n low: 36,\n high: 38,\n decimals: 1,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"29463-7\",\n display: \"Body weight\",\n unit: \"kg\",\n low: 50,\n high: 100,\n decimals: 1,\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"8302-2\",\n display: \"Body height\",\n unit: \"cm\",\n low: 150,\n high: 190,\n decimals: 0,\n }),\n]);\n\n/**\n * SNOMED CT problem/condition example codes (for a US Core `Condition.code`). Public SNOMED identifiers\n * used as structural fillers; `@cosyte/synth` bundles no SNOMED content.\n */\nexport const EXAMPLE_CONDITIONS: readonly CodeConcept[] = Object.freeze([\n Object.freeze({ system: SYSTEM.SNOMED, code: \"59621000\", display: \"Essential hypertension\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"44054006\", display: \"Type 2 diabetes mellitus\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"195967001\", display: \"Asthma\" }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"13645005\",\n display: \"Chronic obstructive lung disease\",\n }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"38341003\", display: \"Hypertensive disorder\" }),\n]);\n\n/**\n * RxNorm medication example codes (for a US Core `MedicationRequest.medicationCodeableConcept`). Public\n * RxNorm identifiers used as structural fillers; `@cosyte/synth` bundles no RxNorm content.\n */\nexport const EXAMPLE_MEDICATIONS: readonly CodeConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.RXNORM,\n code: \"1049221\",\n display: \"Acetaminophen 325 MG Oral Tablet\",\n }),\n Object.freeze({ system: SYSTEM.RXNORM, code: \"197361\", display: \"Amlodipine 5 MG Oral Tablet\" }),\n Object.freeze({\n system: SYSTEM.RXNORM,\n code: \"860975\",\n display: \"24 HR Metformin hydrochloride 500 MG Extended Release Oral Tablet\",\n }),\n Object.freeze({\n system: SYSTEM.RXNORM,\n code: \"308136\",\n display: \"Amoxicillin 250 MG Oral Capsule\",\n }),\n Object.freeze({\n system: SYSTEM.RXNORM,\n code: \"617314\",\n display: \"Atorvastatin 40 MG Oral Tablet\",\n }),\n]);\n\n/**\n * OMB race categories (US Core `us-core-race` `ombCategory`) — the five OMB categories, public code\n * facts from the CDC Race & Ethnicity code system (`urn:oid:2.16.840.1.113883.6.238`).\n */\nexport const EXAMPLE_RACE_CATEGORIES: readonly CodeConcept[] = Object.freeze([\n Object.freeze({ system: SYSTEM.OMB_RACE_ETHNICITY, code: \"2106-3\", display: \"White\" }),\n Object.freeze({\n system: SYSTEM.OMB_RACE_ETHNICITY,\n code: \"2054-5\",\n display: \"Black or African American\",\n }),\n Object.freeze({ system: SYSTEM.OMB_RACE_ETHNICITY, code: \"2028-9\", display: \"Asian\" }),\n Object.freeze({\n system: SYSTEM.OMB_RACE_ETHNICITY,\n code: \"1002-5\",\n display: \"American Indian or Alaska Native\",\n }),\n Object.freeze({\n system: SYSTEM.OMB_RACE_ETHNICITY,\n code: \"2076-8\",\n display: \"Native Hawaiian or Other Pacific Islander\",\n }),\n]);\n\n/**\n * OMB ethnicity categories (US Core `us-core-ethnicity` `ombCategory`) — the two OMB categories, public\n * code facts from the CDC Race & Ethnicity code system.\n */\nexport const EXAMPLE_ETHNICITY_CATEGORIES: readonly CodeConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.OMB_RACE_ETHNICITY,\n code: \"2135-2\",\n display: \"Hispanic or Latino\",\n }),\n Object.freeze({\n system: SYSTEM.OMB_RACE_ETHNICITY,\n code: \"2186-5\",\n display: \"Not Hispanic or Latino\",\n }),\n]);\n\n/**\n * CVX vaccine-administered example codes (for a US Core `Immunization.vaccineCode`). Public CDC CVX\n * identifiers used as structural fillers; `@cosyte/synth` bundles no CVX content.\n */\nexport const EXAMPLE_VACCINES: readonly CodeConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.CVX,\n code: \"140\",\n display: \"Influenza, seasonal, injectable, preservative free\",\n }),\n Object.freeze({ system: SYSTEM.CVX, code: \"03\", display: \"MMR\" }),\n Object.freeze({ system: SYSTEM.CVX, code: \"20\", display: \"DTaP\" }),\n Object.freeze({ system: SYSTEM.CVX, code: \"133\", display: \"Pneumococcal conjugate PCV 13\" }),\n Object.freeze({\n system: SYSTEM.CVX,\n code: \"208\",\n display: \"COVID-19, mRNA, LNP-S, PF, 30 mcg/0.3 mL dose\",\n }),\n]);\n\n/**\n * Allergen-substance example codes (for a US Core `AllergyIntolerance.code`). Public RxNorm / SNOMED CT\n * identifiers used as structural fillers; no terminology content is bundled.\n */\nexport const EXAMPLE_ALLERGENS: readonly CodeConcept[] = Object.freeze([\n Object.freeze({ system: SYSTEM.RXNORM, code: \"7980\", display: \"Penicillin G\" }),\n Object.freeze({ system: SYSTEM.RXNORM, code: \"2670\", display: \"Codeine\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"762952008\", display: \"Peanut (substance)\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"227493005\", display: \"Cashew nuts (substance)\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"3718001\", display: \"Cow's milk (substance)\" }),\n]);\n\n/**\n * Allergy-reaction manifestation example codes (for `AllergyIntolerance.reaction.manifestation`).\n * Public SNOMED CT clinical-finding identifiers used as structural fillers.\n */\nexport const EXAMPLE_ALLERGY_MANIFESTATIONS: readonly CodeConcept[] = Object.freeze([\n Object.freeze({ system: SYSTEM.SNOMED, code: \"247472004\", display: \"Wheal (finding)\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"126485001\", display: \"Urticaria (disorder)\" }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"271807003\",\n display: \"Eruption of skin (disorder)\",\n }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"267036007\", display: \"Dyspnea (finding)\" }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"422587007\", display: \"Nausea (finding)\" }),\n]);\n\n/**\n * SNOMED CT procedure example codes (for a US Core `Procedure.code`). Public SNOMED identifiers used as\n * structural fillers — **not** CPT (which is never bundled).\n */\nexport const EXAMPLE_PROCEDURES: readonly CodeConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"80146002\",\n display: \"Excision of appendix (procedure)\",\n }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"73761001\", display: \"Colonoscopy (procedure)\" }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"5880005\",\n display: \"Physical examination procedure (procedure)\",\n }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"108252007\",\n display: \"Laboratory procedure (procedure)\",\n }),\n Object.freeze({ system: SYSTEM.SNOMED, code: \"71651007\", display: \"Mammography (procedure)\" }),\n]);\n\n/**\n * LOINC diagnostic-report example codes (for a US Core Laboratory `DiagnosticReport.code`). Public LOINC\n * panel identifiers used as structural fillers.\n */\nexport const EXAMPLE_DIAGNOSTIC_REPORTS: readonly CodeConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"24323-8\",\n display: \"Comprehensive metabolic 2000 panel - Serum or Plasma\",\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"58410-2\",\n display: \"CBC panel - Blood by Automated count\",\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"24357-6\",\n display: \"Urinalysis complete panel - Urine\",\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"24331-1\",\n display: \"Lipid 1996 panel - Serum or Plasma\",\n }),\n Object.freeze({\n system: SYSTEM.LOINC,\n code: \"24321-2\",\n display: \"Basic metabolic 1998 panel - Serum or Plasma\",\n }),\n]);\n\n/**\n * SNOMED CT encounter-type example codes (for a US Core `Encounter.type`). Public SNOMED identifiers\n * used as structural fillers.\n */\nexport const EXAMPLE_ENCOUNTER_TYPES: readonly CodeConcept[] = Object.freeze([\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"308335008\",\n display: \"Patient encounter procedure (procedure)\",\n }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"185349003\",\n display: \"Encounter for check up (procedure)\",\n }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"185347001\",\n display: \"Encounter for problem (procedure)\",\n }),\n Object.freeze({\n system: SYSTEM.SNOMED,\n code: \"390906007\",\n display: \"Follow-up encounter (procedure)\",\n }),\n]);\n\n/**\n * HL7 v3 `ActCode` encounter-class example codes (for `Encounter.class`, a single `Coding`). Public\n * ActCode identifiers used as structural fillers.\n */\nexport const EXAMPLE_ENCOUNTER_CLASSES: readonly CodeConcept[] = Object.freeze([\n Object.freeze({ system: SYSTEM.V3_ACT_CODE, code: \"AMB\", display: \"ambulatory\" }),\n Object.freeze({ system: SYSTEM.V3_ACT_CODE, code: \"EMER\", display: \"emergency\" }),\n Object.freeze({ system: SYSTEM.V3_ACT_CODE, code: \"IMP\", display: \"inpatient encounter\" }),\n]);\n","/**\n * Synthetic FHIR R4 **`Patient`** generation — the anchor of the US Core clinical spine. Built through\n * `@cosyte/fhir`'s model constructors, every identity field drawn from the\n * synthetic-safety providers. In `us-core` mode the resource claims US Core Patient via\n * `meta.profile`, satisfies its required elements (`identifier` + `system` + `value`, `name`, `gender`),\n * and carries the must-support race / ethnicity / birthsex extensions.\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport {\n bool,\n coding,\n fhirPatientIdentity,\n meta,\n mrnIdentifier,\n narrative,\n prop,\n str,\n type Prop,\n} from \"./builder.js\";\nimport { EXAMPLE_ETHNICITY_CATEGORIES, EXAMPLE_RACE_CATEGORIES } from \"./example-codes.js\";\nimport {\n US_CORE_BIRTHSEX_EXTENSION,\n US_CORE_ETHNICITY_EXTENSION,\n US_CORE_PROFILE,\n US_CORE_RACE_EXTENSION,\n} from \"./us-core.js\";\n\n/** Options for {@link generatePatient}. */\nexport interface GeneratePatientOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /**\n * The profile posture. `\"base\"` (default) emits a spec-clean base-R4 `Patient`; `\"us-core\"` adds the\n * US Core `meta.profile` and the race/ethnicity/birthsex must-support extensions (the required\n * elements — identifier/name/gender — are always present).\n */\n readonly profile?: \"base\" | \"us-core\";\n}\n\n/** A US Core `us-core-race` / `us-core-ethnicity` complex extension with one OMB category + text. */\nfunction ombExtension(\n url: string,\n category: { system: string; code: string; display: string },\n): FhirComplex {\n return complex([\n prop(\"url\", str(url)),\n prop(\n \"extension\",\n list([\n complex([prop(\"url\", str(\"ombCategory\")), prop(\"valueCoding\", coding(category))]),\n complex([prop(\"url\", str(\"text\")), prop(\"valueString\", str(category.display))]),\n ]),\n ),\n ]);\n}\n\n/**\n * Generate a spec-clean synthetic FHIR R4 `Patient` (base or US Core), built through `@cosyte/fhir`.\n *\n * @param options - Seed and profile posture. See {@link GeneratePatientOptions}.\n * @returns The `Patient` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generatePatient } from \"@cosyte/synth/fhir\";\n * import { serializeResource } from \"@cosyte/fhir\";\n * const patient = generatePatient({ seed: 42, profile: \"us-core\" });\n * serializeResource(patient);\n * ```\n */\nexport function generatePatient(options: GeneratePatientOptions = {}): FhirComplex {\n const { seed = 0, profile = \"base\" } = options;\n const rng = createRng(seed);\n const id = fhirPatientIdentity(rng);\n const usCore = profile === \"us-core\";\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Patient\")),\n prop(\"id\", str(`syn-patient-${id.id}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.PATIENT])));\n props.push(\n prop(\n \"text\",\n narrative(\n `Synthetic patient ${id.person.given} ${id.person.family} (${id.gender}, born ${id.birthDate}).`,\n ),\n ),\n );\n\n if (usCore) {\n const race = rng.pick(EXAMPLE_RACE_CATEGORIES);\n const ethnicity = rng.pick(EXAMPLE_ETHNICITY_CATEGORIES);\n const birthsex = id.gender === \"male\" ? \"M\" : \"F\";\n props.push(\n prop(\n \"extension\",\n list([\n ombExtension(US_CORE_RACE_EXTENSION, race),\n ombExtension(US_CORE_ETHNICITY_EXTENSION, ethnicity),\n complex([prop(\"url\", str(US_CORE_BIRTHSEX_EXTENSION)), prop(\"valueCode\", str(birthsex))]),\n ]),\n ),\n );\n }\n\n props.push(prop(\"identifier\", list([mrnIdentifier(id.mrn)])));\n props.push(prop(\"active\", bool(true)));\n props.push(\n prop(\n \"name\",\n list([\n complex([\n prop(\"use\", str(\"official\")),\n prop(\"family\", str(id.person.family)),\n prop(\"given\", list([str(id.person.given)])),\n ]),\n ]),\n ),\n );\n props.push(\n prop(\n \"telecom\",\n list([\n complex([\n prop(\"system\", str(\"phone\")),\n prop(\"value\", str(id.phone)),\n prop(\"use\", str(\"home\")),\n ]),\n complex([prop(\"system\", str(\"email\")), prop(\"value\", str(id.email))]),\n ]),\n ),\n );\n props.push(prop(\"gender\", str(id.gender)));\n props.push(prop(\"birthDate\", str(id.birthDate)));\n props.push(\n prop(\n \"address\",\n list([\n complex([\n prop(\"use\", str(\"home\")),\n prop(\"line\", list([str(id.address.street)])),\n prop(\"city\", str(id.address.city)),\n prop(\"state\", str(id.address.state)),\n prop(\"postalCode\", str(id.address.zip)),\n ]),\n ]),\n ),\n );\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Condition`** generation — a US Core \"Problems and Health Concerns\" problem-list\n * item. Built through `@cosyte/fhir`; the `code` comes from the license-clean SNOMED\n * example pool, the `subject` from a supplied or derived synthetic Patient reference.\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { codeableConcept, meta, narrative, prop, reference, str, type Prop } from \"./builder.js\";\nimport { EXAMPLE_CONDITIONS } from \"./example-codes.js\";\nimport { SYSTEM, US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateCondition}. */\nexport interface GenerateConditionOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `subject` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly subject?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core `Condition` (problem-list item), built through `@cosyte/fhir`.\n *\n * @param options - Seed, subject reference, and US Core posture. See {@link GenerateConditionOptions}.\n * @returns The `Condition` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateCondition } from \"@cosyte/synth/fhir\";\n * const condition = generateCondition({ seed: 7, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateCondition(options: GenerateConditionOptions = {}): FhirComplex {\n const { seed = 0, subject = \"Patient/syn-patient-1\", usCore = true } = options;\n const rng = createRng(seed);\n const code = rng.pick(EXAMPLE_CONDITIONS);\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Condition\")),\n prop(\"id\", str(`syn-cond-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.CONDITION])));\n props.push(prop(\"text\", narrative(`Synthetic condition: ${code.display}.`)));\n props.push(\n prop(\n \"clinicalStatus\",\n codeableConcept({ system: SYSTEM.CONDITION_CLINICAL, code: \"active\", display: \"Active\" }),\n ),\n );\n props.push(\n prop(\n \"verificationStatus\",\n codeableConcept({\n system: SYSTEM.CONDITION_VER_STATUS,\n code: \"confirmed\",\n display: \"Confirmed\",\n }),\n ),\n );\n props.push(\n prop(\n \"category\",\n list([\n codeableConcept({\n system: SYSTEM.CONDITION_CATEGORY,\n code: \"problem-list-item\",\n display: \"Problem List Item\",\n }),\n ]),\n ),\n );\n props.push(prop(\"code\", codeableConcept(code)));\n props.push(prop(\"subject\", reference(subject)));\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Observation`** generation — US Core Laboratory Result and US Core Vital Signs. Built\n * through `@cosyte/fhir`; `code` and the measured `valueQuantity` come from\n * the license-clean LOINC/UCUM example pool, `subject` from a supplied or derived Patient reference.\n * The measured value is drawn from the seeded generator within a structurally-sane band — it implies no\n * real measurement.\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng, type Rng } from \"../rng/rng.js\";\nimport {\n codeableConcept,\n dec,\n meta,\n narrative,\n prop,\n reference,\n str,\n type Prop,\n} from \"./builder.js\";\nimport {\n EXAMPLE_LAB_OBSERVATIONS,\n EXAMPLE_VITAL_SIGNS,\n type QuantConcept,\n} from \"./example-codes.js\";\nimport { SYSTEM, US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateObservationLab} / {@link generateVitalSign}. */\nexport interface GenerateObservationOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `subject` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly subject?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/** Draw a synthetic `decimal` value string within the concept's band, at its declared precision. */\nfunction drawValue(rng: Rng, concept: QuantConcept): string {\n const span = concept.high - concept.low;\n const raw = concept.low + rng.float() * span;\n return raw.toFixed(concept.decimals);\n}\n\n/** A UCUM `valueQuantity` for a measured concept — `value` (decimal), `unit`, UCUM `system` + `code`. */\nfunction valueQuantity(rng: Rng, concept: QuantConcept): FhirComplex {\n return complex([\n prop(\"value\", dec(drawValue(rng, concept))),\n prop(\"unit\", str(concept.unit)),\n prop(\"system\", str(SYSTEM.UCUM)),\n prop(\"code\", str(concept.unit)),\n ]);\n}\n\n/** Build an `Observation` of the given category from a measured concept pool. */\nfunction buildObservation(\n seed: number,\n subject: string,\n usCore: boolean,\n profileUrl: string,\n category: { code: string; display: string },\n pool: readonly QuantConcept[],\n effective: boolean,\n): FhirComplex {\n const rng = createRng(seed);\n const concept = rng.pick(pool);\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Observation\")),\n prop(\"id\", str(`syn-obs-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([profileUrl])));\n props.push(\n prop(\"text\", narrative(`Synthetic ${category.display.toLowerCase()}: ${concept.display}.`)),\n );\n props.push(prop(\"status\", str(\"final\")));\n props.push(\n prop(\n \"category\",\n list([\n codeableConcept({\n system: SYSTEM.OBSERVATION_CATEGORY,\n code: category.code,\n display: category.display,\n }),\n ]),\n ),\n );\n props.push(prop(\"code\", codeableConcept(concept)));\n props.push(prop(\"subject\", reference(subject)));\n // Draw the effective instant deterministically (a plausible recent date) before the value.\n const y = rng.int(2020, 2025);\n const m = String(rng.int(1, 12)).padStart(2, \"0\");\n const d = String(rng.int(1, 28)).padStart(2, \"0\");\n if (effective) props.push(prop(\"effectiveDateTime\", str(`${String(y)}-${m}-${d}`)));\n props.push(prop(\"valueQuantity\", valueQuantity(rng, concept)));\n return complex(props);\n}\n\n/**\n * Generate a spec-clean synthetic US Core **Laboratory Result** `Observation`.\n *\n * @param options - Seed, subject reference, US Core posture. See {@link GenerateObservationOptions}.\n * @returns The `Observation` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateObservationLab } from \"@cosyte/synth/fhir\";\n * const obs = generateObservationLab({ seed: 3, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateObservationLab(options: GenerateObservationOptions = {}): FhirComplex {\n const { seed = 0, subject = \"Patient/syn-patient-1\", usCore = true } = options;\n return buildObservation(\n seed,\n subject,\n usCore,\n US_CORE_PROFILE.OBSERVATION_LAB,\n { code: \"laboratory\", display: \"Laboratory\" },\n EXAMPLE_LAB_OBSERVATIONS,\n false,\n );\n}\n\n/**\n * Generate a spec-clean synthetic US Core **Vital Signs** `Observation` (a single-value vital such as\n * heart rate or body weight; `effectiveDateTime` is required by the vital-signs profile).\n *\n * @param options - Seed, subject reference, US Core posture. See {@link GenerateObservationOptions}.\n * @returns The `Observation` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateVitalSign } from \"@cosyte/synth/fhir\";\n * const vs = generateVitalSign({ seed: 5, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateVitalSign(options: GenerateObservationOptions = {}): FhirComplex {\n const { seed = 0, subject = \"Patient/syn-patient-1\", usCore = true } = options;\n return buildObservation(\n seed,\n subject,\n usCore,\n US_CORE_PROFILE.VITAL_SIGNS,\n { code: \"vital-signs\", display: \"Vital Signs\" },\n EXAMPLE_VITAL_SIGNS,\n true,\n );\n}\n","/**\n * Synthetic FHIR R4 **`MedicationRequest`** generation — a US Core MedicationRequest with an inline\n * `medicationCodeableConcept`. Built through `@cosyte/fhir`; the medication comes\n * from the license-clean RxNorm example pool. US Core invariant `us-core-21` requires a `requester`\n * whenever `intent = order`, so a synthetic requester reference is always emitted.\n *\n * @module\n */\n\nimport { complex } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { codeableConcept, meta, narrative, prop, reference, str, type Prop } from \"./builder.js\";\nimport { EXAMPLE_MEDICATIONS } from \"./example-codes.js\";\nimport { US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateMedicationRequest}. */\nexport interface GenerateMedicationRequestOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `subject` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly subject?: string;\n /** The `requester` reference. Defaults to a synthetic `Practitioner` reference. */\n readonly requester?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core `MedicationRequest`, built through `@cosyte/fhir`.\n *\n * @param options - Seed, subject/requester references, US Core posture.\n * @returns The `MedicationRequest` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateMedicationRequest } from \"@cosyte/synth/fhir\";\n * const mr = generateMedicationRequest({ seed: 9, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateMedicationRequest(\n options: GenerateMedicationRequestOptions = {},\n): FhirComplex {\n const {\n seed = 0,\n subject = \"Patient/syn-patient-1\",\n requester = \"Practitioner/syn-practitioner-1\",\n usCore = true,\n } = options;\n const rng = createRng(seed);\n const med = rng.pick(EXAMPLE_MEDICATIONS);\n const y = rng.int(2020, 2025);\n const m = String(rng.int(1, 12)).padStart(2, \"0\");\n const d = String(rng.int(1, 28)).padStart(2, \"0\");\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"MedicationRequest\")),\n prop(\"id\", str(`syn-medreq-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.MEDICATION_REQUEST])));\n props.push(prop(\"text\", narrative(`Synthetic medication order: ${med.display}.`)));\n props.push(prop(\"status\", str(\"active\")));\n props.push(prop(\"intent\", str(\"order\")));\n props.push(prop(\"medicationCodeableConcept\", codeableConcept(med)));\n props.push(prop(\"subject\", reference(subject)));\n props.push(prop(\"authoredOn\", str(`${String(y)}-${m}-${d}`)));\n props.push(prop(\"requester\", reference(requester)));\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Encounter`** generation — a US Core Encounter. Built through `@cosyte/fhir`'s model\n * constructors; `class` and `type` come from the\n * license-clean v3-ActCode / SNOMED example pools, `subject` from a supplied or derived synthetic\n * Patient reference. The required elements (`status`, `class`, `type`, `subject`) are always present.\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { safe } from \"../safe/index.js\";\nimport {\n coding,\n codeableConcept,\n meta,\n narrative,\n prop,\n reference,\n str,\n toFhirDate,\n type Prop,\n} from \"./builder.js\";\nimport { EXAMPLE_ENCOUNTER_CLASSES, EXAMPLE_ENCOUNTER_TYPES } from \"./example-codes.js\";\nimport { US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateEncounter}. */\nexport interface GenerateEncounterOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `subject` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly subject?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core `Encounter`, built through `@cosyte/fhir`.\n *\n * @param options - Seed, subject reference, and US Core posture. See {@link GenerateEncounterOptions}.\n * @returns The `Encounter` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateEncounter } from \"@cosyte/synth/fhir\";\n * const encounter = generateEncounter({ seed: 11, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateEncounter(options: GenerateEncounterOptions = {}): FhirComplex {\n const { seed = 0, subject = \"Patient/syn-patient-1\", usCore = true } = options;\n const rng = createRng(seed);\n const cls = rng.pick(EXAMPLE_ENCOUNTER_CLASSES);\n const type = rng.pick(EXAMPLE_ENCOUNTER_TYPES);\n const id = safe.identifier(rng, \"AN\");\n const start = toFhirDate(safe.dateYmd(rng, 2018, 2024));\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Encounter\")),\n prop(\"id\", str(`syn-enc-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.ENCOUNTER])));\n props.push(prop(\"text\", narrative(`Synthetic encounter: ${type.display}.`)));\n props.push(\n prop(\n \"identifier\",\n list([\n complex([\n prop(\"system\", str(`urn:oid:${id.assigningAuthorityOid}`)),\n prop(\"value\", str(id.value)),\n ]),\n ]),\n ),\n );\n props.push(prop(\"status\", str(\"finished\")));\n props.push(prop(\"class\", coding(cls)));\n props.push(prop(\"type\", list([codeableConcept(type)])));\n props.push(prop(\"subject\", reference(subject)));\n props.push(prop(\"period\", complex([prop(\"start\", str(`${start}T09:00:00Z`))])));\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Immunization`** generation — a US Core Immunization. Built through `@cosyte/fhir`;\n * `vaccineCode` comes from the license-clean CVX example\n * pool, `patient` from a supplied or derived synthetic Patient reference. The required elements\n * (`status`, `vaccineCode`, `patient`, `occurrenceDateTime`) are always present.\n *\n * @module\n */\n\nimport { complex } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { safe } from \"../safe/index.js\";\nimport {\n bool,\n codeableConcept,\n meta,\n narrative,\n prop,\n reference,\n str,\n toFhirDate,\n type Prop,\n} from \"./builder.js\";\nimport { EXAMPLE_VACCINES } from \"./example-codes.js\";\nimport { US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateImmunization}. */\nexport interface GenerateImmunizationOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `patient` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly patient?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core `Immunization`, built through `@cosyte/fhir`.\n *\n * @param options - Seed, patient reference, and US Core posture. See {@link GenerateImmunizationOptions}.\n * @returns The `Immunization` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateImmunization } from \"@cosyte/synth/fhir\";\n * const imm = generateImmunization({ seed: 13, patient: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateImmunization(options: GenerateImmunizationOptions = {}): FhirComplex {\n const { seed = 0, patient = \"Patient/syn-patient-1\", usCore = true } = options;\n const rng = createRng(seed);\n const vaccine = rng.pick(EXAMPLE_VACCINES);\n const occurrence = toFhirDate(safe.dateYmd(rng, 2015, 2024));\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Immunization\")),\n prop(\"id\", str(`syn-imm-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.IMMUNIZATION])));\n props.push(prop(\"text\", narrative(`Synthetic immunization: ${vaccine.display}.`)));\n props.push(prop(\"status\", str(\"completed\")));\n props.push(prop(\"vaccineCode\", codeableConcept(vaccine)));\n props.push(prop(\"patient\", reference(patient)));\n props.push(prop(\"occurrenceDateTime\", str(occurrence)));\n props.push(prop(\"primarySource\", bool(true)));\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`AllergyIntolerance`** generation — a US Core AllergyIntolerance. Built through\n * `@cosyte/fhir`; the allergen `code` and reaction\n * `manifestation` come from the license-clean RxNorm/SNOMED example pools, `patient` from a supplied or\n * derived synthetic Patient reference. `clinicalStatus` + `verificationStatus` are emitted together so\n * the base `ait-1`/`ait-2` invariants hold; the required `code` and `patient` are always present.\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { codeableConcept, meta, narrative, prop, reference, str, type Prop } from \"./builder.js\";\nimport { EXAMPLE_ALLERGENS, EXAMPLE_ALLERGY_MANIFESTATIONS } from \"./example-codes.js\";\nimport { SYSTEM, US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateAllergyIntolerance}. */\nexport interface GenerateAllergyIntoleranceOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `patient` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly patient?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core `AllergyIntolerance`, built through `@cosyte/fhir`.\n *\n * @param options - Seed, patient reference, and US Core posture. See\n * {@link GenerateAllergyIntoleranceOptions}.\n * @returns The `AllergyIntolerance` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateAllergyIntolerance } from \"@cosyte/synth/fhir\";\n * const allergy = generateAllergyIntolerance({ seed: 15, patient: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateAllergyIntolerance(\n options: GenerateAllergyIntoleranceOptions = {},\n): FhirComplex {\n const { seed = 0, patient = \"Patient/syn-patient-1\", usCore = true } = options;\n const rng = createRng(seed);\n const allergen = rng.pick(EXAMPLE_ALLERGENS);\n const manifestation = rng.pick(EXAMPLE_ALLERGY_MANIFESTATIONS);\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"AllergyIntolerance\")),\n prop(\"id\", str(`syn-allergy-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.ALLERGY_INTOLERANCE])));\n props.push(prop(\"text\", narrative(`Synthetic allergy: ${allergen.display}.`)));\n props.push(\n prop(\n \"clinicalStatus\",\n codeableConcept({ system: SYSTEM.ALLERGY_CLINICAL, code: \"active\", display: \"Active\" }),\n ),\n );\n props.push(\n prop(\n \"verificationStatus\",\n codeableConcept({\n system: SYSTEM.ALLERGY_VERIFICATION,\n code: \"confirmed\",\n display: \"Confirmed\",\n }),\n ),\n );\n props.push(prop(\"code\", codeableConcept(allergen)));\n props.push(prop(\"patient\", reference(patient)));\n props.push(\n prop(\n \"reaction\",\n list([complex([prop(\"manifestation\", list([codeableConcept(manifestation)]))])]),\n ),\n );\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Procedure`** generation — a US Core Procedure. Built through `@cosyte/fhir`; the\n * `code` comes from the license-clean SNOMED procedure\n * example pool (never CPT), `subject` from a supplied or derived synthetic Patient\n * reference. The required elements (`status`, `code`, `subject`) plus the must-support\n * `performedDateTime` are always present.\n *\n * @module\n */\n\nimport { complex } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { safe } from \"../safe/index.js\";\nimport {\n codeableConcept,\n meta,\n narrative,\n prop,\n reference,\n str,\n toFhirDate,\n type Prop,\n} from \"./builder.js\";\nimport { EXAMPLE_PROCEDURES } from \"./example-codes.js\";\nimport { US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateProcedure}. */\nexport interface GenerateProcedureOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `subject` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly subject?: string;\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core `Procedure`, built through `@cosyte/fhir`.\n *\n * @param options - Seed, subject reference, and US Core posture. See {@link GenerateProcedureOptions}.\n * @returns The `Procedure` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateProcedure } from \"@cosyte/synth/fhir\";\n * const procedure = generateProcedure({ seed: 17, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateProcedure(options: GenerateProcedureOptions = {}): FhirComplex {\n const { seed = 0, subject = \"Patient/syn-patient-1\", usCore = true } = options;\n const rng = createRng(seed);\n const code = rng.pick(EXAMPLE_PROCEDURES);\n const performed = toFhirDate(safe.dateYmd(rng, 2018, 2024));\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Procedure\")),\n prop(\"id\", str(`syn-proc-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.PROCEDURE])));\n props.push(prop(\"text\", narrative(`Synthetic procedure: ${code.display}.`)));\n props.push(prop(\"status\", str(\"completed\")));\n props.push(prop(\"code\", codeableConcept(code)));\n props.push(prop(\"subject\", reference(subject)));\n props.push(prop(\"performedDateTime\", str(`${performed}T10:00:00Z`)));\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`DiagnosticReport`** generation — the US Core DiagnosticReport Profile for\n * Laboratory Results Reporting. Built through `@cosyte/fhir`;\n * the report `code` comes from the license-clean LOINC example pool, `subject` from a supplied or\n * derived synthetic Patient reference. The required `category` carries the profile's mandated `LAB`\n * slice, and `effectiveDateTime` + `issued` are always present so the `us-core-8`/`us-core-9`\n * invariants hold for a `final` report. Optional `result` references wire the report to its\n * `Observation`s (used by the `document` Bundle).\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng } from \"../rng/rng.js\";\nimport { safe } from \"../safe/index.js\";\nimport {\n codeableConcept,\n meta,\n narrative,\n prop,\n reference,\n str,\n toFhirDate,\n type Prop,\n} from \"./builder.js\";\nimport { EXAMPLE_DIAGNOSTIC_REPORTS } from \"./example-codes.js\";\nimport { SYSTEM, US_CORE_PROFILE } from \"./us-core.js\";\n\n/** Options for {@link generateDiagnosticReport}. */\nexport interface GenerateDiagnosticReportOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The `subject` reference (e.g. `\"Patient/syn-patient-1\"` or a `urn:uuid:` fullUrl). */\n readonly subject?: string;\n /** `result` references to the report's `Observation`s (empty ⇒ omitted). */\n readonly results?: readonly string[];\n /** Whether to claim US Core via `meta.profile`. Defaults to `true`. */\n readonly usCore?: boolean;\n}\n\n/**\n * Generate a spec-clean synthetic US Core Laboratory `DiagnosticReport`, built through `@cosyte/fhir`.\n *\n * @param options - Seed, subject, result references, US Core posture. See\n * {@link GenerateDiagnosticReportOptions}.\n * @returns The `DiagnosticReport` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateDiagnosticReport } from \"@cosyte/synth/fhir\";\n * const report = generateDiagnosticReport({ seed: 19, subject: \"Patient/syn-patient-1\" });\n * ```\n */\nexport function generateDiagnosticReport(\n options: GenerateDiagnosticReportOptions = {},\n): FhirComplex {\n const { seed = 0, subject = \"Patient/syn-patient-1\", results = [], usCore = true } = options;\n const rng = createRng(seed);\n const code = rng.pick(EXAMPLE_DIAGNOSTIC_REPORTS);\n const day = toFhirDate(safe.dateYmd(rng, 2018, 2024));\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"DiagnosticReport\")),\n prop(\"id\", str(`syn-dr-${rng.digits(8)}`)),\n ];\n if (usCore) props.push(prop(\"meta\", meta([US_CORE_PROFILE.DIAGNOSTIC_REPORT_LAB])));\n props.push(prop(\"text\", narrative(`Synthetic laboratory report: ${code.display}.`)));\n props.push(prop(\"status\", str(\"final\")));\n props.push(\n prop(\n \"category\",\n list([\n codeableConcept({\n system: SYSTEM.DIAGNOSTIC_SERVICE_SECTION,\n code: \"LAB\",\n display: \"Laboratory\",\n }),\n ]),\n ),\n );\n props.push(prop(\"code\", codeableConcept(code)));\n props.push(prop(\"subject\", reference(subject)));\n props.push(prop(\"effectiveDateTime\", str(`${day}T08:30:00Z`)));\n props.push(prop(\"issued\", str(`${day}T09:00:00.000Z`)));\n if (results.length > 0) {\n props.push(prop(\"result\", list(results.map((r) => reference(r)))));\n }\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Composition`** generation — the mandatory first resource of a `document` Bundle\n * (FHIR invariant `bdl-11`), built through `@cosyte/fhir`.\n * A Composition is a base-R4 resource (US Core 6.1.0 defines no Composition profile), so it is grounded\n * against base FHIR R4; every reference it carries (`subject`, `author`, `custodian`, section `entry`s)\n * is an in-bundle `urn:uuid:` fullUrl so the document is self-contained and its references resolve.\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport type { Rng } from \"../rng/rng.js\";\nimport { codeableConcept, narrative, prop, reference, str, type Prop } from \"./builder.js\";\nimport { SYSTEM } from \"./us-core.js\";\n\n/** A document section: a LOINC section code, a human title, and the entry references it summarizes. */\nexport interface CompositionSection {\n /** The LOINC section code. */\n readonly code: string;\n /** The section's human title / display. */\n readonly title: string;\n /** In-bundle `urn:uuid:` references to the resources the section summarizes. */\n readonly entries: readonly string[];\n}\n\n/** Inputs for {@link buildComposition}. */\nexport interface BuildCompositionInput {\n /** The `subject` reference (the patient's in-bundle fullUrl). */\n readonly subject: string;\n /** The `author` + `custodian` reference (an in-bundle Organization fullUrl). */\n readonly organization: string;\n /** The document date (`YYYY-MM-DD`). */\n readonly date: string;\n /** The document sections. */\n readonly sections: readonly CompositionSection[];\n}\n\n/** One `Composition.section` — title, LOINC code, and its `entry` references (satisfies `cmp-1`). */\nfunction section(sec: CompositionSection): FhirComplex {\n return complex([\n prop(\"title\", str(sec.title)),\n prop(\"code\", codeableConcept({ system: SYSTEM.LOINC, code: sec.code, display: sec.title })),\n prop(\"entry\", list(sec.entries.map((e) => reference(e)))),\n ]);\n}\n\n/**\n * Build a spec-clean synthetic base-R4 `Composition` for a `document` Bundle, through `@cosyte/fhir`.\n *\n * @param rng - The seeded generator (for the resource id).\n * @param input - Subject/organization references, date, and sections. See {@link BuildCompositionInput}.\n * @returns The `Composition` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { buildComposition } from \"@cosyte/synth/fhir\";\n * // buildComposition(createRng(1), { subject, organization, date: \"2020-01-01\", sections: [] });\n * ```\n */\nexport function buildComposition(rng: Rng, input: BuildCompositionInput): FhirComplex {\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Composition\")),\n prop(\"id\", str(`syn-comp-${rng.digits(8)}`)),\n prop(\"text\", narrative(\"Synthetic continuity-of-care document summary.\")),\n prop(\"status\", str(\"final\")),\n prop(\n \"type\",\n codeableConcept({\n system: SYSTEM.LOINC,\n code: \"34133-9\",\n display: \"Summarization of Episode Note\",\n }),\n ),\n prop(\"subject\", reference(input.subject)),\n prop(\"date\", str(`${input.date}T09:00:00Z`)),\n prop(\"author\", list([reference(input.organization)])),\n prop(\"title\", str(\"Synthetic Continuity of Care Document\")),\n prop(\"custodian\", reference(input.organization)),\n prop(\"section\", list(input.sections.map((s) => section(s)))),\n ];\n return complex(props);\n}\n","/**\n * Synthetic FHIR R4 **`Bundle`** generation — a self-contained `collection`,\n * `transaction`, or `document` Bundle assembling a synthetic US Core `Patient` and its full clinical\n * spine (`Condition`, lab + vital-sign `Observation`s, `MedicationRequest`, `Encounter`,\n * `Immunization`, `AllergyIntolerance`, `Procedure`, `DiagnosticReport`), wired by `urn:uuid:`\n * `fullUrl`s so every intra-bundle reference resolves. Built through `@cosyte/fhir`. The `document`\n * shape prepends the FHIR-mandated `Composition` (invariant `bdl-11`) and a synthetic\n * `Organization` author/custodian, and carries the required `identifier` + `timestamp` (`bdl-9`/`bdl-10`).\n *\n * @module\n */\n\nimport { complex, list } from \"@cosyte/fhir\";\nimport type { FhirComplex } from \"@cosyte/fhir\";\n\nimport { createRng, type Rng } from \"../rng/rng.js\";\nimport { makeCorpus, type Corpus } from \"../corpus.js\";\nimport { bool, narrative, prop, str, toFhirDate, type Prop } from \"./builder.js\";\nimport { buildComposition, type CompositionSection } from \"./composition.js\";\nimport { generatePatient } from \"./patient.js\";\nimport { generateCondition } from \"./condition.js\";\nimport { generateObservationLab, generateVitalSign } from \"./observation.js\";\nimport { generateMedicationRequest } from \"./medication-request.js\";\nimport { generateEncounter } from \"./encounter.js\";\nimport { generateImmunization } from \"./immunization.js\";\nimport { generateAllergyIntolerance } from \"./allergy-intolerance.js\";\nimport { generateProcedure } from \"./procedure.js\";\nimport { generateDiagnosticReport } from \"./diagnostic-report.js\";\nimport { roundTrip } from \"./round-trip.js\";\nimport { safe } from \"../safe/index.js\";\n\n/** The Bundle shapes `@cosyte/synth` supports. */\nexport type FhirBundleType = \"collection\" | \"transaction\" | \"document\";\n\n/** Options for {@link generateBundle}. */\nexport interface GenerateBundleOptions {\n /** The seed (deterministic). Defaults to `0`. */\n readonly seed?: number;\n /** The Bundle shape. Defaults to `\"collection\"`. */\n readonly type?: FhirBundleType;\n}\n\n/** The `resourceType` string of a generated resource (its `request.url` in a transaction Bundle). */\nfunction resourceTypeOf(resource: FhirComplex): string {\n const rt = resource.properties.find((p) => p.name === \"resourceType\");\n return rt !== undefined && rt.value.kind === \"primitive\" ? String(rt.value.value) : \"Resource\";\n}\n\n/** A minimal synthetic `Organization` (author/custodian) — no PHI, name is clearly synthetic. */\nfunction buildOrganization(rng: Rng): FhirComplex {\n const id = safe.identifier(rng, \"AN\");\n return complex([\n prop(\"resourceType\", str(\"Organization\")),\n prop(\"id\", str(`syn-org-${rng.digits(8)}`)),\n prop(\"text\", narrative(\"Synthetic health organization.\")),\n prop(\n \"identifier\",\n list([\n complex([\n prop(\"system\", str(`urn:oid:${id.assigningAuthorityOid}`)),\n prop(\"value\", str(id.value)),\n ]),\n ]),\n ),\n prop(\"active\", bool(true)),\n prop(\"name\", str(\"Synthetic Health Organization\")),\n ]);\n}\n\n/** One assembled spine member — its stable in-bundle `urn:uuid:` fullUrl and its resource model. */\ninterface SpineEntry {\n readonly fullUrl: string;\n readonly resource: FhirComplex;\n}\n\n/** The assembled clinical spine plus the shared patient / organization fullUrls a document references. */\ninterface Spine {\n readonly patientUrl: string;\n readonly orgUrl: string;\n readonly date: string;\n /** Per-kind fullUrls, for the document Composition's section entries. */\n readonly urls: Readonly<Record<string, string>>;\n /** The clinical entries (Patient first, then Organization, then the clinical resources). */\n readonly entries: readonly SpineEntry[];\n}\n\n/** Build the shared clinical spine — every reference wired to an in-bundle `urn:uuid:` fullUrl. */\nfunction buildSpine(rng: Rng): Spine {\n const patientUrl = `urn:uuid:${safe.uuid(rng)}`;\n const orgUrl = `urn:uuid:${safe.uuid(rng)}`;\n const date = toFhirDate(safe.dateYmd(rng, 2018, 2024));\n\n const patient: SpineEntry = {\n fullUrl: patientUrl,\n resource: generatePatient({ seed: rng.nextUint32(), profile: \"us-core\" }),\n };\n const org: SpineEntry = { fullUrl: orgUrl, resource: buildOrganization(rng) };\n\n const condUrl = `urn:uuid:${safe.uuid(rng)}`;\n const cond = generateCondition({ seed: rng.nextUint32(), subject: patientUrl });\n const labUrl = `urn:uuid:${safe.uuid(rng)}`;\n const lab = generateObservationLab({ seed: rng.nextUint32(), subject: patientUrl });\n const vitalUrl = `urn:uuid:${safe.uuid(rng)}`;\n const vital = generateVitalSign({ seed: rng.nextUint32(), subject: patientUrl });\n const medUrl = `urn:uuid:${safe.uuid(rng)}`;\n const med = generateMedicationRequest({\n seed: rng.nextUint32(),\n subject: patientUrl,\n requester: orgUrl,\n });\n const encUrl = `urn:uuid:${safe.uuid(rng)}`;\n const enc = generateEncounter({ seed: rng.nextUint32(), subject: patientUrl });\n const immUrl = `urn:uuid:${safe.uuid(rng)}`;\n const imm = generateImmunization({ seed: rng.nextUint32(), patient: patientUrl });\n const allergyUrl = `urn:uuid:${safe.uuid(rng)}`;\n const allergy = generateAllergyIntolerance({ seed: rng.nextUint32(), patient: patientUrl });\n const procUrl = `urn:uuid:${safe.uuid(rng)}`;\n const proc = generateProcedure({ seed: rng.nextUint32(), subject: patientUrl });\n const drUrl = `urn:uuid:${safe.uuid(rng)}`;\n const dr = generateDiagnosticReport({\n seed: rng.nextUint32(),\n subject: patientUrl,\n results: [labUrl],\n });\n\n const entries: SpineEntry[] = [\n patient,\n org,\n { fullUrl: condUrl, resource: cond },\n { fullUrl: labUrl, resource: lab },\n { fullUrl: vitalUrl, resource: vital },\n { fullUrl: medUrl, resource: med },\n { fullUrl: encUrl, resource: enc },\n { fullUrl: immUrl, resource: imm },\n { fullUrl: allergyUrl, resource: allergy },\n { fullUrl: procUrl, resource: proc },\n { fullUrl: drUrl, resource: dr },\n ];\n const urls = {\n condition: condUrl,\n lab: labUrl,\n vital: vitalUrl,\n medication: medUrl,\n encounter: encUrl,\n immunization: immUrl,\n allergy: allergyUrl,\n procedure: procUrl,\n diagnosticReport: drUrl,\n };\n return { patientUrl, orgUrl, date, urls, entries };\n}\n\n/** The document sections summarizing the clinical spine (LOINC section codes → entry references). */\nfunction documentSections(urls: Readonly<Record<string, string>>): CompositionSection[] {\n const at = (k: string): string[] => (urls[k] !== undefined ? [urls[k]] : []);\n return [\n { code: \"11450-4\", title: \"Problem List\", entries: at(\"condition\") },\n {\n code: \"30954-2\",\n title: \"Relevant Diagnostic Tests/Laboratory Data\",\n entries: [...at(\"diagnosticReport\"), ...at(\"lab\"), ...at(\"vital\")],\n },\n { code: \"10160-0\", title: \"History of Medication Use\", entries: at(\"medication\") },\n { code: \"48765-2\", title: \"Allergies and Adverse Reactions\", entries: at(\"allergy\") },\n { code: \"11369-6\", title: \"History of Immunizations\", entries: at(\"immunization\") },\n { code: \"47519-4\", title: \"History of Procedures\", entries: at(\"procedure\") },\n { code: \"46240-8\", title: \"History of Encounters\", entries: at(\"encounter\") },\n ];\n}\n\n/**\n * Generate a spec-clean synthetic FHIR `Bundle` (`collection`, `transaction`, or `document`) built\n * through `@cosyte/fhir`, containing a US Core `Patient` and its full clinical spine wired by\n * `urn:uuid:` references so every reference resolves in-bundle.\n *\n * @param options - Seed and Bundle shape. See {@link GenerateBundleOptions}.\n * @returns The `Bundle` resource model (a `FhirComplex`).\n * @example\n * ```ts\n * import { generateBundle } from \"@cosyte/synth/fhir\";\n * const bundle = generateBundle({ seed: 42, type: \"document\" });\n * ```\n */\nexport function generateBundle(options: GenerateBundleOptions = {}): FhirComplex {\n const { seed = 0, type = \"collection\" } = options;\n const rng = createRng(seed);\n const spine = buildSpine(rng);\n\n const members: SpineEntry[] =\n type === \"document\"\n ? [\n {\n fullUrl: `urn:uuid:${safe.uuid(rng)}`,\n resource: buildComposition(rng, {\n subject: spine.patientUrl,\n organization: spine.orgUrl,\n date: spine.date,\n sections: documentSections(spine.urls),\n }),\n },\n ...spine.entries,\n ]\n : [...spine.entries];\n\n const entries = members.map((member) => {\n const entryProps: Prop[] = [\n prop(\"fullUrl\", str(member.fullUrl)),\n prop(\"resource\", member.resource),\n ];\n // A document Bundle forbids entry.request/response (bdl-3a); a transaction requires request.\n if (type === \"transaction\") {\n entryProps.push(\n prop(\n \"request\",\n complex([prop(\"method\", str(\"POST\")), prop(\"url\", str(resourceTypeOf(member.resource)))]),\n ),\n );\n }\n return complex(entryProps);\n });\n\n const props: Prop[] = [\n prop(\"resourceType\", str(\"Bundle\")),\n prop(\"id\", str(`syn-bundle-${rng.digits(8)}`)),\n ];\n // A document Bundle requires an identifier (bdl-9) and a timestamp (bdl-10).\n if (type === \"document\") {\n const id = safe.identifier(rng, \"AN\");\n props.push(\n prop(\n \"identifier\",\n complex([\n prop(\"system\", str(`urn:oid:${id.assigningAuthorityOid}`)),\n prop(\"value\", str(`urn:uuid:${safe.uuid(rng)}`)),\n ]),\n ),\n );\n }\n props.push(prop(\"type\", str(type)));\n if (type === \"document\") props.push(prop(\"timestamp\", str(`${spine.date}T09:00:00.000Z`)));\n props.push(prop(\"entry\", list(entries)));\n\n return complex(props);\n}\n\n/** A FHIR resource kind the {@link fhirCorpus} can generate. */\nexport type FhirResourceKind =\n | \"Patient\"\n | \"USCorePatient\"\n | \"Condition\"\n | \"ObservationLab\"\n | \"VitalSign\"\n | \"MedicationRequest\"\n | \"Encounter\"\n | \"Immunization\"\n | \"AllergyIntolerance\"\n | \"Procedure\"\n | \"DiagnosticReport\"\n | \"Bundle\"\n | \"DocumentBundle\";\n\n/** The default corpus mix — the full US Core clinical spine plus a collection Bundle. */\nconst DEFAULT_MIX: readonly FhirResourceKind[] = Object.freeze([\n \"USCorePatient\",\n \"Condition\",\n \"ObservationLab\",\n \"VitalSign\",\n \"MedicationRequest\",\n \"Encounter\",\n \"Immunization\",\n \"AllergyIntolerance\",\n \"Procedure\",\n \"DiagnosticReport\",\n \"Bundle\",\n]);\n\n/** Generate one resource of the given kind from a seed. */\nfunction generateKind(kind: FhirResourceKind, seed: number): FhirComplex {\n switch (kind) {\n case \"Patient\":\n return generatePatient({ seed, profile: \"base\" });\n case \"USCorePatient\":\n return generatePatient({ seed, profile: \"us-core\" });\n case \"Condition\":\n return generateCondition({ seed });\n case \"ObservationLab\":\n return generateObservationLab({ seed });\n case \"VitalSign\":\n return generateVitalSign({ seed });\n case \"MedicationRequest\":\n return generateMedicationRequest({ seed });\n case \"Encounter\":\n return generateEncounter({ seed });\n case \"Immunization\":\n return generateImmunization({ seed });\n case \"AllergyIntolerance\":\n return generateAllergyIntolerance({ seed });\n case \"Procedure\":\n return generateProcedure({ seed });\n case \"DiagnosticReport\":\n return generateDiagnosticReport({ seed });\n case \"Bundle\":\n return generateBundle({ seed });\n case \"DocumentBundle\":\n return generateBundle({ seed, type: \"document\" });\n }\n}\n\n/** Options for {@link fhirCorpus}. */\nexport interface FhirCorpusOptions {\n /** The seed for the whole corpus (deterministic). */\n readonly seed: number;\n /** How many resources to generate. Defaults to `1`. */\n readonly count?: number;\n /** The resource kinds to cycle through. Defaults to the full US Core clinical spine + a Bundle. */\n readonly mix?: readonly FhirResourceKind[];\n}\n\n/**\n * Build a reproducible {@link Corpus} of spec-clean FHIR resources across the supported kinds. Each\n * resource is generated from a distinct sub-seed derived from the corpus seed and round-tripped through\n * `@cosyte/fhir`; the per-artifact `warnings` record the validator's non-informational findings (empty\n * ⇒ spec-clean, no US Core profiles supplied). Pass US Core `StructureDefinition`s to a per-resource\n * {@link roundTrip} call to additionally assert profile conformance (BYO — none is bundled).\n *\n * @param options - Seed, count, and the resource mix. See {@link FhirCorpusOptions}.\n * @returns A deep-frozen {@link Corpus}.\n * @example\n * ```ts\n * import { fhirCorpus } from \"@cosyte/synth/fhir\";\n * const corpus = fhirCorpus({ seed: 42, count: 6 });\n * corpus.artifacts.every((a) => a.warnings.length === 0); // spec-clean (structural)\n * ```\n */\nexport function fhirCorpus(options: FhirCorpusOptions): Corpus {\n const { seed, count = 1 } = options;\n const kinds = options.mix ?? DEFAULT_MIX;\n const seedStream = createRng(seed);\n const artifacts = Array.from({ length: count }, (_unused, i) => {\n const kind = kinds[i % kinds.length] ?? \"USCorePatient\";\n const rt = roundTrip(generateKind(kind, seedStream.nextUint32()));\n // The artifact records the findings that break spec-cleanliness — validator **errors** (empty ⇒\n // spec-clean). Advisory warnings a legal resource may carry (e.g. `REFERENCE_UNRESOLVED` on a\n // collection Bundle's external reference, or the base `dom-6` narrative best-practice) are not\n // spec-cleanliness violations and are excluded here; a caller wanting the full picture calls\n // `roundTrip` directly (it exposes both `errors` and `warnings`).\n return { format: \"fhir\" as const, kind, content: rt.content, warnings: rt.errors };\n });\n return makeCorpus(seed, artifacts);\n}\n","/**\n * Shared money helpers for the X12 generators. X12 amounts are {@link \"@cosyte/x12\".X12Decimal}, never\n * a float (float arithmetic destroys cents), so every generated charge / payment / adjustment is\n * constructed through {@link dec} — a single, tested conversion point rather than a per-generator\n * duplicate.\n *\n * @module\n */\n\nimport { X12Decimal } from \"@cosyte/x12\";\n\n/**\n * A non-null `X12Decimal` from a decimal string. Throws on an unparseable string — the generators only\n * ever pass literals or `${n}.00` strings, so the throw is a defensive guard, never a runtime path.\n *\n * @param value - A decimal string, e.g. `\"150.00\"`.\n * @returns The parsed {@link \"@cosyte/x12\".X12Decimal}.\n * @throws If `value` is not a valid X12 decimal.\n * @example\n * ```ts\n * import { dec } from \"@cosyte/synth/x12\";\n * dec(\"150.00\"); // X12Decimal\n * ```\n */\nexport function dec(value: string): X12Decimal {\n const d = X12Decimal.fromString(value);\n if (d === undefined) throw new Error(`invalid synthetic decimal: ${value}`);\n return d;\n}\n\n/**\n * A whole-dollar `${n}.00` money string.\n *\n * @param n - The whole-dollar amount.\n * @returns The `${n}.00` string.\n * @example\n * ```ts\n * import { money } from \"@cosyte/synth/x12\";\n * money(150); // \"150.00\"\n * ```\n */\nexport function money(n: number): string {\n return `${String(n)}.00`;\n}\n","/**\n * Synthetic identity for X12 healthcare transactions — every subscriber, patient, provider, and payer\n * identifier `synth` puts into an 837 / 835 / 271 is minted here, and **only** from the\n * synthetic-safety providers. X12 is uniquely identity-dense: a claim carries subscriber\n * *and* patient names, member ids, provider NPIs, a provider tax id, dates of birth, and addresses —\n * across two HL loops. The synthetic-by-construction invariant is therefore attacked hardest here, so\n * every locus below has a construction-level guarantee, not a heuristic:\n *\n * - **member id** — minted under the synthetic assigning authority (no reserved range exists; the\n * *namespace* is the guarantee).\n * - **NPI** — a deliberately **invalid Luhn** check digit, so it can never be a NPPES-issued NPI\n * ({@link ../safe/reserved.isSyntheticNpi}).\n * - **provider tax id** — emitted as an SSN (REF*SY) in the SSA **never-issued** 900-range, so it can\n * never be a real, issuable SSN (900–999 is never assigned as an SSN — the universal synthetic-safe\n * SSN convention).\n * - **name** — the shipped clearly-fake pool; **DOB / dates** — the seeded generator (no real event\n * implied); **address** — synthetic street + reserved ZIP.\n *\n * @module\n */\n\nimport type { Rng } from \"../rng/rng.js\";\nimport { safe, type SyntheticName, type SyntheticAddress } from \"../safe/index.js\";\n\n/** Synthetic trading-partner (submitter / receiver / payer id) codes — never real assigned ids. */\nconst SYNTHETIC_ORG_NAMES: readonly string[] = Object.freeze([\n \"SYNTH BILLING GROUP\",\n \"FIXTURE CLINIC INC\",\n \"PLACEHOLDER MEDICAL CTR\",\n \"SAMPLE HEALTH PARTNERS\",\n \"MOCK CARE ASSOCIATES\",\n \"PROTOTYPE PHYSICIANS LLC\",\n]);\n\n/** Synthetic payer names — clearly fictional carriers. */\nconst SYNTHETIC_PAYER_NAMES: readonly string[] = Object.freeze([\n \"SYNTHCARE HEALTH PLAN\",\n \"FIXTURE MUTUAL INSURANCE\",\n \"PLACEHOLDER BENEFIT ADMIN\",\n \"SAMPLE STATE MEDICAID\",\n \"MOCK NATIONAL INSURER\",\n]);\n\n/** A synthetic person (subscriber / patient / rendering provider) — all fields from `../safe`. */\nexport interface X12Person {\n /** Name from the shipped fake-name pool. */\n readonly person: SyntheticName;\n /** Member/cardholder id, synthetic-AA scoped (all-digit under a synthetic namespace). */\n readonly memberId: string;\n /** Date of birth `CCYYMMDD` from the seeded generator. */\n readonly dob: string;\n /** Administrative sex (X12 DMG-03 `M`/`F`). */\n readonly sex: \"M\" | \"F\";\n /** Synthetic postal address (reserved non-real ZIP). */\n readonly address: SyntheticAddress;\n}\n\n/** A synthetic billing organization — org name + invalid-Luhn NPI + never-issued-SSN tax id. */\nexport interface X12Organization {\n /** A clearly-fictional organization name. */\n readonly name: string;\n /** A 10-digit NPI with a deliberately-invalid Luhn check digit (never a real NPI). */\n readonly npi: string;\n /** The provider tax id as a never-issued (900-range) SSN — emitted at REF*SY. */\n readonly taxIdSsn: string;\n /** Synthetic postal address. */\n readonly address: SyntheticAddress;\n}\n\n/** A synthetic payer — name + a synthetic payer id (PI). */\nexport interface X12Payer {\n /** A clearly-fictional payer name. */\n readonly name: string;\n /** The payer identifier (NM1*PR*...*PI), synthetic. */\n readonly payerId: string;\n}\n\n/** The submitter / receiver trading-partner identity for the interchange envelope. */\nexport interface X12TradingPartners {\n /** ISA-06 / submitter id. */\n readonly senderId: string;\n /** ISA-08 / receiver id. */\n readonly receiverId: string;\n}\n\n/**\n * Mint a synthetic person. Fixed draw order (name → member id → DOB → sex → address) so the same seed\n * yields the same person.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link X12Person}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { x12Person } from \"@cosyte/synth/x12\";\n * const { person, memberId } = x12Person(createRng(1));\n * ```\n */\nexport function x12Person(rng: Rng): X12Person {\n const person = safe.name(rng);\n const memberId = `MBR${safe.identifier(rng, \"MB\").value}`;\n const dob = safe.dateYmd(rng, 1935, 2010);\n const sex = rng.pick([\"M\", \"F\"] as const);\n const address = safe.address(rng);\n return { person, memberId, dob, sex, address };\n}\n\n/**\n * Mint a synthetic billing organization — org name, an invalid-Luhn NPI, a never-issued-SSN tax id,\n * and an address.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link X12Organization}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { x12Organization } from \"@cosyte/synth/x12\";\n * const org = x12Organization(createRng(1)); // org.npi is invalid-Luhn; org.taxIdSsn is 900-range\n * ```\n */\nexport function x12Organization(rng: Rng): X12Organization {\n const name = rng.pick(SYNTHETIC_ORG_NAMES);\n const npiValue = safe.npi(rng);\n const taxIdSsn = safe.ssn(rng).replace(/\\D/g, \"\"); // 900-range, 9 digits, no dashes for REF*SY.\n const address = safe.address(rng);\n return { name, npi: npiValue, taxIdSsn, address };\n}\n\n/**\n * Mint a synthetic rendering/service provider **person** — a person name plus an invalid-Luhn NPI.\n *\n * @param rng - The seeded generator.\n * @returns The provider name and NPI.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { x12ProviderPerson } from \"@cosyte/synth/x12\";\n * const rendering = x12ProviderPerson(createRng(1));\n * ```\n */\nexport function x12ProviderPerson(rng: Rng): {\n readonly person: SyntheticName;\n readonly npi: string;\n} {\n const person = safe.name(rng);\n const npiValue = safe.npi(rng);\n return { person, npi: npiValue };\n}\n\n/**\n * Mint a synthetic payer — a fictional name and a synthetic payer id.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link X12Payer}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { x12Payer } from \"@cosyte/synth/x12\";\n * const payer = x12Payer(createRng(1));\n * ```\n */\nexport function x12Payer(rng: Rng): X12Payer {\n const name = rng.pick(SYNTHETIC_PAYER_NAMES);\n const payerId = `SYN${rng.digits(5)}`;\n return { name, payerId };\n}\n\n/**\n * Mint synthetic submitter/receiver trading-partner ids for the interchange envelope. These are not\n * PHI, but are kept clearly synthetic for consistency.\n *\n * @param rng - The seeded generator.\n * @returns Synthetic {@link X12TradingPartners}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { x12TradingPartners } from \"@cosyte/synth/x12\";\n * const { senderId, receiverId } = x12TradingPartners(createRng(1));\n * ```\n */\nexport function x12TradingPartners(rng: Rng): X12TradingPartners {\n return { senderId: `SYNSUB${rng.digits(3)}`, receiverId: `SYNRCV${rng.digits(3)}` };\n}\n\n/** A seeded interchange/group/transaction envelope timing + control-number bundle. */\nexport interface X12EnvelopeTiming {\n /** ISA-09 interchange date `YYMMDD`. */\n readonly interchangeDate: string;\n /** ISA-10 interchange time `HHMM`. */\n readonly interchangeTime: string;\n /** ISA-13 interchange control number (9 digits). */\n readonly interchangeControlNumber: string;\n /** GS-06 group control number. */\n readonly groupControlNumber: string;\n /** ST-02 transaction set control number (4+ digits). */\n readonly transactionSetControlNumber: string;\n /** A `CCYYMMDD` transaction/service base date (recent, seeded). */\n readonly serviceDate: string;\n}\n\n/**\n * Mint a seeded envelope timing + control-number bundle. The service/transaction date is drawn in a\n * recent plausible window (2024–2026) so a generated transaction reads like a current one; every value\n * is seeded, so the interchange is byte-reproducible.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link X12EnvelopeTiming}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { x12EnvelopeTiming } from \"@cosyte/synth/x12\";\n * const timing = x12EnvelopeTiming(createRng(1));\n * ```\n */\nexport function x12EnvelopeTiming(rng: Rng): X12EnvelopeTiming {\n const serviceDate = safe.dateYmd(rng, 2024, 2026); // CCYYMMDD\n const yy = serviceDate.slice(2, 4);\n const mmdd = serviceDate.slice(4, 8);\n const hh = String(rng.int(0, 23)).padStart(2, \"0\");\n const mi = String(rng.int(0, 59)).padStart(2, \"0\");\n return {\n interchangeDate: `${yy}${mmdd}`,\n interchangeTime: `${hh}${mi}`,\n interchangeControlNumber: rng.digits(9),\n groupControlNumber: String(rng.int(1, 99999)),\n transactionSetControlNumber: rng.digits(4),\n serviceDate,\n };\n}\n","/**\n * License-clean example code pools for X12 generation. `synth` ships only a tiny curated\n * set of **spec-example codes** — the same codes that appear in the WPC 005010 TR3 implementation-guide\n * examples and the `@cosyte/x12` builder test fixtures — never a bundled CPT/ICD/NDC table. They are\n * used purely to give a generated claim a structurally-valid code element; a consumer who needs a real\n * code set supplies their own (matching `@cosyte/terminology`'s content-free stance).\n *\n * Every code here is a *structural placeholder*: a `synth` claim may pair a diagnosis and a procedure\n * that make no clinical sense, and that is correct — `synth` exercises the *parser*, not clinical\n * coherence.\n *\n * @module\n */\n\n/** A code drawn from a pool, with the X12 qualifier that names its code system. */\nexport interface X12ExampleCode {\n /** The code value (the element or composite component). */\n readonly code: string;\n /** A short human label — documentation only, never emitted. */\n readonly label: string;\n}\n\n/**\n * HCPCS/CPT professional procedure codes (SV1-01-2, qualifier `HC`) — office-visit / lab E&M codes\n * from the 837P TR3 examples. Structural placeholders only.\n */\nexport const PROFESSIONAL_PROCEDURES: readonly X12ExampleCode[] = Object.freeze([\n { code: \"99213\", label: \"office/outpatient visit, established patient\" },\n { code: \"99214\", label: \"office/outpatient visit, established patient, moderate\" },\n { code: \"99203\", label: \"office/outpatient visit, new patient\" },\n { code: \"85025\", label: \"complete blood count with differential\" },\n { code: \"80053\", label: \"comprehensive metabolic panel\" },\n { code: \"93000\", label: \"electrocardiogram, routine\" },\n]);\n\n/** Professional procedure modifiers (SV1-01-3..6). */\nexport const PROCEDURE_MODIFIERS: readonly string[] = Object.freeze([\"25\", \"59\", \"76\", \"GT\"]);\n\n/** Place-of-service codes (CLM-05-1 / SV1-05). */\nexport const PLACES_OF_SERVICE: readonly string[] = Object.freeze([\"11\", \"22\", \"21\", \"12\", \"49\"]);\n\n/**\n * ICD-10-CM diagnosis codes (HI qualifier `ABK` principal / `ABF` secondary) — codes from the TR3\n * examples. Structural placeholders only.\n */\nexport const DIAGNOSES: readonly X12ExampleCode[] = Object.freeze([\n { code: \"J20.9\", label: \"acute bronchitis, unspecified\" },\n { code: \"E11.9\", label: \"type 2 diabetes mellitus without complications\" },\n { code: \"I10\", label: \"essential (primary) hypertension\" },\n { code: \"M54.5\", label: \"low back pain\" },\n { code: \"R07.9\", label: \"chest pain, unspecified\" },\n { code: \"Z00.00\", label: \"general adult medical exam without abnormal findings\" },\n]);\n\n/** NUBC revenue codes (837I SV2-01) — spec-example codes. */\nexport const REVENUE_CODES: readonly X12ExampleCode[] = Object.freeze([\n { code: \"0120\", label: \"room & board, semi-private\" },\n { code: \"0300\", label: \"laboratory, general\" },\n { code: \"0450\", label: \"emergency room, general\" },\n { code: \"0636\", label: \"drugs requiring detailed coding\" },\n]);\n\n/** Institutional procedure codes paired with revenue lines (837I SV2-02-2, qualifier `HC`). */\nexport const INSTITUTIONAL_PROCEDURES: readonly X12ExampleCode[] = Object.freeze([\n { code: \"99221\", label: \"initial hospital care, per day\" },\n { code: \"99231\", label: \"subsequent hospital care, per day\" },\n]);\n\n/** CDT dental procedure codes (837D SV3-01-2, qualifier `AD`) — spec-example codes. */\nexport const DENTAL_PROCEDURES: readonly X12ExampleCode[] = Object.freeze([\n { code: \"D2391\", label: \"resin-based composite, one surface, posterior\" },\n { code: \"D1110\", label: \"prophylaxis, adult\" },\n { code: \"D0120\", label: \"periodic oral evaluation\" },\n]);\n\n/** ADA tooth codes (837D TOO-02, qualifier `JP`) + surfaces (TOO-03). */\nexport const TOOTH_CODES: readonly string[] = Object.freeze([\"14\", \"3\", \"19\", \"30\"]);\n/** Tooth surface codes (TOO-03). */\nexport const TOOTH_SURFACES: readonly string[] = Object.freeze([\"M\", \"O\", \"D\", \"B\", \"L\"]);\n\n/**\n * Claim adjustment reason codes (CARC — CAS-02) paired with a group code. CARC is a public WPC code\n * list; these are the handful used in the 835 TR3 examples. Structural placeholders only.\n */\nexport const CARC_CODES: readonly string[] = Object.freeze([\"1\", \"2\", \"3\", \"45\", \"96\", \"197\"]);\n\n/** Service type codes (271 EB-03) — the public X12 code list 1365, spec-example subset. */\nexport const SERVICE_TYPE_CODES: readonly string[] = Object.freeze([\"30\", \"1\", \"35\", \"88\", \"98\"]);\n","/**\n * Spec-clean HIPAA 005010 **837** claim generation — Professional (`build837P`, TR3 005010X222A2),\n * Institutional (`build837I`, X223A3), and Dental (`build837D`, X224A2) — built through\n * `@cosyte/x12`'s domain builders so the ISA/GS/ST…SE/GE/IEA envelope, the computed HL spine, and\n * every segment are the parser's own conservative emit. Every subscriber, patient,\n * provider, and payer identifier is drawn from the synthetic-safety providers via {@link ./identity};\n * every generated 837 round-trips through `@cosyte/x12` with zero warnings.\n *\n * @module\n */\n\nimport {\n build837P,\n build837I,\n build837D,\n type X12Decimal,\n type Build837Spec,\n type Build837BillingProviderSpec,\n type Build837SubscriberSpec,\n type Build837ClaimSpec,\n type Build837ServiceLineSpec,\n type Build837EnvelopeSpec,\n type X12Interchange,\n} from \"@cosyte/x12\";\n\nimport { createRng, type Rng } from \"../rng/rng.js\";\n\nimport { dec } from \"./money.js\";\n\nimport {\n x12Person,\n x12Organization,\n x12ProviderPerson,\n x12Payer,\n x12TradingPartners,\n x12EnvelopeTiming,\n} from \"./identity.js\";\nimport {\n PROFESSIONAL_PROCEDURES,\n INSTITUTIONAL_PROCEDURES,\n DENTAL_PROCEDURES,\n REVENUE_CODES,\n DIAGNOSES,\n PLACES_OF_SERVICE,\n PROCEDURE_MODIFIERS,\n TOOTH_CODES,\n TOOTH_SURFACES,\n} from \"./example-codes.js\";\n\n/** The 837 variant to generate. */\nexport type Claim837Variant = \"P\" | \"I\" | \"D\";\n\n/** Options for {@link generate837}. */\nexport interface Generate837Options {\n /** The seed (deterministic — same seed yields a byte-identical interchange). */\n readonly seed: number;\n}\n\n/** A `CCYYMMDD` DTP date shortly before the service base date. */\nfunction serviceDtp(serviceDate: string): {\n qualifier: string;\n formatQualifier: string;\n value: string;\n} {\n return { qualifier: \"472\", formatQualifier: \"D8\", value: serviceDate };\n}\n\n/** Build the shared envelope spec from already-drawn seeded timing + trading partners. */\nfunction envelopeOf(\n partners: ReturnType<typeof x12TradingPartners>,\n timing: ReturnType<typeof x12EnvelopeTiming>,\n): Build837EnvelopeSpec {\n return {\n senderId: partners.senderId,\n receiverId: partners.receiverId,\n interchangeDate: timing.interchangeDate,\n interchangeTime: timing.interchangeTime,\n interchangeControlNumber: timing.interchangeControlNumber,\n groupControlNumber: timing.groupControlNumber,\n transactionSetControlNumber: timing.transactionSetControlNumber,\n usageIndicator: \"T\",\n };\n}\n\n/** One professional (SV1) service line + its charge. */\nfunction professionalLine(\n rng: Rng,\n serviceDate: string,\n): { line: Build837ServiceLineSpec; charge: X12Decimal } {\n const charge = dec(`${String(rng.int(75, 400))}.00`);\n const line: Build837ServiceLineSpec = {\n variant: \"P\",\n procedureQualifier: \"HC\",\n procedureCode: rng.pick(PROFESSIONAL_PROCEDURES).code,\n ...(rng.bool(0.4) ? { modifiers: [rng.pick(PROCEDURE_MODIFIERS)] } : {}),\n charge,\n unitOfMeasure: \"UN\",\n units: dec(\"1\"),\n placeOfServiceCode: rng.pick(PLACES_OF_SERVICE),\n diagnosisPointers: [\"1\"],\n dates: [serviceDtp(serviceDate)],\n };\n return { line, charge };\n}\n\n/** One institutional (SV2) service line + its charge. */\nfunction institutionalLine(\n rng: Rng,\n serviceDate: string,\n): { line: Build837ServiceLineSpec; charge: X12Decimal } {\n const charge = dec(`${String(rng.int(500, 5000))}.00`);\n const line: Build837ServiceLineSpec = {\n variant: \"I\",\n revenueCode: rng.pick(REVENUE_CODES).code,\n procedureQualifier: \"HC\",\n procedureCode: rng.pick(INSTITUTIONAL_PROCEDURES).code,\n charge,\n unitOfMeasure: \"UN\",\n units: dec(\"1\"),\n dates: [serviceDtp(serviceDate)],\n };\n return { line, charge };\n}\n\n/** One dental (SV3) service line + its charge. */\nfunction dentalLine(\n rng: Rng,\n serviceDate: string,\n): { line: Build837ServiceLineSpec; charge: X12Decimal } {\n const charge = dec(`${String(rng.int(80, 900))}.00`);\n const line: Build837ServiceLineSpec = {\n variant: \"D\",\n procedureQualifier: \"AD\",\n procedureCode: rng.pick(DENTAL_PROCEDURES).code,\n charge,\n units: dec(\"1\"),\n placeOfServiceCode: \"11\",\n toothInformation: [\n { qualifier: \"JP\", toothCode: rng.pick(TOOTH_CODES), surfaces: [rng.pick(TOOTH_SURFACES)] },\n ],\n dates: [serviceDtp(serviceDate)],\n };\n return { line, charge };\n}\n\n/** Build one claim of the given variant with 1–2 service lines; `totalCharge` = Σ line charges. */\nfunction claimOf(rng: Rng, variant: Claim837Variant, serviceDate: string): Build837ClaimSpec {\n const lineCount = rng.int(1, 2);\n const built = Array.from({ length: lineCount }, () => {\n if (variant === \"P\") return professionalLine(rng, serviceDate);\n if (variant === \"I\") return institutionalLine(rng, serviceDate);\n return dentalLine(rng, serviceDate);\n });\n const total = built.reduce((acc, b) => acc.add(b.charge), dec(\"0\"));\n const diagnosis = rng.pick(DIAGNOSES).code;\n const secondary = rng.pick(DIAGNOSES).code;\n return {\n claimId: `PTACCT${rng.digits(6)}`,\n totalCharge: total,\n placeOfServiceCode: variant === \"P\" ? rng.pick(PLACES_OF_SERVICE) : \"11\",\n facilityCodeQualifier: \"B\",\n claimFrequencyCode: \"1\",\n providerSignatureOnFile: \"Y\",\n providerAcceptAssignment: \"A\",\n benefitsAssignment: \"Y\",\n releaseOfInformationCode: \"Y\",\n diagnoses: [\n { qualifier: \"ABK\", code: diagnosis },\n { qualifier: \"ABF\", code: secondary },\n ],\n dates: [{ qualifier: \"431\", formatQualifier: \"D8\", value: serviceDate }],\n serviceLines: built.map((b) => b.line),\n };\n}\n\n/** Assemble the full nested 837 spec (billing provider → subscriber → claim) from synthetic identity. */\nfunction specOf(rng: Rng, variant: Claim837Variant): Build837Spec {\n const partners = x12TradingPartners(rng);\n const timing = x12EnvelopeTiming(rng);\n const envelope = envelopeOf(partners, timing);\n const org = x12Organization(rng);\n const subscriberPerson = x12Person(rng);\n const rendering = x12ProviderPerson(rng);\n const payer = x12Payer(rng);\n\n const claim = claimOf(rng, variant, timing.serviceDate);\n\n const subscriber: Build837SubscriberSpec = {\n info: {\n payerResponsibilityCode: \"P\",\n individualRelationshipCode: \"18\", // self\n groupNumber: `GRP${rng.digits(5)}`,\n claimFilingIndicator: \"MB\",\n },\n subscriber: {\n entityIdentifierCode: \"IL\",\n entityTypeQualifier: \"1\",\n name: subscriberPerson.person.family,\n firstName: subscriberPerson.person.given,\n idQualifier: \"MI\",\n idCode: subscriberPerson.memberId,\n address: {\n lines: [subscriberPerson.address.street],\n city: subscriberPerson.address.city,\n state: subscriberPerson.address.state,\n postalCode: subscriberPerson.address.zip,\n },\n },\n payer: {\n entityIdentifierCode: \"PR\",\n entityTypeQualifier: \"2\",\n name: payer.name,\n idQualifier: \"PI\",\n idCode: payer.payerId,\n },\n claims: [\n {\n ...claim,\n // Rendering provider (Loop 2310B, NM1 fields round-trip) — a person with an invalid-Luhn NPI.\n providers: [\n {\n entityIdentifierCode: \"82\",\n entityTypeQualifier: \"1\",\n name: rendering.person.family,\n firstName: rendering.person.given,\n idQualifier: \"XX\",\n idCode: rendering.npi,\n },\n ],\n },\n ],\n };\n\n const billingProvider: Build837BillingProviderSpec = {\n provider: {\n entityIdentifierCode: \"85\",\n entityTypeQualifier: \"2\",\n name: org.name,\n idQualifier: \"XX\",\n idCode: org.npi,\n address: {\n lines: [org.address.street],\n city: org.address.city,\n state: org.address.state,\n postalCode: org.address.zip,\n },\n // Provider tax id as a never-issued (900-range) SSN at REF*SY — provably synthetic (roadmap §4.1).\n references: [{ qualifier: \"SY\", value: org.taxIdSsn }],\n },\n subscribers: [subscriber],\n };\n\n return {\n envelope,\n submitter: {\n entityIdentifierCode: \"41\",\n entityTypeQualifier: \"2\",\n name: org.name,\n idQualifier: \"46\",\n idCode: envelope.senderId,\n },\n receiver: {\n entityIdentifierCode: \"40\",\n entityTypeQualifier: \"2\",\n name: payer.name,\n idQualifier: \"46\",\n idCode: envelope.receiverId,\n },\n billingProviders: [billingProvider],\n };\n}\n\n/**\n * Generate a spec-clean 005010 837 claim of the given `variant`, built through `@cosyte/x12`'s\n * `build837P` / `build837I` / `build837D`. Every identity value is synthetic-by-construction; the returned\n * interchange round-trips through `@cosyte/x12` with zero warnings.\n *\n * @param variant - `\"P\"` professional, `\"I\"` institutional, or `\"D\"` dental.\n * @param options - The seed. See {@link Generate837Options}.\n * @returns A frozen `X12Interchange` (feed it to {@link ./round-trip.roundTrip} to verify).\n * @example\n * ```ts\n * import { generate837, roundTrip } from \"@cosyte/synth/x12\";\n * const { specClean } = roundTrip(generate837(\"P\", { seed: 42 }));\n * // specClean === true\n * ```\n */\nexport function generate837(variant: Claim837Variant, options: Generate837Options): X12Interchange {\n const rng = createRng(options.seed);\n const spec = specOf(rng, variant);\n if (variant === \"P\") return build837P(spec);\n if (variant === \"I\") return build837I(spec);\n return build837D(spec);\n}\n\n/**\n * Generate a spec-clean 837**P** (Professional) claim.\n *\n * @param options - The seed.\n * @returns A frozen `X12Interchange`.\n * @example\n * ```ts\n * import { generate837P } from \"@cosyte/synth/x12\";\n * const ix = generate837P({ seed: 1 });\n * ```\n */\nexport function generate837P(options: Generate837Options): X12Interchange {\n return generate837(\"P\", options);\n}\n\n/**\n * Generate a spec-clean 837**I** (Institutional) claim.\n *\n * @param options - The seed.\n * @returns A frozen `X12Interchange`.\n * @example\n * ```ts\n * import { generate837I } from \"@cosyte/synth/x12\";\n * const ix = generate837I({ seed: 1 });\n * ```\n */\nexport function generate837I(options: Generate837Options): X12Interchange {\n return generate837(\"I\", options);\n}\n\n/**\n * Generate a spec-clean 837**D** (Dental) claim.\n *\n * @param options - The seed.\n * @returns A frozen `X12Interchange`.\n * @example\n * ```ts\n * import { generate837D } from \"@cosyte/synth/x12\";\n * const ix = generate837D({ seed: 1 });\n * ```\n */\nexport function generate837D(options: Generate837Options): X12Interchange {\n return generate837(\"D\", options);\n}\n","/**\n * Spec-clean HIPAA 005010X221A1 **835** Health Care Claim Payment/Advice (ERA) generation, built\n * through `@cosyte/x12`'s `build835`. The 835 is **balance-checked by construction**:\n * `build835` REFUSES an out-of-balance remit, so `synth` computes amounts that satisfy the three X12\n * balance identities — line (`charge = payment + Σ CAS`), claim (`totalCharge = totalPayment +\n * patientResponsibility`), and remit (`BPR-02 = Σ CLP-04 − Σ PLB`) — before handing them to the\n * builder. Patient, payer, and payee identity is drawn from the synthetic-safety providers\n * ({@link ./identity}); every generated 835 round-trips through `@cosyte/x12` with zero warnings.\n *\n * @module\n */\n\nimport {\n build835,\n type Build835Spec,\n type Build835ClaimSpec,\n type Build835ServiceLineSpec,\n type X12Interchange,\n} from \"@cosyte/x12\";\n\nimport { createRng } from \"../rng/rng.js\";\n\nimport { dec, money } from \"./money.js\";\n\nimport {\n x12Person,\n x12Organization,\n x12Payer,\n x12TradingPartners,\n x12EnvelopeTiming,\n} from \"./identity.js\";\nimport { PROFESSIONAL_PROCEDURES, PROCEDURE_MODIFIERS } from \"./example-codes.js\";\n\n/** Options for {@link generate835}. */\nexport interface Generate835Options {\n /** The seed (deterministic — same seed yields a byte-identical interchange). */\n readonly seed: number;\n}\n\n/**\n * Generate a spec-clean 005010X221A1 835 remittance, built through `@cosyte/x12`'s `build835`. A single\n * balanced claim with one service line: `charge = payment + patientResponsibility`, and the remit\n * total equals the claim payment (no provider-level adjustments). Every identity value is\n * synthetic-by-construction; the returned interchange round-trips with zero warnings.\n *\n * @param options - The seed. See {@link Generate835Options}.\n * @returns A frozen `X12Interchange` (feed it to {@link ./round-trip.roundTrip} to verify).\n * @example\n * ```ts\n * import { generate835, roundTrip } from \"@cosyte/synth/x12\";\n * const { specClean } = roundTrip(generate835({ seed: 7 }));\n * // specClean === true\n * ```\n */\nexport function generate835(options: Generate835Options): X12Interchange {\n const rng = createRng(options.seed);\n const partners = x12TradingPartners(rng);\n const timing = x12EnvelopeTiming(rng);\n const patient = x12Person(rng);\n const org = x12Organization(rng); // the payee (rendering clinic)\n const payer = x12Payer(rng);\n\n // Balanced amounts: charge = payment + patient responsibility (the single CAS adjustment).\n const chargeN = rng.int(200, 2000);\n const patientRespN = rng.int(10, Math.min(chargeN - 1, 150));\n const paymentN = chargeN - patientRespN;\n const casReason = rng.pick([\"1\", \"2\", \"3\"] as const); // deductible / coinsurance / copay\n\n const line: Build835ServiceLineSpec = {\n productServiceIdQualifier: \"HC\",\n productServiceId: rng.pick(PROFESSIONAL_PROCEDURES).code,\n ...(rng.bool(0.4) ? { modifiers: [rng.pick(PROCEDURE_MODIFIERS)] } : {}),\n chargeAmount: dec(money(chargeN)),\n paymentAmount: dec(money(paymentN)),\n serviceDateStart: timing.serviceDate,\n serviceDateEnd: timing.serviceDate,\n adjustments: [{ groupCode: \"PR\", reasonCode: casReason, amount: dec(money(patientRespN)) }],\n amounts: [{ qualifier: \"B6\", amount: dec(money(paymentN)) }],\n };\n\n const claim: Build835ClaimSpec = {\n patientControlNumber: `PTACCT${rng.digits(6)}`,\n claimStatusCode: \"1\", // processed as primary\n totalChargeAmount: dec(money(chargeN)),\n totalPaymentAmount: dec(money(paymentN)),\n patientResponsibilityAmount: dec(money(patientRespN)),\n claimFilingIndicatorCode: \"MB\",\n payerClaimControlNumber: `ICN${rng.digits(9)}`,\n facilityTypeCode: \"11\",\n claimFrequencyCode: \"1\",\n patient: {\n entityIdentifierCode: \"QC\",\n lastName: patient.person.family,\n firstName: patient.person.given,\n idQualifier: \"MI\",\n idCode: patient.memberId,\n },\n serviceProvider: {\n entityIdentifierCode: \"82\",\n name: org.name,\n idQualifier: \"XX\",\n idCode: org.npi,\n },\n servicePeriodStart: timing.serviceDate,\n servicePeriodEnd: timing.serviceDate,\n serviceLines: [line],\n };\n\n const spec: Build835Spec = {\n envelope: {\n senderId: partners.senderId,\n receiverId: partners.receiverId,\n interchangeDate: timing.interchangeDate,\n interchangeTime: timing.interchangeTime,\n interchangeControlNumber: timing.interchangeControlNumber,\n groupControlNumber: timing.groupControlNumber,\n transactionSetControlNumber: timing.transactionSetControlNumber,\n usageIndicator: \"T\",\n },\n payment: {\n transactionHandlingCode: \"I\",\n totalActualPayment: dec(money(paymentN)),\n creditDebitFlag: \"C\",\n method: \"ACH\",\n paymentDate: timing.serviceDate,\n },\n traces: [\n {\n traceTypeCode: \"1\",\n referenceId: rng.digits(7),\n originatingCompanyId: `1${rng.digits(9)}`,\n },\n ],\n payer: {\n entityIdentifierCode: \"PR\",\n name: payer.name,\n address: {\n lines: [org.address.street],\n city: org.address.city,\n state: org.address.state,\n postalCode: org.address.zip,\n },\n additionalIdentifiers: [{ qualifier: \"2U\", value: payer.payerId }],\n },\n payee: {\n entityIdentifierCode: \"PE\",\n name: org.name,\n idQualifier: \"XX\",\n idCode: org.npi,\n address: {\n lines: [org.address.street],\n city: org.address.city,\n state: org.address.state,\n postalCode: org.address.zip,\n },\n },\n claims: [claim],\n };\n\n return build835(spec);\n}\n","/**\n * Spec-clean HIPAA 005010X279A1 **271** Health Care Eligibility Benefit Response generation, built\n * through `@cosyte/x12`'s `build271`. The 271 carries subscriber identity (name,\n * member id, DOB, address) plus benefit information across the 20→21→22 HL hierarchy; every identity\n * value is drawn from the synthetic-safety providers ({@link ./identity}). Every generated 271\n * round-trips through `@cosyte/x12` with zero warnings.\n *\n * **Note (coverage tracks the builder):** `@cosyte/x12` ships a **271** builder but no\n * **270** (request) builder — the 270 is only *read* (as the echoed trace on the 271). Per the\n * through-the-builder discipline (never hand-write bytes around a missing builder), `synth` generates\n * the 271 and **defers 270** until `@cosyte/x12` grows a `build270` (noted in the README + CHANGELOG).\n *\n * @module\n */\n\nimport { build271, type Build271Spec, type X12Interchange } from \"@cosyte/x12\";\n\nimport { createRng } from \"../rng/rng.js\";\n\nimport { dec, money } from \"./money.js\";\n\nimport {\n x12Person,\n x12Organization,\n x12Payer,\n x12TradingPartners,\n x12EnvelopeTiming,\n} from \"./identity.js\";\nimport { SERVICE_TYPE_CODES } from \"./example-codes.js\";\n\n/** Options for {@link generate271}. */\nexport interface Generate271Options {\n /** The seed (deterministic — same seed yields a byte-identical interchange). */\n readonly seed: number;\n}\n\n/**\n * Generate a spec-clean 005010X279A1 271 eligibility response, built through `@cosyte/x12`'s\n * `build271`: one information source (payer) → one information receiver (provider) → one subscriber\n * with an active-coverage benefit. Every identity value is synthetic-by-construction; the\n * returned interchange round-trips with zero warnings.\n *\n * @param options - The seed. See {@link Generate271Options}.\n * @returns A frozen `X12Interchange` (feed it to {@link ./round-trip.roundTrip} to verify).\n * @example\n * ```ts\n * import { generate271, roundTrip } from \"@cosyte/synth/x12\";\n * const { specClean } = roundTrip(generate271({ seed: 3 }));\n * // specClean === true\n * ```\n */\nexport function generate271(options: Generate271Options): X12Interchange {\n const rng = createRng(options.seed);\n const partners = x12TradingPartners(rng);\n const timing = x12EnvelopeTiming(rng);\n const subscriber = x12Person(rng);\n const providerOrg = x12Organization(rng);\n const payer = x12Payer(rng);\n\n const serviceTypes = [\n { code: rng.pick(SERVICE_TYPE_CODES) },\n { code: rng.pick(SERVICE_TYPE_CODES) },\n ];\n\n const spec: Build271Spec = {\n envelope: {\n senderId: partners.senderId,\n receiverId: partners.receiverId,\n interchangeDate: timing.interchangeDate,\n interchangeTime: timing.interchangeTime,\n interchangeControlNumber: timing.interchangeControlNumber,\n groupControlNumber: timing.groupControlNumber,\n transactionSetControlNumber: timing.transactionSetControlNumber,\n usageIndicator: \"T\",\n },\n informationSources: [\n {\n entity: {\n entityIdentifierCode: \"PR\",\n entityTypeQualifier: \"2\",\n name: payer.name,\n idQualifier: \"PI\",\n idCode: payer.payerId,\n },\n receivers: [\n {\n entity: {\n entityIdentifierCode: \"1P\",\n entityTypeQualifier: \"2\",\n name: providerOrg.name,\n idQualifier: \"XX\",\n idCode: providerOrg.npi,\n },\n subscribers: [\n {\n traces: [{ traceTypeCode: \"2\", referenceId: `ELIG${rng.digits(10)}` }],\n name: {\n entityIdentifierCode: \"IL\",\n entityTypeQualifier: \"1\",\n lastName: subscriber.person.family,\n firstName: subscriber.person.given,\n idQualifier: \"MI\",\n idCode: subscriber.memberId,\n address: {\n lines: [subscriber.address.street],\n city: subscriber.address.city,\n state: subscriber.address.state,\n postalCode: subscriber.address.zip,\n },\n dateOfBirth: subscriber.dob,\n genderCode: subscriber.sex,\n },\n references: [{ qualifier: \"6P\", value: `GRP${rng.digits(5)}` }],\n dates: [{ qualifier: \"307\", formatQualifier: \"D8\", value: timing.serviceDate }],\n benefits: [\n {\n eligibilityCode: \"1\", // active coverage\n coverageLevelCode: \"IND\",\n serviceTypeCodes: serviceTypes,\n inPlanNetwork: \"Y\",\n monetaryAmount: dec(money(rng.int(500, 5000))),\n percent: dec(String(rng.pick([80, 90, 100] as const))),\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n };\n\n return build271(spec);\n}\n","/**\n * Synthetic identity for NCPDP transactions — every patient, prescriber, pharmacy, and cardholder\n * identifier `synth` puts into a SCRIPT ePrescription or a Telecom claim is minted here, and **only**\n * from the synthetic-safety providers. NCPDP is identity-dense in a way the refuter\n * attacks hardest: a NewRx carries the **patient** (name, DOB, gender) *and* the **prescriber** (name,\n * NPI, **DEA**); a Telecom claim adds the **cardholder / member** (name, member id). Every locus below\n * has a construction-level guarantee, not a heuristic:\n *\n * - **NPI** — a deliberately **invalid Luhn** check digit, so it can never be a NPPES-issued NPI\n * ({@link ../safe/reserved.isSyntheticNpi}).\n * - **DEA** — a deliberately **invalid checksum**, so it can never be a validly-issued DEA registration\n * ({@link ../safe/reserved.isSyntheticDea}). This is the NCPDP-specific identity locus X12 did not have.\n * - **member / cardholder / patient id** — minted under the synthetic assigning authority with an\n * `MBR` prefix (no reserved range exists; the *namespace* is the guarantee).\n * - **name** — the shipped clearly-fake pool; **DOB** — the seeded generator (no real event implied);\n * **phone** — the reserved `555-01xx` block; **address** — synthetic street + reserved ZIP.\n *\n * @module\n */\n\nimport type { Rng } from \"../rng/rng.js\";\nimport { safe, type SyntheticName, type SyntheticAddress } from \"../safe/index.js\";\n\n/** Synthetic pharmacy business names — clearly fictional. */\nconst SYNTHETIC_PHARMACY_NAMES: readonly string[] = Object.freeze([\n \"SYNTH COMMUNITY PHARMACY\",\n \"FIXTURE DRUG MART\",\n \"PLACEHOLDER RX SERVICES\",\n \"SAMPLE APOTHECARY LLC\",\n \"MOCK PHARMACY GROUP\",\n]);\n\n/** A synthetic patient — every field from `../safe`. */\nexport interface NcpdpPatient {\n /** Name from the shipped fake-name pool. */\n readonly person: SyntheticName;\n /** Date of birth `CCYYMMDD` from the seeded generator. */\n readonly dob: string;\n /** Administrative gender code (`1` = male, `2` = female — NCPDP gender codes). */\n readonly gender: \"1\" | \"2\";\n /** Patient id, synthetic-AA scoped (`MBR`-prefixed — never a bare SSN). */\n readonly patientId: string;\n /** Reserved `555-01xx` phone. */\n readonly phone: string;\n /** Synthetic postal address (reserved non-real ZIP). */\n readonly address: SyntheticAddress;\n}\n\n/** A synthetic prescriber — name + invalid-Luhn NPI + invalid-checksum DEA. */\nexport interface NcpdpPrescriber {\n /** A clearly-fake prescriber name. */\n readonly person: SyntheticName;\n /** A 10-digit NPI with a deliberately-invalid Luhn check digit (never a real NPI). */\n readonly npi: string;\n /** A DEA number with a deliberately-invalid checksum (never a real DEA registration). */\n readonly dea: string;\n}\n\n/** A synthetic dispensing pharmacy — business name + invalid-Luhn NPI + synthetic NCPDP id. */\nexport interface NcpdpPharmacy {\n /** A clearly-fictional pharmacy business name. */\n readonly businessName: string;\n /** A 10-digit NPI with a deliberately-invalid Luhn check digit. */\n readonly npi: string;\n /** A 7-digit NCPDP provider id (synthetic — an all-digit id under no real chain). */\n readonly ncpdpId: string;\n}\n\n/** A synthetic cardholder / insurance identity — the covered person on a Telecom claim. */\nexport interface NcpdpCardholder {\n /** The cardholder name (may differ from the patient). */\n readonly person: SyntheticName;\n /** Cardholder / member id, synthetic-AA scoped (`MBR`-prefixed). */\n readonly cardholderId: string;\n /** Group id, synthetic. */\n readonly groupId: string;\n /** Person code (`01` = cardholder, `02` = spouse, `03` = child — structural). */\n readonly personCode: string;\n}\n\n/**\n * Mint a synthetic patient. Fixed draw order (name → DOB → gender → id → phone → address) so the same\n * seed yields the same patient.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link NcpdpPatient}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { ncpdpPatient } from \"@cosyte/synth/ncpdp\";\n * const { person, patientId } = ncpdpPatient(createRng(1));\n * ```\n */\nexport function ncpdpPatient(rng: Rng): NcpdpPatient {\n const person = safe.name(rng);\n const dob = safe.dateYmd(rng, 1935, 2010);\n const gender = rng.pick([\"1\", \"2\"] as const);\n const patientId = `MBR${safe.identifier(rng, \"MR\").value}`;\n const phone = safe.phone(rng);\n const address = safe.address(rng);\n return { person, dob, gender, patientId, phone, address };\n}\n\n/**\n * Mint a synthetic prescriber — a person name, an invalid-Luhn NPI, and an invalid-checksum DEA (the\n * DEA's second letter is derived from the prescriber's family name so it reads plausibly).\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link NcpdpPrescriber}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { ncpdpPrescriber } from \"@cosyte/synth/ncpdp\";\n * const p = ncpdpPrescriber(createRng(1)); // p.npi invalid-Luhn; p.dea invalid-checksum\n * ```\n */\nexport function ncpdpPrescriber(rng: Rng): NcpdpPrescriber {\n const person = safe.name(rng);\n const npi = safe.npi(rng);\n const dea = safe.dea(rng, person);\n return { person, npi, dea };\n}\n\n/**\n * Mint a synthetic dispensing pharmacy — a fictional business name, an invalid-Luhn NPI, and a 7-digit\n * synthetic NCPDP provider id.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link NcpdpPharmacy}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { ncpdpPharmacy } from \"@cosyte/synth/ncpdp\";\n * const rx = ncpdpPharmacy(createRng(1));\n * ```\n */\nexport function ncpdpPharmacy(rng: Rng): NcpdpPharmacy {\n const businessName = rng.pick(SYNTHETIC_PHARMACY_NAMES);\n const npi = safe.npi(rng);\n const ncpdpId = rng.digits(7);\n return { businessName, npi, ncpdpId };\n}\n\n/**\n * Mint a synthetic cardholder / insurance identity for a Telecom claim.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link NcpdpCardholder}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { ncpdpCardholder } from \"@cosyte/synth/ncpdp\";\n * const c = ncpdpCardholder(createRng(1));\n * ```\n */\nexport function ncpdpCardholder(rng: Rng): NcpdpCardholder {\n const person = safe.name(rng);\n const cardholderId = `MBR${safe.identifier(rng, \"MB\").value}`;\n const groupId = `GRP${rng.digits(5)}`;\n const personCode = rng.pick([\"01\", \"02\", \"03\"] as const);\n return { person, cardholderId, groupId, personCode };\n}\n\n/** A seeded SCRIPT routing/correlation bundle — message ids + timestamps, all reproducible. */\nexport interface NcpdpScriptRouting {\n /** `<MessageID>` — a synthetic message id. */\n readonly messageId: string;\n /** `<SentTime>` — a seeded ISO-8601 timestamp (never wall-clock). */\n readonly sentTime: string;\n /** `<PrescriberOrderNumber>` — a synthetic order number. */\n readonly prescriberOrderNumber: string;\n /** A `CCYYMMDD` written / service date (seeded, recent window). */\n readonly date: string;\n}\n\n/**\n * Mint a seeded SCRIPT routing bundle. The timestamp is drawn from the seeded generator in a recent\n * window (2024–2026) so a message reads current while staying byte-reproducible.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link NcpdpScriptRouting}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { ncpdpScriptRouting } from \"@cosyte/synth/ncpdp\";\n * const r = ncpdpScriptRouting(createRng(1));\n * ```\n */\nexport function ncpdpScriptRouting(rng: Rng): NcpdpScriptRouting {\n const date = safe.dateYmd(rng, 2024, 2026); // CCYYMMDD\n const yyyy = date.slice(0, 4);\n const mm = date.slice(4, 6);\n const dd = date.slice(6, 8);\n const hh = String(rng.int(0, 23)).padStart(2, \"0\");\n const mi = String(rng.int(0, 59)).padStart(2, \"0\");\n return {\n messageId: `SYNTH-${rng.digits(10)}`,\n sentTime: `${yyyy}-${mm}-${dd}T${hh}:${mi}:00Z`,\n prescriberOrderNumber: `PON${rng.digits(8)}`,\n date,\n };\n}\n","/**\n * License-clean example drug + code pools for synthetic NCPDP generation. NCPDP charges for its\n * standards and is protective of their prose, so — like every other `synth` format — **no NCPDP\n * copyrighted text is bundled**: these are widely-known generic drug descriptions and invented,\n * clearly-example product codes, not lifted from any NCPDP data dictionary.\n *\n * A drug code is **not** PHI — it names a product, never a patient — so realism here carries no\n * synthetic-safety hazard; the pool exists only to give a generated NewRx / claim a plausible,\n * license-clean drug. Patient / prescriber identity comes from the synthetic-safety providers\n * (`../safe`), never from here.\n *\n * `# synthetic: true`\n *\n * @module\n */\n\n/** One example drug: a widely-known generic description + an invented, clearly-example NDC. */\nexport interface NcpdpExampleDrug {\n /** A widely-known generic drug description (RxNorm-style; public knowledge, not NCPDP prose). */\n readonly description: string;\n /** An invented 11-digit NDC (`5-4-2`, digits only) — an example product code, never a real NDC. */\n readonly ndc: string;\n /** The dispense quantity unit-of-measure qualifier hint (structural only). */\n readonly form: string;\n}\n\n/**\n * A small pool of license-clean example drugs. The NDCs use the invented labeler prefix `00000`\n * (never an FDA-assigned labeler), so they are transparently examples; the descriptions are common\n * generics anyone can name without a licensed database.\n */\nexport const EXAMPLE_DRUGS: readonly NcpdpExampleDrug[] = Object.freeze([\n { description: \"Amoxicillin 500 MG Oral Capsule\", ndc: \"00000010101\", form: \"EA\" },\n { description: \"Lisinopril 10 MG Oral Tablet\", ndc: \"00000020202\", form: \"EA\" },\n { description: \"Atorvastatin 20 MG Oral Tablet\", ndc: \"00000030303\", form: \"EA\" },\n { description: \"Metformin 500 MG Oral Tablet\", ndc: \"00000040404\", form: \"EA\" },\n { description: \"Amlodipine 5 MG Oral Tablet\", ndc: \"00000050505\", form: \"EA\" },\n { description: \"Omeprazole 20 MG Delayed Release Capsule\", ndc: \"00000060606\", form: \"EA\" },\n { description: \"Levothyroxine 50 MCG Oral Tablet\", ndc: \"00000070707\", form: \"EA\" },\n { description: \"Azithromycin 250 MG Oral Tablet\", ndc: \"00000080808\", form: \"EA\" },\n { description: \"Sertraline 50 MG Oral Tablet\", ndc: \"00000090909\", form: \"EA\" },\n { description: \"Albuterol 90 MCG Metered Dose Inhaler\", ndc: \"00000101010\", form: \"EA\" },\n]);\n\n/** Example free-text SIG directions (public, common-sense dosing text — not NCPDP prose). */\nexport const EXAMPLE_SIG_TEXT: readonly string[] = Object.freeze([\n \"Take 1 tablet by mouth once daily\",\n \"Take 1 capsule by mouth twice daily with food\",\n \"Take 2 tablets by mouth every 12 hours as needed\",\n \"Take 1 tablet by mouth at bedtime\",\n \"Inhale 2 puffs by mouth every 4 to 6 hours as needed\",\n]);\n\n/** Dispense-as-written / product-selection codes (single-digit, structural). */\nexport const DAW_CODES: readonly string[] = Object.freeze([\"0\", \"1\", \"2\"]);\n","/**\n * Spec-clean NCPDP **Telecommunication vD.0** claim generation — `B1` (billing), `B2` (reversal), and\n * `B3` (rebill) — built through `@cosyte/ncpdp`'s `buildTelecomRequest` + `serializeTelecom` so the\n * fixed Transaction Header, the FS/GS/RS framing, and every field are the parser's own conservative\n * emit. Every field id below is a real 2-character NCPDP field identifier, and every\n * value at a PHI-bearing locus is drawn from the synthetic-safety providers via {@link ./identity}: the\n * patient / cardholder names come from the fake-name pool, the DOB / dates from the seeded generator,\n * the phone from the reserved `555-01xx` block, the member / cardholder ids under the synthetic\n * assigning authority, and the prescriber NPI with an invalid Luhn check digit. Each transaction\n * round-trips through `parseTelecom` with zero warnings.\n *\n * @module\n */\n\nimport {\n buildTelecomRequest,\n serializeTelecom,\n type TelecomHeaderInput,\n type TelecomSegmentInput,\n type TelecomFieldInput,\n} from \"@cosyte/ncpdp/telecom\";\n\nimport { createRng, type Rng } from \"../rng/rng.js\";\nimport { ncpdpPatient, ncpdpCardholder, ncpdpPharmacy, ncpdpPrescriber } from \"./identity.js\";\nimport { EXAMPLE_DRUGS, DAW_CODES } from \"./example-codes.js\";\n\n/** The Telecom transaction codes `synth` generates. */\nexport type TelecomTransactionCode = \"B1\" | \"B2\" | \"B3\";\n\n/** A synthetic routing BIN (an ISO/IIN routing number — not patient identity, kept clearly synthetic). */\nconst SYNTHETIC_BIN = \"999999\";\n\n/** Options for the Telecom generators. */\nexport interface GenerateTelecomOptions {\n /** The seed (deterministic — same seed yields a byte-identical transaction). */\n readonly seed: number;\n}\n\n/** Drop any incidental separators; keep the compact wire value (never carries FS/GS/RS). */\nfunction digitsOnly(value: string): string {\n return value.replace(/\\D/g, \"\");\n}\n\n/** Build the fixed Transaction Header for the given transaction code, from seeded identity. */\nfunction header(\n rng: Rng,\n transactionCode: TelecomTransactionCode,\n pharmacyNpi: string,\n): TelecomHeaderInput {\n const date = serviceDate(rng);\n return {\n binNumber: SYNTHETIC_BIN,\n versionRelease: \"D0\",\n transactionCode,\n processorControlNumber: `SYN${rng.digits(4)}`,\n transactionCount: \"1\",\n serviceProviderIdQualifier: \"01\", // 01 = NPI\n serviceProviderId: pharmacyNpi,\n dateOfService: date,\n softwareCertificationId: `SW${rng.digits(6)}`,\n };\n}\n\n/** A seeded `CCYYMMDD` service date in a recent window. */\nfunction serviceDate(rng: Rng): string {\n const year = rng.int(2024, 2026);\n const month = rng.int(1, 12);\n const day = rng.int(1, 28);\n return `${String(year)}${String(month).padStart(2, \"0\")}${String(day).padStart(2, \"0\")}`;\n}\n\n/** A field pair; dropped when the value is empty so no empty field is emitted. */\nfunction field(id: string, value: string): TelecomFieldInput {\n return { id, value };\n}\n\n/** The Patient segment (01) — CA/CB name, C4 DOB, C5 gender, CM address, CQ phone, CY patient id. */\nfunction patientSegment(rng: Rng): TelecomSegmentInput {\n const p = ncpdpPatient(rng);\n return {\n segmentId: \"01\",\n fields: [\n field(\"C4\", p.dob),\n field(\"C5\", p.gender),\n field(\"CA\", p.person.given),\n field(\"CB\", p.person.family),\n field(\"CM\", p.address.street),\n field(\"CQ\", digitsOnly(p.phone)),\n field(\"CY\", p.patientId),\n ],\n };\n}\n\n/** The Insurance segment (04) — C2 cardholder id, C1 group, C3 person code, CC/CD cardholder name. */\nfunction insuranceSegment(rng: Rng): TelecomSegmentInput {\n const c = ncpdpCardholder(rng);\n return {\n segmentId: \"04\",\n fields: [\n field(\"C2\", c.cardholderId),\n field(\"C1\", c.groupId),\n field(\"C3\", c.personCode),\n field(\"CC\", c.person.given),\n field(\"CD\", c.person.family),\n ],\n };\n}\n\n/** The Prescriber segment (03) — DB prescriber id (NPI), EZ qualifier (`01` = NPI). */\nfunction prescriberSegment(rng: Rng): TelecomSegmentInput {\n const dr = ncpdpPrescriber(rng);\n return {\n segmentId: \"03\",\n fields: [field(\"EZ\", \"01\"), field(\"DB\", dr.npi)],\n };\n}\n\n/** The Claim segment (07) — Rx ref, product (NDC), quantity, days supply, DAW. `minimal` for a reversal. */\nfunction claimSegment(rng: Rng, minimal: boolean): TelecomSegmentInput {\n const drug = rng.pick(EXAMPLE_DRUGS);\n const rxRef = `RX${rng.digits(7)}`;\n const fill = String(rng.int(0, 5));\n if (minimal) {\n return {\n segmentId: \"07\",\n fields: [field(\"EM\", \"1\"), field(\"D2\", rxRef), field(\"D3\", fill)],\n };\n }\n return {\n segmentId: \"07\",\n fields: [\n field(\"EM\", \"1\"), // 1 = Rx Billing\n field(\"D2\", rxRef),\n field(\"D3\", fill),\n field(\"E1\", \"03\"), // 03 = NDC\n field(\"D7\", drug.ndc),\n field(\"E7\", String(rng.int(30, 90))),\n field(\"D5\", String(rng.pick([30, 60, 90] as const))),\n field(\"D8\", rng.pick(DAW_CODES)),\n ],\n };\n}\n\n/**\n * Generate a spec-clean Telecom transaction of the given code, built through\n * `@cosyte/ncpdp`'s `buildTelecomRequest` + `serializeTelecom`. `B1`/`B3` carry the full\n * patient / insurance / prescriber / claim segment set; `B2` (reversal) is the minimal\n * insurance + claim-reference set a reversal actually carries. Every identity value is\n * synthetic-by-construction; the transaction round-trips through `parseTelecom` with zero\n * warnings.\n *\n * @param code - `\"B1\"` billing, `\"B2\"` reversal, or `\"B3\"` rebill.\n * @param options - The seed. See {@link GenerateTelecomOptions}.\n * @returns The serialized Telecom wire string.\n * @example\n * ```ts\n * import { generateTelecom } from \"@cosyte/synth/ncpdp\";\n * const wire = generateTelecom(\"B1\", { seed: 42 });\n * ```\n */\nexport function generateTelecom(\n code: TelecomTransactionCode,\n options: GenerateTelecomOptions,\n): string {\n const rng = createRng(options.seed);\n const pharmacy = ncpdpPharmacy(rng);\n const head = header(rng, code, pharmacy.npi);\n const segments: TelecomSegmentInput[] =\n code === \"B2\"\n ? [insuranceSegment(rng), claimSegment(rng, true)]\n : [\n patientSegment(rng),\n insuranceSegment(rng),\n prescriberSegment(rng),\n claimSegment(rng, false),\n ];\n return serializeTelecom(buildTelecomRequest({ header: head, segments }));\n}\n\n/**\n * Generate a spec-clean Telecom **B1** billing claim.\n *\n * @param options - The seed.\n * @returns The serialized Telecom wire string.\n * @example\n * ```ts\n * import { generateB1 } from \"@cosyte/synth/ncpdp\";\n * const wire = generateB1({ seed: 1 });\n * ```\n */\nexport function generateB1(options: GenerateTelecomOptions): string {\n return generateTelecom(\"B1\", options);\n}\n\n/**\n * Generate a spec-clean Telecom **B2** reversal.\n *\n * @param options - The seed.\n * @returns The serialized Telecom wire string.\n * @example\n * ```ts\n * import { generateB2 } from \"@cosyte/synth/ncpdp\";\n * const wire = generateB2({ seed: 1 });\n * ```\n */\nexport function generateB2(options: GenerateTelecomOptions): string {\n return generateTelecom(\"B2\", options);\n}\n\n/**\n * Generate a spec-clean Telecom **B3** rebill.\n *\n * @param options - The seed.\n * @returns The serialized Telecom wire string.\n * @example\n * ```ts\n * import { generateB3 } from \"@cosyte/synth/ncpdp\";\n * const wire = generateB3({ seed: 1 });\n * ```\n */\nexport function generateB3(options: GenerateTelecomOptions): string {\n return generateTelecom(\"B3\", options);\n}\n","/**\n * The C-CDA example-code pool — a thin adapter that **reuses** the same license-clean, public\n * code facts the FHIR generators ship (`../fhir/example-codes.ts`), reshaped into `@cosyte/ccda`'s\n * `BuildCode` tuple (an OID `codeSystem` instead of a FHIR `system` URI). Reusing one source of truth\n * keeps the LOINC / RxNorm / SNOMED / CVX pools consistent across the FHIR and C-CDA surfaces;\n * `@cosyte/synth` still bundles\n * **no** terminology content — these are public spec-example codes, not copyrighted tables.\n *\n * Nothing here is PHI: codes and their display text are not patient identifiers. The synthetic-safety\n * invariant governs identity fields (name / DOB / MRN / telecom), which come from `../safe`.\n *\n * @module\n */\n\nimport { CVX, LOINC, NCI_ROUTE, RXNORM, SNOMED_CT } from \"@cosyte/ccda\";\nimport type { BuildCode, BuildQuantity } from \"@cosyte/ccda\";\n\nimport type { Rng } from \"../rng/rng.js\";\nimport {\n EXAMPLE_ALLERGENS,\n EXAMPLE_ALLERGY_MANIFESTATIONS,\n EXAMPLE_CONDITIONS,\n EXAMPLE_DIAGNOSTIC_REPORTS,\n EXAMPLE_LAB_OBSERVATIONS,\n EXAMPLE_MEDICATIONS,\n EXAMPLE_PROCEDURES,\n EXAMPLE_VACCINES,\n EXAMPLE_VITAL_SIGNS,\n type CodeConcept,\n type QuantConcept,\n} from \"../fhir/example-codes.js\";\n\n/** Map a FHIR code-system `system` URI to the C-CDA OID `@cosyte/ccda` expects. */\nconst URI_TO_OID: Readonly<Record<string, string>> = Object.freeze({\n \"http://loinc.org\": LOINC,\n \"http://snomed.info/sct\": SNOMED_CT,\n \"http://www.nlm.nih.gov/research/umls/rxnorm\": RXNORM,\n \"http://hl7.org/fhir/sid/cvx\": CVX,\n});\n\n/**\n * Adapt a FHIR {@link CodeConcept} to a `@cosyte/ccda` {@link BuildCode}, resolving its `system` URI to\n * the matching OID. The `codeSystem` is always set explicitly (never left to a per-slot default), so a\n * SNOMED allergen or a LOINC panel carries the right OID regardless of which builder slot consumes it.\n *\n * @param concept - The FHIR-shaped `{ system, code, display }` concept.\n * @returns The `@cosyte/ccda` `BuildCode`.\n * @throws {Error} When the concept's `system` URI has no known OID mapping.\n * @example\n * ```ts\n * import { toBuildCode } from \"@cosyte/synth/ccda\";\n * // toBuildCode({ system: \"http://snomed.info/sct\", code: \"59621000\", display: \"Essential hypertension\" });\n * ```\n */\nexport function toBuildCode(concept: CodeConcept): BuildCode {\n const codeSystem = URI_TO_OID[concept.system];\n if (codeSystem === undefined) {\n throw new Error(`ccda example-codes: no OID mapping for code system \"${concept.system}\"`);\n }\n return { code: concept.code, codeSystem, displayName: concept.display };\n}\n\n/**\n * Draw a synthetic-but-structurally-sane {@link BuildQuantity} for a quantitative concept — a value in\n * the concept's plausible band (from the seeded generator, so reproducible) rendered to the concept's\n * decimal precision, with its UCUM unit. The value implies **no** real measurement.\n *\n * @param rng - The seeded generator.\n * @param concept - The quantitative concept (LOINC code + UCUM unit + value band).\n * @returns A `BuildQuantity` (`{ value, unit }`) for the C-CDA builder.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { quantityFor, LAB_RESULTS } from \"@cosyte/synth/ccda\";\n * // quantityFor(createRng(1), LAB_RESULTS[0]);\n * ```\n */\nexport function quantityFor(rng: Rng, concept: QuantConcept): BuildQuantity {\n const scale = 10 ** concept.decimals;\n const value = rng.int(concept.low * scale, concept.high * scale) / scale;\n return { value, unit: concept.unit };\n}\n\n/** SNOMED CT problem/condition example codes (Problems / Past Medical History). */\nexport const PROBLEMS: readonly CodeConcept[] = EXAMPLE_CONDITIONS;\n/** RxNorm / SNOMED CT allergen example codes (Allergies). */\nexport const ALLERGENS: readonly CodeConcept[] = EXAMPLE_ALLERGENS;\n/** SNOMED CT allergy-reaction manifestation example codes. */\nexport const ALLERGY_REACTIONS: readonly CodeConcept[] = EXAMPLE_ALLERGY_MANIFESTATIONS;\n/** RxNorm medication example codes (Medications). */\nexport const MEDICATIONS: readonly CodeConcept[] = EXAMPLE_MEDICATIONS;\n/** LOINC laboratory-result example codes with UCUM units + value bands (Results members). */\nexport const LAB_RESULTS: readonly QuantConcept[] = EXAMPLE_LAB_OBSERVATIONS;\n/** LOINC panel example codes (the Result Organizer `code`). */\nexport const RESULT_PANELS: readonly CodeConcept[] = EXAMPLE_DIAGNOSTIC_REPORTS;\n/** LOINC vital-sign example codes with UCUM units + value bands (Vital Signs members). */\nexport const VITAL_SIGNS: readonly QuantConcept[] = EXAMPLE_VITAL_SIGNS;\n/** CVX vaccine example codes (Immunizations). */\nexport const VACCINES: readonly CodeConcept[] = EXAMPLE_VACCINES;\n/** SNOMED CT procedure example codes (Procedures). */\nexport const PROCEDURES: readonly CodeConcept[] = EXAMPLE_PROCEDURES;\n\n/**\n * SNOMED CT Current Smoking Status value-set example codes (Social History). Public SNOMED CT\n * identifiers used as structural fillers; `@cosyte/synth` bundles no SNOMED content.\n */\nexport const SMOKING_STATUSES: readonly BuildCode[] = Object.freeze([\n Object.freeze({ code: \"266919005\", codeSystem: SNOMED_CT, displayName: \"Never smoker\" }),\n Object.freeze({ code: \"8517006\", codeSystem: SNOMED_CT, displayName: \"Former smoker\" }),\n Object.freeze({\n code: \"449868002\",\n codeSystem: SNOMED_CT,\n displayName: \"Current every day smoker\",\n }),\n Object.freeze({\n code: \"428041000124106\",\n codeSystem: SNOMED_CT,\n displayName: \"Current some day smoker\",\n }),\n]);\n\n/**\n * NCI Thesaurus administration-route example codes (Medications / Immunizations `route`). Public NCI\n * concept ids used as structural fillers.\n */\nexport const ROUTES: readonly BuildCode[] = Object.freeze([\n Object.freeze({ code: \"C38288\", codeSystem: NCI_ROUTE, displayName: \"Oral\" }),\n Object.freeze({ code: \"C28161\", codeSystem: NCI_ROUTE, displayName: \"Intramuscular\" }),\n Object.freeze({ code: \"C38276\", codeSystem: NCI_ROUTE, displayName: \"Intravenous\" }),\n Object.freeze({ code: \"C38299\", codeSystem: NCI_ROUTE, displayName: \"Subcutaneous\" }),\n]);\n","/**\n * Synthetic C-CDA patient identity — the `recordTarget` demographics for a generated document, every\n * field minted from the synthetic-safety providers in `../safe`. No value a generated\n * C-CDA carries at a PHI locus can be real or plausibly-real: the name is from the shipped fake-name\n * pool, the MRN lives under the synthetic assigning-authority OID (never a real facility namespace),\n * and the birth date comes from the seeded generator (never wall-clock).\n *\n * The draw order is **fixed** (name → MRN → DOB → gender) so the same seed yields the same identity —\n * the reproducibility contract.\n *\n * @module\n */\n\nimport type { BuildCcdaPatient } from \"@cosyte/ccda\";\n\nimport type { Rng } from \"../rng/rng.js\";\nimport { safe, type SyntheticIdentifier, type SyntheticName } from \"../safe/index.js\";\n\n/** A synthetic C-CDA patient identity — the values threaded into a document's `recordTarget`. */\nexport interface CcdaPatientIdentity {\n /** The `BuildCcdaPatient` `@cosyte/ccda` consumes for the single `recordTarget`. */\n readonly patient: BuildCcdaPatient;\n /** The name from the shipped fake-name pool (also used to compose synthetic narrative/email). */\n readonly person: SyntheticName;\n /** The medical-record identifier, scoped to the synthetic assigning authority. */\n readonly mrn: SyntheticIdentifier;\n}\n\n/**\n * Mint a complete synthetic {@link CcdaPatientIdentity}. Every value comes from a synthetic-safety\n * provider — no code path here can return a real identifier. The MRN is scoped to the\n * synthetic assigning-authority OID (`mrnRoot`), so it is non-colliding by *namespace*, not by value.\n *\n * @param rng - The seeded generator.\n * @returns A synthetic {@link CcdaPatientIdentity}.\n * @example\n * ```ts\n * import { createRng } from \"@cosyte/synth\";\n * import { ccdaPatientIdentity } from \"@cosyte/synth/ccda\";\n * // const { patient } = ccdaPatientIdentity(createRng(1));\n * ```\n */\nexport function ccdaPatientIdentity(rng: Rng): CcdaPatientIdentity {\n const person = safe.name(rng);\n const mrn = safe.identifier(rng, \"MR\");\n const birthTime = safe.dateYmd(rng, 1930, 2010);\n const gender = rng.pick([\"M\", \"F\"] as const);\n const patient: BuildCcdaPatient = {\n mrn: mrn.value,\n mrnRoot: mrn.assigningAuthorityOid,\n mrnAssigningAuthority: mrn.assigningAuthority,\n given: [person.given],\n family: person.family,\n gender,\n birthTime,\n };\n return { patient, person, mrn };\n}\n","/**\n * Synthetic **C-CDA document generation** — a spec-clean Continuity of Care Document\n * (CCD) or Referral Note built **through `@cosyte/ccda`'s `buildCcda`**, so template IDs, LOINC section\n * codes, and structured/narrative agreement are the builder's own (spec-clean *by construction*), and\n * every `recordTarget` / clinical identifier is drawn from the synthetic-safety providers.\n *\n * The document round-trips through `parseCcda` with **zero warnings** — the builder's round-trip-by-\n * construction guarantee, re-verified independently by {@link ./round-trip.roundTrip}. Coverage tracks\n * `buildCcda`'s section/doc-type maturity: the CCD SHALL sections (Problems,\n * Allergies, Medications, Results, Vital Signs) plus Immunizations, Procedures, and Social History\n * (Smoking Status). Clinical *content* is drawn from the reused, license-clean example-code pools; a\n * `synth` document exercises the parser, it is **not** a clinically-coherent record.\n *\n * @module\n */\n\nimport { buildCcda, type BuildCcdaInit, type CcdaDocument } from \"@cosyte/ccda\";\n\nimport { createRng, type Rng } from \"../rng/rng.js\";\nimport { safe } from \"../safe/index.js\";\n\nimport {\n ALLERGENS,\n ALLERGY_REACTIONS,\n LAB_RESULTS,\n MEDICATIONS,\n PROBLEMS,\n PROCEDURES,\n RESULT_PANELS,\n ROUTES,\n SMOKING_STATUSES,\n VACCINES,\n VITAL_SIGNS,\n quantityFor,\n toBuildCode,\n} from \"./example-codes.js\";\nimport { ccdaPatientIdentity } from \"./identity.js\";\n\n/** The C-CDA document type a generator emits — the two `buildCcda` supports. */\nexport type CcdaDocumentType = \"ccd\" | \"referralNote\";\n\n/** Options common to every C-CDA generator. */\nexport interface GenerateCcdaOptions {\n /** The seed (deterministic — same seed yields a byte-identical document). Defaults to `0`. */\n readonly seed?: number;\n /** The document type to emit. Defaults to `\"ccd\"`. */\n readonly documentType?: CcdaDocumentType;\n}\n\n/** Pick `n` **distinct** items from a pool (`n` clamped to the pool size) using the seeded generator. */\nfunction pickN<T>(rng: Rng, pool: readonly T[], n: number): T[] {\n const take = Math.min(n, pool.length);\n const indices = pool.map((_v, i) => i);\n const out: T[] = [];\n for (let i = 0; i < take; i += 1) {\n const j = rng.int(0, indices.length - 1);\n // `j` is in `[0, indices.length-1]` on a non-empty array, so `indices[j]` and `pool[idx]` are\n // never holes; the casts discharge `noUncheckedIndexedAccess`'s `| undefined` with no runtime\n // re-check (mirroring `Rng.pick`).\n const idx = indices[j] as number;\n indices.splice(j, 1);\n out.push(pool[idx] as T);\n }\n return out;\n}\n\n/**\n * Assemble the synthetic {@link BuildCcdaInit} — the identity + clinical content the builder turns into\n * a spec-clean document. Section counts vary with the seed (each SHALL clinical section is always\n * non-empty; the optional sections are always populated for a rich fixture), and every code is drawn\n * from the reused example-code pools.\n */\nfunction buildInit(rng: Rng, documentType: CcdaDocumentType): BuildCcdaInit {\n const effectiveTime = safe.dateYmd(rng, 2020, 2025);\n const { patient, person } = ccdaPatientIdentity(rng);\n\n const problems = pickN(rng, PROBLEMS, rng.int(1, 3)).map((c) => ({\n problem: toBuildCode(c),\n status: \"active\" as const,\n onset: safe.dateYmd(rng, 2010, 2019),\n }));\n\n const allergen = rng.pick(ALLERGENS);\n const reaction = rng.pick(ALLERGY_REACTIONS);\n const allergies = [{ allergen: toBuildCode(allergen), reaction: toBuildCode(reaction) }];\n\n const medications = pickN(rng, MEDICATIONS, rng.int(1, 2)).map((c) => ({\n drug: toBuildCode(c),\n dose: { value: 1, unit: \"{tablet}\" },\n route: rng.pick(ROUTES),\n frequency: { value: rng.pick([8, 12, 24]), unit: \"h\" },\n }));\n\n const panel = rng.pick(RESULT_PANELS);\n const resultMembers = pickN(rng, LAB_RESULTS, 2).map((q) => ({\n test: toBuildCode(q),\n quantity: quantityFor(rng, q),\n effectiveTime,\n }));\n const results = [{ code: toBuildCode(panel), effectiveTime, results: resultMembers }];\n\n const vitalMembers = pickN(rng, VITAL_SIGNS, 2).map((q) => ({\n code: toBuildCode(q),\n quantity: quantityFor(rng, q),\n }));\n const vitalSigns = [{ effectiveTime, vitals: vitalMembers }];\n\n const vaccine = rng.pick(VACCINES);\n const immunizations = [\n {\n vaccine: toBuildCode(vaccine),\n dose: { value: 0.5, unit: \"mL\" },\n route: rng.pick(ROUTES),\n effectiveTime: safe.dateYmd(rng, 2018, 2024),\n },\n ];\n\n const procedure = rng.pick(PROCEDURES);\n const procedures = [\n {\n code: toBuildCode(procedure),\n disposition: \"performed\" as const,\n effectiveTime: safe.dateYmd(rng, 2015, 2023),\n },\n ];\n\n const smokingStatus = [{ value: rng.pick(SMOKING_STATUSES), effectiveTime }];\n\n const base: BuildCcdaInit = {\n documentType,\n effectiveTime,\n patient,\n problems,\n allergies,\n medications,\n results,\n vitalSigns,\n immunizations,\n procedures,\n smokingStatus,\n };\n\n if (documentType === \"referralNote\") {\n // The Referral Note's narrative-only SHALL sections — synthetic free text (never fabricated\n // clinical judgment about a real person; the \"patient\" does not exist).\n return {\n ...base,\n reasonForReferral: `Synthetic referral for evaluation of ${person.given} ${person.family}.`,\n assessment: \"Synthetic assessment narrative. Not a real clinical assessment.\",\n };\n }\n return base;\n}\n\n/**\n * Generate a spec-clean synthetic C-CDA document (CCD by default, or Referral Note), built through\n * `@cosyte/ccda`'s `buildCcda`. The returned {@link CcdaDocument} round-trips through `parseCcda` with\n * zero warnings, and the same seed yields a byte-identical document.\n *\n * @param options - Seed and document type. See {@link GenerateCcdaOptions}.\n * @returns The `@cosyte/ccda` `CcdaDocument` (serialize via `serializeCcda(doc)` or `doc.toString()`).\n * @example\n * ```ts\n * import { generateCcda } from \"@cosyte/synth/ccda\";\n * import { serializeCcda } from \"@cosyte/ccda\";\n * const xml = serializeCcda(generateCcda({ seed: 42 }));\n * ```\n */\nexport function generateCcda(options: GenerateCcdaOptions = {}): CcdaDocument {\n const { seed = 0, documentType = \"ccd\" } = options;\n const rng = createRng(seed);\n return buildCcda(buildInit(rng, documentType));\n}\n\n/**\n * Generate a spec-clean synthetic **Continuity of Care Document (CCD)**.\n *\n * @param options - Seed (deterministic). See {@link GenerateCcdaOptions}.\n * @returns The `CcdaDocument`.\n * @example\n * ```ts\n * import { generateCcd, roundTrip } from \"@cosyte/synth/ccda\";\n * roundTrip(generateCcd({ seed: 1 })).specClean; // true\n * ```\n */\nexport function generateCcd(options: Omit<GenerateCcdaOptions, \"documentType\"> = {}): CcdaDocument {\n return generateCcda({ ...options, documentType: \"ccd\" });\n}\n\n/**\n * Generate a spec-clean synthetic **Referral Note** — the second document type `buildCcda` supports,\n * with its own US Realm Header specialization and Reason-for-Referral / Assessment narrative sections.\n *\n * @param options - Seed (deterministic). See {@link GenerateCcdaOptions}.\n * @returns The `CcdaDocument`.\n * @example\n * ```ts\n * import { generateReferralNote } from \"@cosyte/synth/ccda\";\n * generateReferralNote({ seed: 1 }).documentType; // \"referralNote\"\n * ```\n */\nexport function generateReferralNote(\n options: Omit<GenerateCcdaOptions, \"documentType\"> = {},\n): CcdaDocument {\n return generateCcda({ ...options, documentType: \"referralNote\" });\n}\n","/**\n * The format-agnostic core of the **`@cosyte/deid` pairing loop** — a **closed-loop\n * co-validation harness** for the `synth` ⇄ `deid` pair.\n *\n * The loop's shape is: **generate a spec-clean synthetic artifact → enumerate the distinctive synthetic\n * PHI sentinels `@cosyte/synth` planted at its patient loci → run it through `@cosyte/deid` → verify\n * every planted sentinel is gone from the de-identified output** (a surviving sentinel is a hard\n * failure), **and that the non-PHI clinical content survived** (the over-scrub guard). It is\n * deterministic and seeded, and it does **not** change what the generators emit — it consumes their\n * output.\n *\n * **Honesty line (governs the whole module).** This is a **co-validation harness**, not an independent\n * audit of `@cosyte/deid` against real-world data. It proves *the pair works on `synth`'s own output*:\n * that the synthetic PHI `synth` plants at the patient loci is removed by `deid`, and that `deid` does\n * not over-scrub `synth`'s clinical payload. A sentinel that `deid` **blocks** rather than redacts still\n * passes the removal check (blocked = gone from the wire). Formats where `@cosyte/deid` ships no adapter\n * (NCPDP **SCRIPT**, **ASTM**) — and DICOM, which `synth` does not generate — are **skipped and named**\n * (see `DEID_LOOP_SKIPPED` in `./index`), never silently.\n *\n * This module holds only the pure, parser-free pieces (the policy, the sentinel model, the sweep, the\n * over-scrub check, the verdict). The per-format loops that drive the generators and the `deid` adapters\n * live in `./index`.\n *\n * @module\n */\n\nimport {\n defineDeidPolicy,\n SAFE_HARBOR_CATEGORIES,\n type DeidPolicy,\n type GenericLocus,\n} from \"@cosyte/deid\";\n\n/**\n * The set of cosyte formats the loop covers — every format for which **both** `@cosyte/synth` generates\n * and `@cosyte/deid` ships an adapter.\n */\nexport type DeidLoopFormat = \"hl7\" | \"fhir\" | \"ccda\" | \"x12\" | \"ncpdp-telecom\";\n\n/**\n * A single **planted sentinel**: one distinctive, synthetic-by-construction PHI token that\n * `@cosyte/synth` placed at a patient locus of a generated artifact, tracked so the loop can prove\n * `@cosyte/deid` removed it. The token is always drawn from a synthetic-safety provider —\n * a fake-name-pool name, a `900`-range SSN, a `555-01xx` phone, a synthetic-assigning-authority\n * identifier — so a sentinel can never be, or collide with, a real person's PHI.\n *\n * @example\n * ```ts\n * const s: DeidSentinel = { token: \"Examplewood\", locus: \"PID-5\", category: \"names\" };\n * ```\n */\nexport interface DeidSentinel {\n /** The exact synthetic token planted at the locus — a literal substring of the spec-clean artifact. */\n readonly token: string;\n /** Where it lives — a format-neutral path (e.g. `\"PID-5\"`, `\"recordTarget\"`, `\"NM1[0]-3\"`). */\n readonly locus: string;\n /** The Safe Harbor category `@cosyte/deid` assigned to the locus, when known. */\n readonly category?: string;\n}\n\n/**\n * The verdict of one pass through the pairing loop for one artifact.\n *\n * `pass` is `true` **iff** at least one sentinel was planted, **no** planted sentinel survived\n * de-identification, and **no** probed clinical value was over-scrubbed.\n *\n * @example\n * ```ts\n * import { hl7DeidLoop } from \"@cosyte/synth/deid\";\n * const r = hl7DeidLoop({ seed: 42 });\n * r.pass; // => true\n * r.survivors.length; // => 0\n * ```\n */\nexport interface DeidLoopResult {\n /** The covered format. */\n readonly format: DeidLoopFormat;\n /** The concrete artifact label (e.g. `\"ORU^R01\"`, `\"837P\"`, `\"CCD\"`). */\n readonly artifact: string;\n /** The seed — the same seed yields the same artifact and the same verdict. */\n readonly seed: number;\n /** Every distinctive synthetic PHI sentinel `synth` planted at a patient locus of the artifact. */\n readonly planted: readonly DeidSentinel[];\n /** Planted sentinels still present in the de-identified output — **must be empty**. */\n readonly survivors: readonly DeidSentinel[];\n /** The non-PHI clinical code tokens probed for over-scrub (present in the spec-clean artifact). */\n readonly clinicalProbed: readonly string[];\n /** Probed clinical tokens missing after de-identification (over-scrub) — **must be empty**. */\n readonly clinicalScrubbed: readonly string[];\n /** The spec-clean serialized artifact (before de-identification). */\n readonly original: string;\n /** The serialized de-identified artifact (`@cosyte/deid`'s output). */\n readonly deidentified: string;\n /** `true` iff sentinels were planted, none survived, and nothing clinical was over-scrubbed. */\n readonly pass: boolean;\n}\n\n/**\n * The name of the removal-oriented policy the loop runs `@cosyte/deid` under.\n *\n * @example\n * ```ts\n * import { DEID_LOOP_POLICY_NAME } from \"@cosyte/synth/deid\";\n * DEID_LOOP_POLICY_NAME; // => \"synth-deid-loop-removal\"\n * ```\n */\nexport const DEID_LOOP_POLICY_NAME = \"synth-deid-loop-removal\";\n\n/**\n * Build the **removal-oriented** de-identification policy the loop runs `@cosyte/deid` under: HIPAA Safe\n * Harbor, but with the three keyed-by-default identifier categories (MRN, health-plan-beneficiary,\n * account) switched from `pseudonymize` to `redact`.\n *\n * Two reasons this is the right policy for a co-validation loop: (1) it needs **no key context**, so the\n * loop is a pure function of the seed (the default Safe Harbor policy pseudonymizes those three\n * categories, which requires the consumer's HMAC key); and (2) it makes the removal contract crisp —\n * every PHI locus is **removed or generalized away**, never replaced by a surrogate that a naive sweep\n * might mistake for a survivor. `pseudonymize` also removes the original value, so this is a stricter,\n * not weaker, check.\n *\n * @returns A frozen {@link DeidPolicy} suitable for the `policy` option of any `@cosyte/deid` adapter.\n * @example\n * ```ts\n * import { deidLoopPolicy } from \"@cosyte/synth/deid\";\n * import { deidentifyHl7 } from \"@cosyte/deid/hl7\";\n * const { document } = deidentifyHl7(msg, { policy: deidLoopPolicy() });\n * ```\n */\nexport function deidLoopPolicy(): DeidPolicy {\n return defineDeidPolicy({\n name: DEID_LOOP_POLICY_NAME,\n transforms: {\n [SAFE_HARBOR_CATEGORIES.MRN]: \"redact\",\n [SAFE_HARBOR_CATEGORIES.HEALTH_PLAN_BENEFICIARY]: \"redact\",\n [SAFE_HARBOR_CATEGORIES.ACCOUNT]: \"redact\",\n },\n });\n}\n\n/**\n * Tokens that are structural labels or generic address words rather than distinctive PHI — dropped when\n * decomposing a composite locus value so a sentinel is always a *distinctive* synthetic token. (A\n * de-identifier keeps `state`, so a generic street suffix at a redacted address locus could otherwise\n * read as a false survivor.)\n *\n * @internal\n */\nconst STOPWORDS: ReadonlySet<string> = new Set([\n \"official\",\n \"usual\",\n \"temp\",\n \"old\",\n \"anonymous\",\n \"maiden\",\n \"nickname\",\n \"home\",\n \"work\",\n \"mobile\",\n \"phone\",\n \"email\",\n \"fax\",\n \"sms\",\n \"pager\",\n \"other\",\n \"use\",\n \"street\",\n \"road\",\n \"avenue\",\n \"court\",\n \"lane\",\n \"drive\",\n \"boulevard\",\n \"place\",\n \"way\",\n \"suite\",\n \"apt\",\n \"unit\",\n \"null\",\n \"undefined\",\n]);\n\n/** Split a composite locus value into candidate tokens on the delimiters the formats use. @internal */\nfunction tokenize(value: string): readonly string[] {\n return value\n .split(/[\\s^~&|,()/\\\\]+/)\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n}\n\n/**\n * Whether a candidate token is a *distinctive* sentinel: long enough, not a structural stopword, and —\n * for a pure-digit run — at least five digits (so a 4-digit street number that a de-identifier removes\n * but that could coincide with a retained value is not treated as a sentinel).\n *\n * @internal\n */\nfunction isDistinctive(token: string): boolean {\n if (token.length < 4) return false;\n if (STOPWORDS.has(token.toLowerCase())) return false;\n if (/^\\d+$/.test(token) && token.length < 5) return false;\n return true;\n}\n\n/**\n * Enumerate the distinctive synthetic PHI sentinels from a de-identifier's **patient-scoped**\n * identifier loci, decomposed to **literal** tokens of the spec-clean artifact.\n *\n * The loci come from `@cosyte/deid`'s own per-format extractor (`extractHl7Loci` / `extractFhirLoci` /\n * `extractX12Loci` / `extractTelecomLoci`), which locates PHI **structurally** — so provider and\n * organization names, which a de-identifier legitimately retains, are never extracted and never become\n * false sentinels. Only `identifier`-kind loci are used (names, SSNs, phones, emails, member/account\n * ids); dates (generalized to a year, not removed) and ZIPs (generalized to three digits) are handled by\n * the format's own contract, not asserted here.\n *\n * Requiring each token to be a **literal substring of `original`** keeps the removal check non-vacuous:\n * a sentinel the sweep later looks for is one that is provably present before de-identification.\n *\n * @param loci - The located candidate values from a `@cosyte/deid` extractor.\n * @param original - The spec-clean serialized artifact the loci were extracted from.\n * @returns The distinctive, literal, synthetic PHI sentinels — de-duplicated by token.\n * @example\n * ```ts\n * import { extractHl7Loci } from \"@cosyte/deid/hl7\";\n * const sentinels = identifierSentinels(extractHl7Loci(msg).loci, msg.toString());\n * ```\n */\nexport function identifierSentinels(\n loci: readonly GenericLocus[],\n original: string,\n): readonly DeidSentinel[] {\n const out: DeidSentinel[] = [];\n const seen = new Set<string>();\n for (const locus of loci) {\n if (locus.kind !== \"identifier\" || locus.value.length === 0) continue;\n for (const token of tokenize(locus.value)) {\n if (!isDistinctive(token)) continue;\n if (!original.includes(token)) continue;\n if (seen.has(token)) continue;\n seen.add(token);\n out.push({\n token,\n locus: locus.path,\n ...(locus.category !== undefined ? { category: locus.category } : {}),\n });\n }\n }\n return out;\n}\n\n/**\n * Enumerate the patient sentinels of a **C-CDA** document by reading the `<recordTarget>` element of the\n * serialized XML — the patient participation. Scoping to `recordTarget` (rather than `author` /\n * `custodian`, which carry provider identity a de-identifier retains) is what keeps the sentinels\n * patient-PHI only. Used for C-CDA because `@cosyte/deid`'s C-CDA extractor operates on a raw DOM, which\n * this zero-dependency module does not construct.\n *\n * @param xml - The serialized spec-clean C-CDA document.\n * @returns The distinctive synthetic patient sentinels (given/family names, the patient id extensions).\n * @example\n * ```ts\n * import { serializeCcda } from \"@cosyte/ccda\";\n * const sentinels = recordTargetSentinels(serializeCcda(generateCcd({ seed: 1 })));\n * ```\n */\nexport function recordTargetSentinels(xml: string): readonly DeidSentinel[] {\n const block = /<recordTarget[\\s\\S]*?<\\/recordTarget>/i.exec(xml);\n if (block === null) return [];\n const scope = block[0];\n const out: DeidSentinel[] = [];\n const seen = new Set<string>();\n const add = (token: string, locus: string): void => {\n const trimmed = token.trim();\n if (!isDistinctive(trimmed) || seen.has(trimmed)) return;\n seen.add(trimmed);\n out.push({ token: trimmed, locus, category: \"names\" });\n };\n for (const m of scope.matchAll(/<given>([^<]+)<\\/given>/g)) add(m[1] ?? \"\", \"recordTarget/given\");\n for (const m of scope.matchAll(/<family>([^<]+)<\\/family>/g))\n add(m[1] ?? \"\", \"recordTarget/family\");\n for (const m of scope.matchAll(/<id\\b[^>]*\\bextension=\"([^\"]+)\"/g))\n add(m[1] ?? \"\", \"recordTarget/id\");\n return out;\n}\n\n/**\n * Sweep the **PHI-locus residue** of a de-identified artifact for **surviving** planted sentinels — the\n * heart of the removal check. A sentinel survives if its exact token still appears in the values that\n * remain at the (former) PHI loci after de-identification; a non-empty result is a **hard failure** (real\n * PHI-shaped data leaked through de-identification).\n *\n * **Why the PHI-locus residue and not the whole document.** `@cosyte/synth` draws patient *and*\n * provider/organization names, addresses, and phones from the same synthetic pools, and a de-identifier\n * legitimately **retains** provider identity. So the same synthetic token can sit at both a patient locus\n * (removed) and a provider locus (retained); a whole-document sweep would read the retained provider copy\n * as a false survivor. Sweeping only the residue at the loci that were PHI — re-read from the\n * de-identifier's own output — is locus-scoped and collision-proof: a token still present *there* is a\n * genuine leak. It remains independent of the de-identifier's manifest: it reads the actual serialized\n * output, so a de-identifier that locates a locus but fails to strip it is still caught.\n *\n * @param phiResidue - The de-identified values that remain at the former PHI loci (for the model formats,\n * the re-extracted identifier-locus values joined; for C-CDA, the de-identified `<recordTarget>` block).\n * @param sentinels - The sentinels planted in the corresponding spec-clean artifact.\n * @returns The subset of `sentinels` still present in `phiResidue` — empty on a clean pass.\n * @example\n * ```ts\n * sweepSurvivors(deidPhiResidue, planted); // => [] (all removed)\n * ```\n */\nexport function sweepSurvivors(\n phiResidue: string,\n sentinels: readonly DeidSentinel[],\n): readonly DeidSentinel[] {\n return sentinels.filter((s) => phiResidue.includes(s.token));\n}\n\n/**\n * The over-scrub side of the loop: of the clinical (non-PHI) code tokens that appear in the spec-clean\n * artifact, which are **missing** after de-identification. A de-identifier must keep clinical content; a\n * non-empty result means it over-scrubbed. Only structured code tokens present before de-identification\n * are probed (a code that appears solely inside a free-text narrative a de-identifier legitimately blocks\n * is not a structured-content loss).\n *\n * Only **distinctive** codes (four or more characters) are probed: a short 2–3 digit code (e.g. a CVX\n * vaccine code) can appear by coincidence *inside* a PHI value a de-identifier removes — a timestamp, an\n * SSN — and would read as a false over-scrub. Distinctive codes (LOINC `4548-4`, SNOMED `44054006`,\n * 11-digit NDCs, CPT `99213`) do not collide this way. An artifact whose clinical codes are all short\n * simply yields an empty probe (the guard is skipped, never falsely tripped).\n *\n * @param original - The spec-clean serialized artifact.\n * @param deidentified - The serialized de-identified artifact.\n * @param clinicalCodes - Candidate structured clinical code tokens (e.g. LOINC/ICD/NDC from the example\n * pools) to probe.\n * @returns `{ probed, scrubbed }` — the distinctive codes present before, and the subset absent after.\n * @example\n * ```ts\n * const { probed, scrubbed } = clinicalRetention(before, after, [\"4548-4\", \"44054006\"]);\n * scrubbed; // => [] (clinical content retained)\n * ```\n */\nexport function clinicalRetention(\n original: string,\n deidentified: string,\n clinicalCodes: readonly string[],\n): { readonly probed: readonly string[]; readonly scrubbed: readonly string[] } {\n const probed = [...new Set(clinicalCodes.filter((c) => c.length >= 4 && original.includes(c)))];\n const scrubbed = probed.filter((c) => !deidentified.includes(c));\n return { probed, scrubbed };\n}\n\n/**\n * Assemble a {@link DeidLoopResult} from the planted sentinels, the de-identified output, and the\n * clinical probe — computing the `pass` verdict (sentinels planted, none survived, nothing over-scrubbed).\n *\n * @param parts - The pieces gathered by a per-format loop.\n * @returns The immutable verdict.\n * @example\n * ```ts\n * const result = assembleVerdict({\n * format: \"hl7\", artifact: \"ORU^R01\", seed: 1,\n * planted, original, deidentified, clinicalCodes,\n * });\n * ```\n */\nexport function assembleVerdict(parts: {\n readonly format: DeidLoopFormat;\n readonly artifact: string;\n readonly seed: number;\n readonly planted: readonly DeidSentinel[];\n readonly original: string;\n readonly deidentified: string;\n /**\n * The de-identified values that remain at the former PHI loci — what the survivor sweep reads (see\n * {@link sweepSurvivors}). Defaults to `deidentified` when omitted (a whole-document sweep), but the\n * per-format loops supply the locus-scoped residue so provider/organization identity a de-identifier\n * legitimately retains never reads as a false survivor.\n */\n readonly phiResidue?: string;\n readonly clinicalCodes: readonly string[];\n}): DeidLoopResult {\n const survivors = sweepSurvivors(parts.phiResidue ?? parts.deidentified, parts.planted);\n const { probed, scrubbed } = clinicalRetention(\n parts.original,\n parts.deidentified,\n parts.clinicalCodes,\n );\n const pass = parts.planted.length > 0 && survivors.length === 0 && scrubbed.length === 0;\n return Object.freeze({\n format: parts.format,\n artifact: parts.artifact,\n seed: parts.seed,\n planted: Object.freeze([...parts.planted]),\n survivors: Object.freeze(survivors),\n clinicalProbed: Object.freeze(probed),\n clinicalScrubbed: Object.freeze(scrubbed),\n original: parts.original,\n deidentified: parts.deidentified,\n pass,\n });\n}\n","/**\n * `@cosyte/synth/deid` — the **`@cosyte/deid` pairing loop**: a deterministic,\n * seeded **co-validation harness** for the `synth` ⇄ `deid` pair.\n *\n * For each covered format it **generates** a spec-clean synthetic artifact through `@cosyte/synth`'s own\n * generators, **enumerates** the distinctive synthetic PHI sentinels planted at the patient loci,\n * **de-identifies** it through `@cosyte/deid`, and **verifies** that every planted sentinel is gone from\n * the de-identified output while the clinical payload survives. A surviving sentinel is a hard failure;\n * an over-scrubbed clinical value is a hard failure.\n *\n * **Scope & honesty.** This proves *the pair works on `synth`'s own output* — it\n * is **not** an independent audit of `@cosyte/deid` against real-world documents. The sentinels are\n * synthetic-by-construction (never realistic); a sentinel `deid` **blocks** rather than redacts still\n * passes (blocked = gone). The loop covers the five formats both packages support\n * ({@link DEID_LOOP_COVERED_FORMATS}); NCPDP **SCRIPT**, **ASTM**, and **DICOM** are **skipped and\n * named** ({@link DEID_LOOP_SKIPPED}), never silently. `@cosyte/deid` is an **optional peer dependency**\n * (the `mllp`/`ncpdp` vendoring pattern); importing this subpath pulls it in.\n *\n * @module\n */\n\nimport { deidentifyHl7, extractHl7Loci } from \"@cosyte/deid/hl7\";\nimport { deidentifyFhir, extractFhirLoci } from \"@cosyte/deid/fhir\";\nimport { deidentifyX12, extractX12Loci } from \"@cosyte/deid/x12\";\nimport { deidentifyTelecom, extractTelecomLoci } from \"@cosyte/deid/ncpdp\";\nimport { deidentifyCcda } from \"@cosyte/deid/ccda\";\nimport { serializeResource } from \"@cosyte/fhir\";\nimport { serializeX12, parseX12, type X12Interchange } from \"@cosyte/x12\";\nimport { serializeCcda } from \"@cosyte/ccda\";\nimport { parseTelecom } from \"@cosyte/ncpdp/telecom\";\nimport type { GenericLocus } from \"@cosyte/deid\";\n\nimport { generateHl7, type Hl7MessageKind } from \"../hl7/index.js\";\nimport { generateBundle } from \"../fhir/index.js\";\nimport {\n generate837P,\n generate837I,\n generate837D,\n generate271,\n generate835,\n} from \"../x12/index.js\";\nimport { generateB1, generateB2, generateB3 } from \"../ncpdp/index.js\";\nimport { generateCcda } from \"../ccda/index.js\";\nimport {\n EXAMPLE_LAB_OBSERVATIONS as HL7_LABS,\n EXAMPLE_ORDER_SERVICES,\n EXAMPLE_VACCINES,\n} from \"../hl7/example-codes.js\";\nimport {\n EXAMPLE_LAB_OBSERVATIONS as FHIR_LABS,\n EXAMPLE_VITAL_SIGNS,\n EXAMPLE_CONDITIONS,\n EXAMPLE_MEDICATIONS,\n} from \"../fhir/example-codes.js\";\nimport {\n PROFESSIONAL_PROCEDURES,\n INSTITUTIONAL_PROCEDURES,\n DIAGNOSES,\n} from \"../x12/example-codes.js\";\nimport { EXAMPLE_DRUGS } from \"../ncpdp/example-codes.js\";\n\nimport {\n assembleVerdict,\n deidLoopPolicy,\n identifierSentinels,\n recordTargetSentinels,\n type DeidLoopResult,\n} from \"./loop.js\";\n\nexport {\n deidLoopPolicy,\n DEID_LOOP_POLICY_NAME,\n identifierSentinels,\n recordTargetSentinels,\n sweepSurvivors,\n clinicalRetention,\n assembleVerdict,\n type DeidLoopFormat,\n type DeidSentinel,\n type DeidLoopResult,\n} from \"./loop.js\";\n\n/**\n * The cosyte formats the pairing loop covers — every format for which **both** `@cosyte/synth`\n * generates and `@cosyte/deid` ships an adapter.\n *\n * @example\n * ```ts\n * import { DEID_LOOP_COVERED_FORMATS } from \"@cosyte/synth/deid\";\n * DEID_LOOP_COVERED_FORMATS; // [\"hl7\",\"fhir\",\"ccda\",\"x12\",\"ncpdp-telecom\"]\n * ```\n */\nexport const DEID_LOOP_COVERED_FORMATS = Object.freeze([\n \"hl7\",\n \"fhir\",\n \"ccda\",\n \"x12\",\n \"ncpdp-telecom\",\n] as const);\n\n/**\n * The format paths the loop **deliberately skips**, each with the honest reason — so a coverage gap is\n * named, never silent.\n *\n * @example\n * ```ts\n * import { DEID_LOOP_SKIPPED } from \"@cosyte/synth/deid\";\n * DEID_LOOP_SKIPPED.map((s) => s.format); // [\"ncpdp-script\",\"astm\",\"dicom\"]\n * ```\n */\nexport const DEID_LOOP_SKIPPED = Object.freeze([\n Object.freeze({\n format: \"ncpdp-script\",\n reason:\n \"@cosyte/deid ships no NCPDP SCRIPT locus map; synth generates SCRIPT but the loop cannot pair it.\",\n }),\n Object.freeze({\n format: \"astm\",\n reason: \"@cosyte/deid ships no ASTM adapter; synth generates ASTM but the loop cannot pair it.\",\n }),\n Object.freeze({\n format: \"dicom\",\n reason: \"@cosyte/synth does not generate DICOM, so there is nothing to pair.\",\n }),\n] as const);\n\nconst POLICY = deidLoopPolicy();\n\n/**\n * The **PHI-locus residue** of a de-identified artifact: the values that remain at the loci a\n * `@cosyte/deid` extractor locates, newline-joined for the survivor sweep. The newline separator keeps a\n * token that ends one locus's value from concatenating with the start of the next into a spurious match.\n * See {@link sweepSurvivors} for why the sweep is locus-scoped rather than whole-document.\n *\n * @internal\n */\nfunction residue(loci: readonly GenericLocus[]): string {\n return loci.map((l) => l.value).join(\"\\n\");\n}\n\n/** The de-identified `<recordTarget>` block of a C-CDA document — the patient PHI residue. @internal */\nfunction recordTargetResidue(xml: string): string {\n return /<recordTarget[\\s\\S]*?<\\/recordTarget>/i.exec(xml)?.[0] ?? \"\";\n}\n\n/** The HL7 v2 structured clinical code pool probed for over-scrub. @internal */\nconst HL7_CLINICAL = [...HL7_LABS, ...EXAMPLE_ORDER_SERVICES, ...EXAMPLE_VACCINES].map(\n (c) => c.code,\n);\n/** The FHIR structured clinical code pool probed for over-scrub. @internal */\nconst FHIR_CLINICAL = [\n ...FHIR_LABS,\n ...EXAMPLE_VITAL_SIGNS,\n ...EXAMPLE_CONDITIONS,\n ...EXAMPLE_MEDICATIONS,\n].map((c) => c.code);\n/** The X12 structured clinical code pool probed for over-scrub. @internal */\nconst X12_CLINICAL = [...PROFESSIONAL_PROCEDURES, ...INSTITUTIONAL_PROCEDURES, ...DIAGNOSES].map(\n (c) => c.code,\n);\n/** The NCPDP structured clinical code pool (drug NDCs) probed for over-scrub. @internal */\nconst NCPDP_CLINICAL = EXAMPLE_DRUGS.map((d) => d.ndc);\n\n/** Options accepted by {@link hl7DeidLoop}. */\nexport interface Hl7DeidLoopOptions {\n /** The seed — the same seed yields the same artifact and the same verdict. Defaults to `0`. */\n readonly seed?: number;\n /** The HL7 v2 message family to generate. Defaults to `\"ORU^R01\"` (a PHI- and clinically-dense report). */\n readonly kind?: Hl7MessageKind;\n}\n\n/**\n * Run the pairing loop for **HL7 v2**: generate a spec-clean message through `@cosyte/hl7`'s builder,\n * plant PHI sentinels at the `PID`, de-identify through `@cosyte/deid/hl7`, and verify removal +\n * clinical retention.\n *\n * @param options - The seed and message family. See {@link Hl7DeidLoopOptions}.\n * @returns The {@link DeidLoopResult} for the message.\n * @example\n * ```ts\n * import { hl7DeidLoop } from \"@cosyte/synth/deid\";\n * const { pass, survivors } = hl7DeidLoop({ seed: 42, kind: \"ORU^R01\" });\n * // pass === true, survivors.length === 0\n * ```\n */\nexport function hl7DeidLoop(options: Hl7DeidLoopOptions = {}): DeidLoopResult {\n const seed = options.seed ?? 0;\n const kind: Hl7MessageKind = options.kind ?? \"ORU^R01\";\n const message = generateHl7(kind, seed);\n const original = message.toString();\n const planted = identifierSentinels(extractHl7Loci(message).loci, original);\n const deidDoc = deidentifyHl7(message, { policy: POLICY }).document;\n const deidentified = deidDoc.toString();\n return assembleVerdict({\n format: \"hl7\",\n artifact: kind,\n seed,\n planted,\n original,\n deidentified,\n phiResidue: residue(extractHl7Loci(deidDoc).loci),\n clinicalCodes: HL7_CLINICAL,\n });\n}\n\n/** Options accepted by {@link fhirDeidLoop}. */\nexport interface FhirDeidLoopOptions {\n /** The seed. Defaults to `0`. */\n readonly seed?: number;\n}\n\n/**\n * Run the pairing loop for **FHIR R4**: generate a spec-clean `Bundle` (US-Core `Patient` + a clinical\n * spine) through `@cosyte/fhir`'s model, plant PHI sentinels at the `Patient` demographics, de-identify\n * through `@cosyte/deid/fhir`, and verify removal + clinical retention. A `Bundle` (not a bare\n * `Patient`) is used so there is clinical content to prove is **not** over-scrubbed.\n *\n * @param options - The seed. See {@link FhirDeidLoopOptions}.\n * @returns The {@link DeidLoopResult} for the bundle.\n * @example\n * ```ts\n * import { fhirDeidLoop } from \"@cosyte/synth/deid\";\n * fhirDeidLoop({ seed: 7 }).pass; // => true\n * ```\n */\nexport function fhirDeidLoop(options: FhirDeidLoopOptions = {}): DeidLoopResult {\n const seed = options.seed ?? 0;\n const bundle = generateBundle({ seed });\n const original = serializeResource(bundle);\n const planted = identifierSentinels(extractFhirLoci(bundle).loci, original);\n const deidDoc = deidentifyFhir(bundle, { policy: POLICY }).document;\n const deidentified = serializeResource(deidDoc);\n return assembleVerdict({\n format: \"fhir\",\n artifact: \"Bundle\",\n seed,\n planted,\n original,\n deidentified,\n phiResidue: residue(extractFhirLoci(deidDoc).loci),\n clinicalCodes: FHIR_CLINICAL,\n });\n}\n\n/** The X12 transaction families the loop can pair. */\nexport type X12DeidVariant = \"837P\" | \"837I\" | \"837D\" | \"271\" | \"835\";\n\n/** Options accepted by {@link x12DeidLoop}. */\nexport interface X12DeidLoopOptions {\n /** The seed. Defaults to `0`. */\n readonly seed?: number;\n /** The transaction family. Defaults to `\"837P\"`. */\n readonly variant?: X12DeidVariant;\n}\n\n/** Dispatch an X12 variant to its generator. @internal */\nfunction generateX12(variant: X12DeidVariant, seed: number): X12Interchange {\n switch (variant) {\n case \"837P\":\n return generate837P({ seed });\n case \"837I\":\n return generate837I({ seed });\n case \"837D\":\n return generate837D({ seed });\n case \"271\":\n return generate271({ seed });\n case \"835\":\n return generate835({ seed });\n }\n}\n\n/**\n * Run the pairing loop for **X12 005010**: generate a spec-clean transaction through `@cosyte/x12`'s\n * builders, plant PHI sentinels across the subscriber/patient loops, de-identify through\n * `@cosyte/deid/x12`, and verify removal + clinical retention.\n *\n * @param options - The seed and transaction family. See {@link X12DeidLoopOptions}.\n * @returns The {@link DeidLoopResult} for the transaction.\n * @example\n * ```ts\n * import { x12DeidLoop } from \"@cosyte/synth/deid\";\n * x12DeidLoop({ seed: 1, variant: \"837P\" }).survivors; // => []\n * ```\n */\nexport function x12DeidLoop(options: X12DeidLoopOptions = {}): DeidLoopResult {\n const seed = options.seed ?? 0;\n const variant: X12DeidVariant = options.variant ?? \"837P\";\n const interchange = generateX12(variant, seed);\n const original = serializeX12(interchange);\n const planted = identifierSentinels(extractX12Loci(interchange).loci, original);\n const deidentified = deidentifyX12(interchange, { policy: POLICY }).x12;\n return assembleVerdict({\n format: \"x12\",\n artifact: variant,\n seed,\n planted,\n original,\n deidentified,\n phiResidue: residue(extractX12Loci(parseX12(deidentified)).loci),\n clinicalCodes: X12_CLINICAL,\n });\n}\n\n/** The NCPDP Telecom transactions the loop can pair. */\nexport type NcpdpTelecomVariant = \"B1\" | \"B2\" | \"B3\";\n\n/** Options accepted by {@link ncpdpTelecomDeidLoop}. */\nexport interface NcpdpTelecomDeidLoopOptions {\n /** The seed. Defaults to `0`. */\n readonly seed?: number;\n /** The Telecom transaction. Defaults to `\"B1\"` (a claim, the PHI- and clinically-densest). */\n readonly transaction?: NcpdpTelecomVariant;\n}\n\n/** Dispatch an NCPDP Telecom transaction to its generator. @internal */\nfunction generateTelecomWire(transaction: NcpdpTelecomVariant, seed: number): string {\n switch (transaction) {\n case \"B1\":\n return generateB1({ seed });\n case \"B2\":\n return generateB2({ seed });\n case \"B3\":\n return generateB3({ seed });\n }\n}\n\n/**\n * Run the pairing loop for **NCPDP Telecom** (pharmacy claims): generate a spec-clean transaction\n * through `@cosyte/ncpdp`, plant PHI sentinels at the patient/cardholder segments, de-identify through\n * `@cosyte/deid/ncpdp`, and verify removal + clinical retention. **NCPDP SCRIPT is out of scope** —\n * `@cosyte/deid` ships no SCRIPT adapter ({@link DEID_LOOP_SKIPPED}).\n *\n * @param options - The seed and transaction. See {@link NcpdpTelecomDeidLoopOptions}.\n * @returns The {@link DeidLoopResult} for the transaction.\n * @example\n * ```ts\n * import { ncpdpTelecomDeidLoop } from \"@cosyte/synth/deid\";\n * ncpdpTelecomDeidLoop({ seed: 3, transaction: \"B1\" }).pass; // => true\n * ```\n */\nexport function ncpdpTelecomDeidLoop(options: NcpdpTelecomDeidLoopOptions = {}): DeidLoopResult {\n const seed = options.seed ?? 0;\n const transaction: NcpdpTelecomVariant = options.transaction ?? \"B1\";\n const original = generateTelecomWire(transaction, seed);\n const tx = parseTelecom(original);\n const planted = identifierSentinels(extractTelecomLoci(tx).loci, original);\n const deidentified = deidentifyTelecom(tx, { policy: POLICY }).telecom;\n return assembleVerdict({\n format: \"ncpdp-telecom\",\n artifact: transaction,\n seed,\n planted,\n original,\n deidentified,\n phiResidue: residue(extractTelecomLoci(parseTelecom(deidentified)).loci),\n clinicalCodes: NCPDP_CLINICAL,\n });\n}\n\n/** The C-CDA document types the loop can pair. */\nexport type CcdaDeidDocumentType = \"ccd\" | \"referral\";\n\n/** Options accepted by {@link ccdaDeidLoop}. */\nexport interface CcdaDeidLoopOptions {\n /** The seed. Defaults to `0`. */\n readonly seed?: number;\n /** The document type. Defaults to `\"ccd\"`. */\n readonly documentType?: CcdaDeidDocumentType;\n}\n\n/**\n * Run the pairing loop for **C-CDA R2.1**: generate a spec-clean document through `@cosyte/ccda`'s\n * `buildCcda`, plant PHI sentinels at the `recordTarget` patient participation, de-identify through\n * `@cosyte/deid/ccda`, and verify removal + clinical retention.\n *\n * Sentinels are read from the `<recordTarget>` element of the serialized XML (not `@cosyte/deid`'s DOM\n * extractor) so that this zero-dependency subpath constructs no XML DOM; scoping to `recordTarget` keeps\n * the sentinels patient-PHI only (`author`/`custodian` provider identity is legitimately retained).\n *\n * @param options - The seed and document type. See {@link CcdaDeidLoopOptions}.\n * @returns The {@link DeidLoopResult} for the document.\n * @example\n * ```ts\n * import { ccdaDeidLoop } from \"@cosyte/synth/deid\";\n * ccdaDeidLoop({ seed: 5, documentType: \"ccd\" }).survivors; // => []\n * ```\n */\nexport function ccdaDeidLoop(options: CcdaDeidLoopOptions = {}): DeidLoopResult {\n const seed = options.seed ?? 0;\n const documentType: CcdaDeidDocumentType = options.documentType ?? \"ccd\";\n const doc = generateCcda({ seed, documentType: documentType === \"ccd\" ? \"ccd\" : \"referralNote\" });\n const original = serializeCcda(doc);\n const planted = recordTargetSentinels(original);\n const deidentified = deidentifyCcda(doc, { policy: POLICY }).document.toString();\n return assembleVerdict({\n format: \"ccda\",\n artifact: documentType === \"ccd\" ? \"CCD\" : \"ReferralNote\",\n seed,\n planted,\n original,\n deidentified,\n phiResidue: recordTargetResidue(deidentified),\n clinicalCodes: [...EXAMPLE_CONDITIONS, ...EXAMPLE_MEDICATIONS].map((c) => c.code),\n });\n}\n\n/** A per-format row of a {@link DeidCoverageSummary}. */\nexport interface DeidCoverageRow {\n /** The covered format. */\n readonly format: string;\n /** The concrete artifacts run for this format. */\n readonly artifacts: readonly string[];\n /** Total distinctive PHI sentinels planted across the runs. */\n readonly planted: number;\n /** Total surviving sentinels — **0** on a clean pass. */\n readonly survivors: number;\n /** Total clinical tokens probed for over-scrub. */\n readonly clinicalProbed: number;\n /** Total clinical tokens over-scrubbed — **0** on a clean pass. */\n readonly clinicalScrubbed: number;\n /** `true` iff every run for this format passed. */\n readonly pass: boolean;\n}\n\n/** The aggregate coverage summary across a set of loop runs. */\nexport interface DeidCoverageSummary {\n /** One row per format. */\n readonly byFormat: readonly DeidCoverageRow[];\n /** Total sentinels planted across every run. */\n readonly totalPlanted: number;\n /** Total surviving sentinels across every run — **0** on a clean pass. */\n readonly totalSurvivors: number;\n /** Total clinical over-scrubs across every run — **0** on a clean pass. */\n readonly totalClinicalScrubbed: number;\n /** `true` iff every run passed. */\n readonly allPass: boolean;\n /** The named, deliberately-skipped format paths (from {@link DEID_LOOP_SKIPPED}). */\n readonly skipped: typeof DEID_LOOP_SKIPPED;\n}\n\n/**\n * Summarize a set of loop runs into a per-format coverage report — the \"coverage summary per format\" the\n * harness reports.\n *\n * @param results - The loop results to aggregate.\n * @returns The {@link DeidCoverageSummary}.\n * @example\n * ```ts\n * import { hl7DeidLoop, fhirDeidLoop, summarizeDeidCoverage } from \"@cosyte/synth/deid\";\n * const summary = summarizeDeidCoverage([hl7DeidLoop(), fhirDeidLoop()]);\n * summary.allPass; // => true\n * ```\n */\nexport function summarizeDeidCoverage(results: readonly DeidLoopResult[]): DeidCoverageSummary {\n const byFormatMap = new Map<string, DeidLoopResult[]>();\n for (const r of results) {\n const list = byFormatMap.get(r.format) ?? [];\n list.push(r);\n byFormatMap.set(r.format, list);\n }\n const byFormat: DeidCoverageRow[] = [];\n for (const [format, runs] of byFormatMap) {\n byFormat.push({\n format,\n artifacts: runs.map((r) => r.artifact),\n planted: runs.reduce((n, r) => n + r.planted.length, 0),\n survivors: runs.reduce((n, r) => n + r.survivors.length, 0),\n clinicalProbed: runs.reduce((n, r) => n + r.clinicalProbed.length, 0),\n clinicalScrubbed: runs.reduce((n, r) => n + r.clinicalScrubbed.length, 0),\n pass: runs.every((r) => r.pass),\n });\n }\n return {\n byFormat,\n totalPlanted: results.reduce((n, r) => n + r.planted.length, 0),\n totalSurvivors: results.reduce((n, r) => n + r.survivors.length, 0),\n totalClinicalScrubbed: results.reduce((n, r) => n + r.clinicalScrubbed.length, 0),\n allPass: results.every((r) => r.pass),\n skipped: DEID_LOOP_SKIPPED,\n };\n}\n"]}
|