diff --git a/.changeset/hl7-v2-timestamps.md b/.changeset/hl7-v2-timestamps.md new file mode 100644 index 000000000..c8eefa81a --- /dev/null +++ b/.changeset/hl7-v2-timestamps.md @@ -0,0 +1,25 @@ +--- +"@northguild/gmt": minor +--- + +A new `healthcare` namespace reads and writes the HL7 v2 date-time, the `DTM` and the older `TS` that most clinical feeds still send, such as `20240615103000-0500`. + +- `parseHL7(value)` returns what the value states: an instant (it has an offset), a local time (it has none), a partial value (a year, month, day or hour), or the HL7 null value `""`. +- `formatHL7(isoString, { precision })` writes an ISO 8601 value as a `DTM`, cut to the precision and never rounded. It never writes a `TS`, which HL7 withdrew in v2.6. +- `isValidHL7(value)` is true exactly when `parseHL7` reads the value. + +An HL7 time with no offset is the sender's local time, and HL7 says so. It is not UTC. `parseHL7` returns it as `kind: "local"` with no `instant`, so you must supply the sender's zone to `resolveLocal` to get one. A value coarser than a minute, such as a birth year, returns `kind: "partial"` and also has no instant. A `TS` degree of precision can only lower the precision, so `199904011200^L` is April 1999, not 12:00. + +```typescript +import { formatHL7, parseHL7, resolveLocal } from "@northguild/gmt"; + +parseHL7("20240615103000-0500"); +// { kind: "instant", instant: "2024-06-15T15:30:00Z", offset: "-05:00", local: "2024-06-15T10:30:00", precision: "second" } + +parseHL7("20240615103000"); // { kind: "local", local: "2024-06-15T10:30:00", precision: "second" } +resolveLocal("2024-06-15T10:30:00", "Europe/Helsinki"); // "2024-06-15T07:30:00Z" + +formatHL7("2024-06-15T15:30:00Z"); // "20240615153000+0000" +``` + +`parseHL7` returns `null`, `formatHL7` returns `""` and `isValidHL7` returns `false` for a value that does not fit, a day the month lacks, an hour of 24 or a second of 60. None of them throws. The functions are also at `@northguild/gmt/healthcare`, `@northguild/gmt/healthcare/parse`, `@northguild/gmt/healthcare/format` and `@northguild/gmt/healthcare/validate`, with the types `Hl7DateTime`, `Hl7Precision`, `Hl7PartialPrecision`, `Hl7MomentPrecision` and `Hl7FormatOptions`. diff --git a/README.md b/README.md index c0225bd95..f0e10e6fd 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ addZoned("2024-03-30T12:00:00+01:00[Europe/Berlin]", { hours: 24 }); // "2024-03 resolveLocal("2024-03-31T02:30:00", "Europe/Berlin", { disambiguation: "reject" }); // "" ``` -- **745 functions, to the nanosecond**, tested in 17 locales. +- **748 functions, to the nanosecond**, tested in 17 locales. - **Never throws.** ISO 8601 strings in. Invalid input returns `""`, `null`, `false` or `[]`. The latest test counts, CI volume and the comparison with Luxon, date-fns, Moment.js, Day.js, Spacetime and `@internationalized/date` are on the [Why GMT](https://northguild.dev/gmt/why-gmt/) page. The full comparison and the method are on the [compare](https://northguild.dev/gmt/compare/) page. @@ -79,9 +79,9 @@ convertUtcToZoned("2024-06-15T12:00:00Z", "Asia/Tokyo"); // "2024-06-15T21:00:00 ``` Every function has a reference page with a live playground: -[plain](https://northguild.dev/gmt/reference/plain/) · [zoned](https://northguild.dev/gmt/reference/zoned/) · [utc](https://northguild.dev/gmt/reference/utc/) · [unix](https://northguild.dev/gmt/reference/unix/) · [instant](https://northguild.dev/gmt/reference/instant/) · [calendar](https://northguild.dev/gmt/reference/calendar/) · [duration](https://northguild.dev/gmt/reference/duration/) · [interval](https://northguild.dev/gmt/reference/interval/) · [workforce](https://northguild.dev/gmt/reference/workforce/) · [span](https://northguild.dev/gmt/reference/span/) · [precision](https://northguild.dev/gmt/reference/precision/) · [recurrence](https://northguild.dev/gmt/reference/recurrence/) · [timescale](https://northguild.dev/gmt/reference/timescale/) · [gnss](https://northguild.dev/gmt/reference/gnss/) · [transport](https://northguild.dev/gmt/reference/transport/) · [intermodal](https://northguild.dev/gmt/reference/intermodal/) · [finance](https://northguild.dev/gmt/reference/finance/) +[plain](https://northguild.dev/gmt/reference/plain/) · [zoned](https://northguild.dev/gmt/reference/zoned/) · [utc](https://northguild.dev/gmt/reference/utc/) · [unix](https://northguild.dev/gmt/reference/unix/) · [instant](https://northguild.dev/gmt/reference/instant/) · [calendar](https://northguild.dev/gmt/reference/calendar/) · [duration](https://northguild.dev/gmt/reference/duration/) · [interval](https://northguild.dev/gmt/reference/interval/) · [workforce](https://northguild.dev/gmt/reference/workforce/) · [span](https://northguild.dev/gmt/reference/span/) · [precision](https://northguild.dev/gmt/reference/precision/) · [recurrence](https://northguild.dev/gmt/reference/recurrence/) · [timescale](https://northguild.dev/gmt/reference/timescale/) · [gnss](https://northguild.dev/gmt/reference/gnss/) · [transport](https://northguild.dev/gmt/reference/transport/) · [intermodal](https://northguild.dev/gmt/reference/intermodal/) · [finance](https://northguild.dev/gmt/reference/finance/) · [healthcare](https://northguild.dev/gmt/reference/healthcare/) -By industry: [Workforce](https://northguild.dev/gmt/industries/workforce/) · [Transport](https://northguild.dev/gmt/industries/transport/) · [Intermodal](https://northguild.dev/gmt/industries/intermodal/) · [GNSS](https://northguild.dev/gmt/industries/gnss/) · [Maritime](https://northguild.dev/gmt/industries/maritime/) · [Finance](https://northguild.dev/gmt/industries/finance/) +By industry: [Workforce](https://northguild.dev/gmt/industries/workforce/) · [Transport](https://northguild.dev/gmt/industries/transport/) · [Intermodal](https://northguild.dev/gmt/industries/intermodal/) · [GNSS](https://northguild.dev/gmt/industries/gnss/) · [Maritime](https://northguild.dev/gmt/industries/maritime/) · [Finance](https://northguild.dev/gmt/industries/finance/) · [Healthcare](https://northguild.dev/gmt/industries/healthcare/) Then the [guides](https://northguild.dev/gmt/guides/) show how to do each job, and the [tools](https://northguild.dev/gmt/tools/) let you try it on your own values. diff --git a/apps/dox/scripts/grow-measure.mjs b/apps/dox/scripts/grow-measure.mjs index 332f3f4b9..eb06d58f8 100644 --- a/apps/dox/scripts/grow-measure.mjs +++ b/apps/dox/scripts/grow-measure.mjs @@ -200,6 +200,11 @@ const PAGES = [ preset: PRESET, drag: null, }, + { + slug: "hl7-timestamp-reader", + preset: PRESET, + drag: null, + }, { slug: "x12-time-reader", preset: { ...PRESET, nth: 0 }, diff --git a/apps/dox/scripts/html-diff.mjs b/apps/dox/scripts/html-diff.mjs index 91db3d343..c9f6af140 100644 --- a/apps/dox/scripts/html-diff.mjs +++ b/apps/dox/scripts/html-diff.mjs @@ -122,6 +122,10 @@ const PAGES = [ path: "tools/dtm-decoder", widget: "dtm-decoder", }, + { + path: "tools/hl7-timestamp-reader", + widget: "hl7-timestamp-reader", + }, { path: "tools/x12-time-reader", widget: "x12-time-reader", diff --git a/apps/dox/scripts/visual-snapshot.mjs b/apps/dox/scripts/visual-snapshot.mjs index 4c4105f36..de5189105 100644 --- a/apps/dox/scripts/visual-snapshot.mjs +++ b/apps/dox/scripts/visual-snapshot.mjs @@ -133,6 +133,7 @@ const PAGES = [ { slug: "tool-eta-drift", path: "/tools/eta-drift/" }, { slug: "tool-departure-board", path: "/tools/departure-board/" }, { slug: "tool-dtm-decoder", path: "/tools/dtm-decoder/" }, + { slug: "tool-hl7-timestamp-reader", path: "/tools/hl7-timestamp-reader/" }, { slug: "tool-x12-time-reader", path: "/tools/x12-time-reader/" }, { slug: "tool-demurrage-clock", path: "/tools/demurrage-clock/" }, { slug: "tool-bl-date-stamp", path: "/tools/bl-date-stamp/" }, diff --git a/apps/dox/src/components/Hl7TimestampReader.astro b/apps/dox/src/components/Hl7TimestampReader.astro new file mode 100644 index 000000000..f1e63be6f --- /dev/null +++ b/apps/dox/src/components/Hl7TimestampReader.astro @@ -0,0 +1,54 @@ +--- +/** + * HL7 Timestamp Reader widget (HLTH-93). + * + * A typed HL7 v2 date-time (a DTM or the older TS): `parseHL7` says whether it + * states an instant, an offset, a local time or only a partial date, the widget + * reads a value with no offset in the zones you choose, and it shows what + * `formatHL7` writes back at each precision. + * + * **The markup and the wiring both live in `lib/hl7-timestamp-reader-mount.ts`**, + * so the chat rail mounts the same widget this page server-renders. + */ + +import { renderHl7TimestampReaderTemplate } from "../lib/hl7-timestamp-reader-mount"; + +/** + * `fullbleed` lets the page say the widget may use the whole main pane; see + * DtmDecoder.astro for the marker it adds and why it sits on a wrapper. + */ +interface Props { + fullbleed?: boolean; +} + +const { fullbleed = false } = Astro.props; +const html = renderHl7TimestampReaderTemplate("hl7-timestamp-reader", {}).value; +--- + +{ + fullbleed ? ( +
+ ) : ( + + ) +} + + diff --git a/apps/dox/src/components/ask/widget-graph.test.ts b/apps/dox/src/components/ask/widget-graph.test.ts index 510c9c84c..8803bcbda 100644 --- a/apps/dox/src/components/ask/widget-graph.test.ts +++ b/apps/dox/src/components/ask/widget-graph.test.ts @@ -159,6 +159,8 @@ describe("the chat island's static import graph", () => { "lib/edi-widgets.ts", "lib/edi-lib.ts", "lib/dtm-decoder.ts", + "lib/hl7-lib.ts", + "lib/hl7-timestamp-reader.ts", "lib/x12-time-reader.ts", "lib/gnss-widgets.ts", "lib/gnss-lib.ts", diff --git a/apps/dox/src/components/ask/widget-registry.ts b/apps/dox/src/components/ask/widget-registry.ts index b52818e13..2179d0225 100644 --- a/apps/dox/src/components/ask/widget-registry.ts +++ b/apps/dox/src/components/ask/widget-registry.ts @@ -68,6 +68,7 @@ import type { PunctualityBoardArgs } from "~/lib/punctuality-board-mount"; import type { EtaDriftArgs } from "~/lib/eta-drift-mount"; import type { DepartureBoardArgs } from "~/lib/departure-board-mount"; import type { DtmDecoderArgs } from "~/lib/dtm-decoder-mount"; +import type { Hl7Args } from "~/lib/hl7-timestamp-reader-mount"; import type { X12TimeReaderArgs } from "~/lib/x12-time-reader-mount"; import type { ZonePlannerArgs } from "~/lib/zone-planner-mount"; import type { GnssWeekDecoderArgs } from "~/lib/gnss-week-decoder-mount"; @@ -107,6 +108,7 @@ import { showDepartureBoardInput, showDstInspectorInput, showDtmDecoderInput, + showHl7TimestampReaderInput, showEpcisEventReaderInput, showElapsedVsClockInput, showGnssRolloverCheckerInput, @@ -640,6 +642,31 @@ const dtmEntry = defineWidget({ checkZones([zone1, zone2, zone3, zone4].filter((z): z is string => !!z)), }); +const hl7Entry = defineWidget({ + title: "HL7 timestamp reader", + kind: "hl7", + parse: (input) => { + const result = showHl7TimestampReaderInput.safeParse(input); + return result.success + ? { ok: true, args: result.data } + : { + ok: false, + reason: "The widget was asked for with arguments that don't fit.", + }; + }, + /* Seeded in the template and again by the mount: every argument is a control + value. Only the four zones are checked here; a value the library does not + read is the widget's own NO SIGNAL, with its reason. */ + load: () => + import("~/lib/hl7-timestamp-reader-mount").then((m) => ({ + renderTemplate: (idPrefix, args) => + m.renderHl7TimestampReaderTemplate(idPrefix, args), + mount: m.mountHl7TimestampReader, + })), + validate: ({ zone1, zone2, zone3, zone4 }) => + checkZones([zone1, zone2, zone3, zone4].filter((z): z is string => !!z)), +}); + const x12TimeEntry = defineWidget({ title: "X12 time reader", kind: "xtime", @@ -1332,6 +1359,7 @@ export const WIDGET_REGISTRY: Record = { showDepartureBoard: departureEntry, showZonePlanner: plannerEntry, showDtmDecoder: dtmEntry, + showHl7TimestampReader: hl7Entry, showX12TimeReader: x12TimeEntry, showDemurrageClock: demurrageEntry, showBlDateStamp: blDateEntry, diff --git a/apps/dox/src/content/docs/guides/index.mdx b/apps/dox/src/content/docs/guides/index.mdx index d2f2fbcab..5b3cc2c6f 100644 --- a/apps/dox/src/content/docs/guides/index.mdx +++ b/apps/dox/src/content/docs/guides/index.mdx @@ -20,7 +20,7 @@ same patterns to coding agents. | [Conversion](./conversion/) | Between plain/zoned/unix/UTC and calendar systems, foreign epochs (NTP, FILETIME, Excel, PostgreSQL), time-ordered IDs, [database timestamps](./conversion/databases/) (PostgreSQL, MySQL, SQL Server, Oracle, SQLite, MongoDB, DynamoDB, Redis, Couchbase, Cassandra, ScyllaDB, Neo4j), Parquet, Arrow, protobuf | | [Intervals](./intervals/interval-basics/) | Range math — containment, overlap, set operations, splitting, [hours of work](./industries/workforce-hours-of-work/) | | [Integration](./integration/) | Cache keys, routers, tables, lint config | -| [Industries](./industries/) | The industry layers on top of the core — transport legs and dwell, cut-offs, multi-leg scheduling, punctuality and timestamp classes, free time and demurrage, billing deadlines, bill of lading dates and multimodal ETAs, EDI timestamps — with real-world scenarios | +| [Industries](./industries/) | The industry layers on top of the core — transport legs and dwell, cut-offs, multi-leg scheduling, punctuality and timestamp classes, free time and demurrage, billing deadlines, bill of lading dates and multimodal ETAs, EDI timestamps, HL7 clinical timestamps — with real-world scenarios | | [How-to](./how-to/) | Short answers to common tasks — add business days, convert between time zones, check whether a local time exists on a DST day | ## Reading order diff --git a/apps/dox/src/content/docs/guides/industries/healthcare-clinical-timestamps.mdx b/apps/dox/src/content/docs/guides/industries/healthcare-clinical-timestamps.mdx new file mode 100644 index 000000000..2addb8044 --- /dev/null +++ b/apps/dox/src/content/docs/guides/industries/healthcare-clinical-timestamps.mdx @@ -0,0 +1,310 @@ +--- +title: "Healthcare: Clinical Timestamps" +description: Read and write the date-times in HL7 version 2 messages, keep a time with no offset local until you name the sender's zone, and keep a partial date a span. +sidebar: + order: 11 +industries: [healthcare] +--- + +HL7 International calls HL7 version 2 "one of the most widely implemented standards for +healthcare information in the world" +([HL7 product list](https://tscwiki.hl7.org/TSC_Product_List_V2)). The date-time in a version 2 +message is not ISO 8601. The number of digits says how precise the value is, and the offset is +optional. A reader that takes a value without an offset for UTC moves every event by the offset +of the place that sent it, and a reader that pads a year to a moment states a fact nobody sent. + +There are three functions: `parseHL7` reads a value, `formatHL7` writes one and `isValidHL7` +checks one. Each takes a string and returns a string, an object or a boolean, and none of them +throws. A call the types accept returns the sentinel (`null`, `""` or `false`) when the value is +wrong. + +```typescript +import { parseHL7 } from "@northguild/gmt/healthcare/parse"; +import { formatHL7 } from "@northguild/gmt/healthcare/format"; +import { isValidHL7 } from "@northguild/gmt/healthcare/validate"; +``` + +Each function has a page in the [healthcare reference](/reference/healthcare/parse/), with a +playground that runs it. + +## HL7 version 2: DTM and TS + +The standard names two types. `DTM` is the date-time. `TS` is the older time stamp, a `DTM` +followed by a degree of precision. The degree is kept only for backward compatibility, and +version 2.6 withdrew `TS`. HL7's own chapters call them 2.A.22 and 2.A.77, and the degree 2.A.77.2 +(headed 2.A.1.22, 2.A.1.77 and 2.A.1.77.2 in the hl7.eu copy of version 2.5.1). + +### The four kinds + +`parseHL7` returns one of four kinds, or `null` for a value it does not read. + +| Kind | When | Members | +| ----------- | --------------------------------------- | ---------------------------------------- | +| `"instant"` | a minute or finer, with an offset | `instant`, `offset`, `local`, `precision` | +| `"local"` | a minute or finer, no offset | `local`, `precision` | +| `"partial"` | year, month, day or hour, or cut to one by a `TS` degree | `local`, `offset`, `precision` | +| `"null"` | the null value `""` | none | + +```typescript +import { parseHL7 } from "@northguild/gmt/healthcare/parse"; + +parseHL7("20240615103000+0300"); +// { kind: "instant", instant: "2024-06-15T07:30:00Z", offset: "+03:00", +// local: "2024-06-15T10:30:00", precision: "second" } +parseHL7("20240615103000"); +// { kind: "local", local: "2024-06-15T10:30:00", precision: "second" } +parseHL7("20240615"); +// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } +parseHL7('""'); +// { kind: "null" } +parseHL7("2024-06-15"); +// null +``` + +The type makes you check `kind` before you read `instant`. Only the `"instant"` kind has one. + +### Precision is the number of digits + +The picture in 2.A.22 is `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`, and the standard says +"The number of characters populated (excluding the time zone specification) specifies the +precision". The digits sent are the precision. + +| Digits sent | Precision | +| ---------------------- | ------------ | +| 4 | `"year"` | +| 6 | `"month"` | +| 8 | `"day"` | +| 10 | `"hour"` | +| 12 | `"minute"` | +| 14 | `"second"` | +| 14, a point, 1 to 4 | `"fraction"` | + +`local` is written at the precision sent, so an hour is `2024-06-15T10` and no minute is added. +From the minute on, seconds are always written, so a minute reads as `10:30:00`. At most four +fraction digits are read, and the fraction is kept as it was sent. + +```typescript +parseHL7("2024061510"); +// { kind: "partial", local: "2024-06-15T10", offset: "", precision: "hour" } +parseHL7("202406151030"); +// { kind: "local", local: "2024-06-15T10:30:00", precision: "minute" } +parseHL7("20240615103000.1234"); +// { kind: "local", local: "2024-06-15T10:30:00.1234", precision: "fraction" } +parseHL7("20240615103000.12345"); +// null +``` + +### The offset that is not there + +2.A.22 says "if the time zone is not included, the time zone defaults to that of the local time +zone of the sender". A value with no offset is the sender's local time, so the `"local"` kind +has no instant. Appending `Z` would state a place the message never named. + +An offset is `+` or `-` and four digits. `+0000` and `-0000` both mean UTC and both read as +`+00:00`. The standard restricts offsets to "legally-defined time zones" but names no list, so +any hour from `00` to `23` and minute from `00` to `59` is read. + +```typescript +parseHL7("20240615103000+0000"); +// { kind: "instant", instant: "2024-06-15T10:30:00Z", offset: "+00:00", +// local: "2024-06-15T10:30:00", precision: "second" } +parseHL7("20240615103000-0000"); +// { kind: "instant", instant: "2024-06-15T10:30:00Z", offset: "+00:00", +// local: "2024-06-15T10:30:00", precision: "second" } +parseHL7("20240615103000+0530"); +// { kind: "instant", instant: "2024-06-15T05:00:00Z", offset: "+05:30", +// local: "2024-06-15T10:30:00", precision: "second" } +``` + +### From a local time to an instant + +When the message names no offset, you know the zone and GMT does not. Pass the `local` member and +the sending facility's IANA zone to `resolveLocal`: + +```typescript +import { parseHL7 } from "@northguild/gmt/healthcare/parse"; +import { resolveLocal } from "@northguild/gmt/instant/convert"; + +const result = parseHL7("20240615103000"); +if (result?.kind === "local") { + resolveLocal(result.local, "Europe/Helsinki"); // "2024-06-15T07:30:00Z" +} +``` + +A wall time can fall in an hour the zone skips or repeats. `resolveLocal` takes a +`disambiguation` option for those, and its [reference page](/reference/instant/convert/resolveLocal/) +says what each value does. `"reject"` returns `""` instead of choosing: + +```typescript +resolveLocal("2024-03-31T03:30:00", "Europe/Helsinki"); // "2024-03-31T01:30:00Z" — 03:30 was skipped; the default, "compatible", takes the later reading +resolveLocal("2024-03-31T03:30:00", "Europe/Helsinki", { disambiguation: "reject" }); // "" +resolveLocal("2024-10-27T03:30:00", "Europe/Helsinki"); // "2024-10-27T00:30:00Z" — 03:30 happened twice; "compatible" takes the earlier reading +resolveLocal("2024-10-27T03:30:00", "Europe/Helsinki", { disambiguation: "later" }); // "2024-10-27T01:30:00Z" — 03:30 happened twice +resolveLocal("2024-10-27T03:30:00", "Europe/Helsinki", { disambiguation: "reject" }); // "" +``` + +### A partial value names a span + +`1965` is a birth year. It is not 1 January 1965 at midnight, and padding it to a moment states a +fact the sender did not send. A `"partial"` value keeps its precision and has no instant. It keeps +an offset when one was sent with it. + +```typescript +parseHL7("1965"); +// { kind: "partial", local: "1965", offset: "", precision: "year" } +parseHL7("196506"); +// { kind: "partial", local: "1965-06", offset: "", precision: "month" } +parseHL7("20240615-0500"); +// { kind: "partial", local: "2024-06-15", offset: "-05:00", precision: "day" } +``` + +### `TS` and its degree of precision + +A `TS` is a `DTM`, then `^`, then one of `Y L D H M S` (year, month, day, hour, minute, second). +The degree only lowers the precision. 2.A.77.2 says it "is either the same as or overrides the +precision indicated by the first component. It may not indicate greater precision". + +```typescript +parseHL7("199904011200^L"); +// { kind: "partial", local: "1999-04", offset: "", precision: "month" } — April 1999 +parseHL7("20240615103000.1234^S"); +// { kind: "local", local: "2024-06-15T10:30:00", precision: "second" } — the fraction is cut +parseHL7("20240615^S"); +// null — a second is finer than the day sent +parseHL7("20240615^"); +// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — an empty degree is absent +parseHL7("20240615^D^"); +// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — so is an empty third component +``` + +A field read on its own carries no MSH-2, so `parseHL7` takes the separators Figure 2-1 +recommends: `^` between components and `&` between subcomponents (ch. 2 §2.5.4). A feed whose +MSH-2 names others re-joins the field with `^` and `&` before it calls `parseHL7`. + +A receiver ignores "components, subcomponents, and extra repetitions of a field that are present +but were not expected" (ch. 2 §2.6.2), and a later version of HL7 adds components at the end of a +data type (§2.8.1, §2.8.2). So a third component, and anything after a component's first `&`, is +not read. A component left empty is not present, so an empty `DTM` returns `null`. + +```typescript +parseHL7("20240615^D^X"); +// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — the third component is ignored +parseHL7("2024&X"); +// { kind: "partial", local: "2024", offset: "", precision: "year" } — so is the subcomponent +parseHL7("&X"); +// null — the DTM before the subcomponent is empty +``` + +### Midnight is the start of the day + +2.A.22 gives `198807050000` as "Midnight of the night extending from July 4 to July 5, 1988", so +`0000` is the start of the stated day. Hour `24` and second `60` are refused. + +```typescript +parseHL7("198807050000"); +// { kind: "local", local: "1988-07-05T00:00:00", precision: "minute" } +parseHL7("2024061524"); +// null +parseHL7("20240615103060"); +// null +``` + +### The null value + +A field that holds two double quotes (`""`) is the null value. It clears a stored value, and +chapter 2 says it "is different from omitting an optional data field". `parseHL7` returns it as +its own kind. An empty string is not the null value and returns `null`. Never treat one as the +other. + +```typescript +parseHL7('""'); // { kind: "null" } +parseHL7(""); // null +``` + +### Writing a `DTM` + +`formatHL7` takes an ISO 8601 value and writes a `DTM`. It writes the offset the value has, and +`Z` writes `+0000`. It never writes a `TS`. The precision is the one the input is written in, and +the `precision` option only lowers it. It cuts and never rounds, so a fraction of `.98765` is +written as `.9876`. + +```typescript +import { formatHL7 } from "@northguild/gmt/healthcare/format"; + +formatHL7("2024-06-15T10:30:00"); // "20240615103000" +formatHL7("2024-06-15T10:30"); // "202406151030" +formatHL7("2024-06-15T10:30:00Z"); // "20240615103000+0000" +formatHL7("2024-06-15T10:30:45.98765-05:00"); // "20240615103045.9876-0500" +formatHL7("2024-06-15T10:30:45.5Z", { precision: "minute" }); // "202406151030+0000" +``` + +A `"local"` value read at minute precision comes back from `parseHL7` with `:00` seconds, so +writing it with the digits it was sent with takes the precision `parseHL7` returned. A +`"partial"` value with an offset has no ISO input form, because `2024-06-15-05:00` is not ISO +8601. Write it from the instant, at the precision you want: + +```typescript +const r = parseHL7("202406151030"); +if (r?.kind === "local") { + formatHL7(r.local); // "20240615103000" — seconds added + formatHL7(r.local, { precision: r.precision }); // "202406151030" — the digits sent +} +formatHL7("2024-06-15T10:30:00-05:00", { precision: "day" }); // "20240615-0500" +formatHL7("2024-06-15-05:00"); // "" — not ISO 8601 +``` + +`formatHL7` returns `""` when it cannot write the value without changing it: an offset with +seconds, a year outside 0000–9999, a reduced ISO form with an offset, a zone annotation with no +offset (choosing the offset is a disambiguation it does not make) and a precision finer than the +input. + +```typescript +formatHL7("2024-06-15T10:30:00+05:30:15"); // "" — the offset has seconds +formatHL7("+010000-01-01T00:00:00"); // "" — the year is outside 0000–9999 +formatHL7("2024-06-15T10:30:00[Europe/Helsinki]"); // "" — a zone, and no offset to write +formatHL7("2024-06-15T10:30:00", { precision: "fraction" }); // "" — there is no fraction to write +``` + +### Check before reading + +`isValidHL7` is `parseHL7(value) !== null`, so the two cannot disagree. The null value is valid. + +```typescript +import { isValidHL7 } from "@northguild/gmt/healthcare/validate"; + +isValidHL7("20240615103000"); // true +isValidHL7("199904011200^L"); // true +isValidHL7('""'); // true +isValidHL7(""); // false +isValidHL7("20240615^S"); // false +``` + +### What is not read + +These return `null` from `parseHL7` and `false` from `isValidHL7`: a separator other than `^` +and `&`, an empty `DTM`, a lower-case degree, a leap second, more than four fraction digits and +ISO 8601 extended form (`2024-06-15T10:30:00`). + +```typescript +parseHL7("20240615~D"); // null +parseHL7("^D"); // null — the DTM is empty +parseHL7("20240615^l"); // null +parseHL7("2024-06-15T10:30:00"); // null — ISO 8601 is the input of formatHL7 +``` + +### The exported types + +[`Hl7DateTime`](/reference/healthcare/parse/parseHL7/#hl7datetime) is the result of `parseHL7`. +Its `precision` is an [`Hl7PartialPrecision`](/reference/types/Hl7PartialPrecision/), year to +hour, for a `"partial"` value and an [`Hl7MomentPrecision`](/reference/types/Hl7MomentPrecision/), +minute to fraction, for an `"instant"` or `"local"` one. +[`Hl7Precision`](/reference/healthcare/format/formatHL7/#hl7precision) is the two together, and +[`Hl7FormatOptions`](/reference/healthcare/format/formatHL7/#hl7formatoptions) is the options of +`formatHL7`. + +## See it break, then work + +- [An HL7 Time Read as UTC](/scenarios/an-hl7-time-read-as-utc/) +- [A TS Date Read as a Time](/scenarios/a-ts-date-read-as-a-time/) +- [Healthcare mistakes](/mistakes/healthcare/) +- [HL7 Timestamp Reader](/tools/hl7-timestamp-reader/), a tool that reads a value of your own diff --git a/apps/dox/src/content/docs/guides/industries/index.mdx b/apps/dox/src/content/docs/guides/industries/index.mdx index 8dd35fbed..ddf4bab9a 100644 --- a/apps/dox/src/content/docs/guides/industries/index.mdx +++ b/apps/dox/src/content/docs/guides/industries/index.mdx @@ -68,6 +68,9 @@ Three things hold across every industry layer: `UTCTimestamp` at the precision its digits state, cut rather than rounded when narrowed, with a second of sixty accepted only for a leap second UTC really inserted. Draws on the leap-second table. +- [Healthcare: clinical timestamps](./healthcare-clinical-timestamps/) — read and write HL7 + version 2 dates and times, keep a time with no offset local until you name the sender's zone, + and keep a partial date a span. ## Scenarios @@ -95,7 +98,9 @@ GMT approach working, on the same live widget: - [The EPCIS Offset Nobody Kept](/scenarios/the-epcis-offset-nobody-kept/) - [A Millisecond Stamp Read as Nanoseconds](/scenarios/a-millisecond-stamp-read-as-nanoseconds/) - [Second Sixty on an Ordinary Day](/scenarios/second-sixty-on-an-ordinary-day/) +- [An HL7 Time Read as UTC](/scenarios/an-hl7-time-read-as-utc/) +- [A TS Date Read as a Time](/scenarios/a-ts-date-read-as-a-time/) The mistakes that have hurt people in these layers are collected under -[Transport mistakes](/mistakes/transport/), [Intermodal mistakes](/mistakes/intermodal/) and -[Finance mistakes](/mistakes/finance/). +[Transport mistakes](/mistakes/transport/), [Intermodal mistakes](/mistakes/intermodal/), +[Finance mistakes](/mistakes/finance/) and [Healthcare mistakes](/mistakes/healthcare/). diff --git a/apps/dox/src/content/docs/guides/integration/skills.mdx b/apps/dox/src/content/docs/guides/integration/skills.mdx index e691ef848..2138e6737 100644 --- a/apps/dox/src/content/docs/guides/integration/skills.mdx +++ b/apps/dox/src/content/docs/guides/integration/skills.mdx @@ -50,6 +50,7 @@ Sample output: - gmt-transport - gmt-intermodal - gmt-workforce + - gmt-healthcare @northguild/gmt-eslint - first-time-setup @@ -79,7 +80,7 @@ For projects that want explicit routing, pass `--map` to bind a task keyword to skill so `intent list` highlights the right match automatically: ```bash -npx @tanstack/intent@latest install --map "basics=gmt-basics" --map "arithmetic=gmt-arithmetic" --map "timezone=gmt-timezone" --map "gnss=gmt-gnss" --map "finance=gmt-finance" --map "transport=gmt-transport" --map "intermodal=gmt-intermodal" --map "workforce=gmt-workforce" --map "lint=first-time-setup" +npx @tanstack/intent@latest install --map "basics=gmt-basics" --map "arithmetic=gmt-arithmetic" --map "timezone=gmt-timezone" --map "gnss=gmt-gnss" --map "finance=gmt-finance" --map "transport=gmt-transport" --map "intermodal=gmt-intermodal" --map "workforce=gmt-workforce" --map "healthcare=gmt-healthcare" --map "lint=first-time-setup" ``` ## Allowlist skills @@ -127,6 +128,7 @@ its tasks use `gmt-gnss`. | Industry | Slug | Task area | Source folders it points to | | --- | --- | --- | --- | | Workforce | `gmt-workforce` | Hours-of-work rules over a duty log, with the caller's own limits | `src/workforce/` | +| Healthcare | `gmt-healthcare` | HL7 v2 date-times, with the sender's local time kept apart from UTC | `src/healthcare/` | | Transport | `gmt-transport` | Transit legs, connections, cut-offs, punctuality, departures | `src/transport/` | | Intermodal | `gmt-intermodal` | Free time, demurrage, billing deadlines, bill of lading dates, EDI and EPCIS timestamps | `src/intermodal/` | | GNSS | `gmt-gnss` | GNSS time scales, broadcast and RINEX week numbers, rollover eras | `src/gnss/` | diff --git a/apps/dox/src/content/docs/install.mdx b/apps/dox/src/content/docs/install.mdx index f4458a215..3dc4466d7 100644 --- a/apps/dox/src/content/docs/install.mdx +++ b/apps/dox/src/content/docs/install.mdx @@ -170,3 +170,4 @@ The industry skills are layers on top of those four, not part of Core: | `@northguild/gmt` | `gmt-transport` | Transit legs, connections, cut-offs, punctuality, departures | | `@northguild/gmt` | `gmt-intermodal` | Free time, demurrage, billing deadlines, bill of lading dates, EDI and EPCIS timestamps | | `@northguild/gmt` | `gmt-workforce` | Hours-of-work rules over a duty log, with the caller's own limits | +| `@northguild/gmt` | `gmt-healthcare` | HL7 v2 date-times, with the sender's local time kept apart from UTC | diff --git a/apps/dox/src/content/docs/mistakes/healthcare.mdx b/apps/dox/src/content/docs/mistakes/healthcare.mdx new file mode 100644 index 000000000..1de0e16ce --- /dev/null +++ b/apps/dox/src/content/docs/mistakes/healthcare.mdx @@ -0,0 +1,108 @@ +--- +title: Healthcare mistakes +description: Common mistakes with HL7 version 2 dates and times, from an offset that is not there to a degree of precision that was dropped, in GMT's healthcare layer. +industries: [healthcare] +sidebar: + label: Healthcare +--- + +The healthcare layer reads the date-times of clinical messages. The mistakes around them are the +ones a hand-written reader makes: taking a value with no offset for UTC, padding a year to a +moment, dropping the precision a time stamp carries, treating the null value as an empty field, +reading midnight as the end of the day before, and rounding when writing. Every output shown here +is what the code returns. + +import Mistake from "../../../components/Mistake.astro"; + +## HL7 version 2 + + + + + + + + + + + + diff --git a/apps/dox/src/content/docs/mistakes/index.mdx b/apps/dox/src/content/docs/mistakes/index.mdx index 8a4c352b9..5cbd66f6c 100644 --- a/apps/dox/src/content/docs/mistakes/index.mdx +++ b/apps/dox/src/content/docs/mistakes/index.mdx @@ -62,6 +62,10 @@ and (where applicable) a live playground you can tinker with. - [B/L Date and Multimodal ETA Mistakes](/mistakes/intermodal/#bl-dates-and-multimodal-eta) - [EDI Timestamp Mistakes](/mistakes/intermodal/#edi-timestamps) +## Healthcare + +- [Healthcare Mistakes](/mistakes/healthcare/) + ## Satellite time - [GNSS Mistakes](/mistakes/gnss/) diff --git a/apps/dox/src/content/docs/scenarios/a-ts-date-read-as-a-time.mdx b/apps/dox/src/content/docs/scenarios/a-ts-date-read-as-a-time.mdx new file mode 100644 index 000000000..83ff3c4f2 --- /dev/null +++ b/apps/dox/src/content/docs/scenarios/a-ts-date-read-as-a-time.mdx @@ -0,0 +1,33 @@ +--- +title: "A TS Date Read as a Time" +description: An older HL7 time stamp whose degree of precision says month, read as noon on the first of April. +industries: [healthcare] +--- + +import Scenario from "~/components/Scenario.astro"; + + + +Type `199904011200^L` into the widget and it returns a month. Delete `^L` and the same digits read +as a time. The full rules are in +[Healthcare: Clinical Timestamps](/guides/industries/healthcare-clinical-timestamps/#ts-and-its-degree-of-precision). diff --git a/apps/dox/src/content/docs/scenarios/an-hl7-time-read-as-utc.mdx b/apps/dox/src/content/docs/scenarios/an-hl7-time-read-as-utc.mdx new file mode 100644 index 000000000..bf3ac7790 --- /dev/null +++ b/apps/dox/src/content/docs/scenarios/an-hl7-time-read-as-utc.mdx @@ -0,0 +1,38 @@ +--- +title: "An HL7 Time Read as UTC" +description: A lab observation time sent as an HL7 date-time with no offset, stored as a UTC instant the message never stated. +industries: [healthcare] +--- + +import Scenario from "~/components/Scenario.astro"; + + + +The widget opens on a value sent with `-0500`, which is an instant. Delete `-0500` and it becomes +a local time with no instant, because the message no longer names a place. The full rules +are in [Healthcare: Clinical Timestamps](/guides/industries/healthcare-clinical-timestamps/). + +To read a value of your own, use the [HL7 Timestamp Reader](/tools/hl7-timestamp-reader/). diff --git a/apps/dox/src/content/docs/tools/hl7-timestamp-reader.mdx b/apps/dox/src/content/docs/tools/hl7-timestamp-reader.mdx new file mode 100644 index 000000000..90773956f --- /dev/null +++ b/apps/dox/src/content/docs/tools/hl7-timestamp-reader.mdx @@ -0,0 +1,43 @@ +--- +title: HL7 Timestamp Reader +description: "Type an HL7 v2 date-time. parseHL7 says whether it states an instant, an offset, a local time or only a partial date, and the tool reads a value with no offset in the zones you choose and shows what formatHL7 writes back at each precision." +industries: [healthcare] +--- + +import Hl7TimestampReader from "../../../components/Hl7TimestampReader.astro"; +import ToolLayout from "../../../components/ToolLayout.astro"; + + + + + +An HL7 time with no offset is the sender's local time. It is not UTC. + + + + + +Type an HL7 v2 date-time, the `DTM` of a field or the older `TS` with its precision code. HL7 v2 is published by HL7 International. The tool calls [`parseHL7`](/reference/healthcare/parse/parseHL7/) and shows what the value states: how many digits it carries, whether it has an offset, and whether it is a time at all. A value with no offset is read in the zones you choose, and the last section shows what [`formatHL7`](/reference/healthcare/format/formatHL7/) writes back at each precision. + + + + + + + +**How a value is read.** The tool reads one field. No `MSH-2` is read, so `^` separates the components and `&` the subcomponents, as HL7 recommends, and a message with other separators is not read as a message. A third component, and anything after a component's first `&`, is shown as ignored and not read, because HL7 tells a receiver to ignore what it does not expect. A value that is not a date-time shows `NO SIGNAL` with one sentence saying why. + +**The four kinds.** A value to the minute or finer, with an offset, is an instant. The same with no offset is a local time. A year, a month, a day or an hour is a partial value, with or without an offset, and so is a finer value that a `TS` degree of precision cuts to one of those. A partial value has a precision and no instant, and the tool never pads it. The null value, two quote characters, is its own kind. It clears a stored time, and it is not a missing field. + +**Why the zones are yours.** The library maps no facility to a zone, so the four zones are your picks. The presets open with example zones, and the value does not say any of them. Each row calls [`resolveLocal`](/reference/instant/convert/resolveLocal/) with `disambiguation: "reject"`: a time the clock shows twice, or never, is not resolved, and the row says why. The strip also sets each result against the same digits read as UTC, which is the mistake the page is about. + +**What is written back.** The last section calls `formatHL7` once for each precision, from year to fraction, on the same moment. It cuts to the precision asked for and never rounds. A precision finer than the value carries is not made up. + +**The functions.** [`parseHL7`](/reference/healthcare/parse/parseHL7/) reads, [`formatHL7`](/reference/healthcare/format/formatHL7/) writes and [`isValidHL7`](/reference/healthcare/validate/isValidHL7/) tells a bad value from a good one. The rules are in [Healthcare: Clinical Timestamps](/guides/industries/healthcare-clinical-timestamps/). + +**Worth trying:** [a month sent as a time stamp](/tools/hl7-timestamp-reader/?w=hl7&wa=%7B%22preset%22%3A%22ts-month%22%7D) — +the value is a partial one, and no instant appears. Then [a time that falls in the hour the clocks go back](/tools/hl7-timestamp-reader/?w=hl7&wa=%7B%22preset%22%3A%22fall-back%22%7D): the clock shows it twice, so the zones that observe the change refuse it. + + + + diff --git a/apps/dox/src/data/gmt-stats.json b/apps/dox/src/data/gmt-stats.json index d6f9eb816..3270c623b 100644 --- a/apps/dox/src/data/gmt-stats.json +++ b/apps/dox/src/data/gmt-stats.json @@ -1,8 +1,8 @@ { "suite": "packages/gmt", - "tests": 72507, - "files": 957, - "executions": 2175210, + "tests": 72935, + "files": 961, + "executions": 2188050, "nodes": ["22", "24", "26"], "timezones": 10, "timezoneList": [ @@ -37,7 +37,7 @@ "ru-RU", "tr-TR" ], - "functions": 745, + "functions": 748, "patterns": 30, "byNamespace": [ { @@ -107,6 +107,10 @@ { "namespace": "finance", "count": 3 + }, + { + "namespace": "healthcare", + "count": 3 } ], "industryNamespaces": [ @@ -114,7 +118,8 @@ "transport", "workforce", "gnss", - "finance" + "finance", + "healthcare" ], "industryLayers": [ { @@ -181,7 +186,13 @@ "label": "Finance", "own": 3, "drawsOn": [] + }, + { + "id": "healthcare", + "label": "Healthcare", + "own": 3, + "drawsOn": [] } ], - "industryFunctions": 87 + "industryFunctions": 90 } diff --git a/apps/dox/src/data/industries.json b/apps/dox/src/data/industries.json index e613dfc56..008b9a6f1 100644 --- a/apps/dox/src/data/industries.json +++ b/apps/dox/src/data/industries.json @@ -51,5 +51,14 @@ "guide": "/guides/industries/finance-message-timestamps/", "namespace": "finance", "drawsOn": [] + }, + { + "id": "healthcare", + "label": "Healthcare", + "definition": "Timestamps in HL7 clinical messages: a precision set by the number of digits sent, and a missing offset that means the sender's local time.", + "icon": "industry-healthcare", + "guide": "/guides/industries/healthcare-clinical-timestamps/", + "namespace": "healthcare", + "drawsOn": [] } ] diff --git a/apps/dox/src/generated/reference/gmt-corpus.json b/apps/dox/src/generated/reference/gmt-corpus.json index ef9d323f0..6dcf45b91 100644 --- a/apps/dox/src/generated/reference/gmt-corpus.json +++ b/apps/dox/src/generated/reference/gmt-corpus.json @@ -2567,6 +2567,141 @@ } ] }, + { + "url": "/reference/healthcare/format/formatHL7", + "page": "/reference/healthcare/format/formatHL7", + "name": "formatHL7", + "namespace": "healthcare", + "module": "format", + "kind": "function", + "signature": "formatHL7(value: string, options?: Hl7FormatOptions): string", + "description": "Write an ISO 8601 string as an HL7 v2 date-time (`DTM`): the inverse of `parseHL7`.", + "sourcePath": "packages/gmt/src/healthcare/format/formatHL7.ts", + "examples": [ + { + "call": "formatHL7(\"2024-06-15T10:30:00-05:00\")", + "result": "\"20240615103000-0500\"" + }, + { + "call": "formatHL7(\"2024-06-15T15:30:00Z\")", + "result": "\"20240615153000+0000\"" + }, + { + "call": "formatHL7(\"2024-06-15T10:30:00\")", + "result": "\"20240615103000\" (the sender's local time)" + }, + { + "call": "formatHL7(\"2024-06-15T10:30:45.98765-05:00\")", + "result": "\"20240615103045.9876-0500\" (cut, not rounded)" + }, + { + "call": "formatHL7(\"2024-06-15T10:30:45.98765-05:00\", { precision: \"day\" })", + "result": "\"20240615-0500\"" + }, + { + "call": "formatHL7(\"2024-06\", { precision: \"day\" })", + "result": "\"\" (finer than the value carries)" + }, + { + "call": "formatHL7(\"2024-06-15-05:00\")", + "result": "\"\" (not ISO 8601)" + }, + { + "call": "formatHL7(\"2024-06-15T10:30:00[Europe/Helsinki]\")", + "result": "\"\" (a zone with no offset)" + }, + { + "call": "formatHL7(\"2024-02-30\")", + "result": "\"\" (no such day)" + } + ] + }, + { + "url": "/reference/healthcare/parse/parseHL7", + "page": "/reference/healthcare/parse/parseHL7", + "name": "parseHL7", + "namespace": "healthcare", + "module": "parse", + "kind": "function", + "signature": "parseHL7(value: string): Hl7DateTime | null", + "description": "Read an HL7 v2 date-time (`DTM`, or the older `TS`) as what it states: a moment, the sender's local time, or a span.", + "sourcePath": "packages/gmt/src/healthcare/parse/parseHL7.ts", + "examples": [ + { + "call": "parseHL7(\"20240615103000-0500\")", + "result": "{ kind: \"instant\", instant: \"2024-06-15T15:30:00Z\", offset: \"-05:00\", local: \"2024-06-15T10:30:00\", precision: \"second\" }" + }, + { + "call": "parseHL7(\"20240615103000\")", + "result": "{ kind: \"local\", local: \"2024-06-15T10:30:00\", precision: \"second\" }" + }, + { + "call": "parseHL7(\"20240615\")", + "result": "{ kind: \"partial\", local: \"2024-06-15\", offset: \"\", precision: \"day\" }" + }, + { + "call": "parseHL7(\"199904011200^L\")", + "result": "{ kind: \"partial\", local: \"1999-04\", offset: \"\", precision: \"month\" }" + }, + { + "call": "parseHL7(\"20240615^D^X\")", + "result": "{ kind: \"partial\", local: \"2024-06-15\", offset: \"\", precision: \"day\" }" + }, + { + "call": "parseHL7('\"\"')", + "result": "{ kind: \"null\" }" + }, + { + "call": "parseHL7(\"\")", + "result": "null" + }, + { + "call": "parseHL7(\"20240615240000\")", + "result": "null (hour 24)" + } + ] + }, + { + "url": "/reference/healthcare/validate/isValidHL7", + "page": "/reference/healthcare/validate/isValidHL7", + "name": "isValidHL7", + "namespace": "healthcare", + "module": "validate", + "kind": "function", + "signature": "isValidHL7(value: string): boolean", + "description": "Return true when `value` is an HL7 v2 `DTM`, or a `TS` with a degree of precision the digits carry, that `parseHL7` reads.", + "sourcePath": "packages/gmt/src/healthcare/validate/isValidHL7.ts", + "examples": [ + { + "call": "isValidHL7(\"20240615103000-0500\")", + "result": "true" + }, + { + "call": "isValidHL7(\"2024\")", + "result": "true" + }, + { + "call": "isValidHL7('\"\"')", + "result": "true (the null value)" + }, + { + "call": "isValidHL7(\"20240615^D^X\")", + "result": "true (the third component is ignored)" + }, + { + "call": "isValidHL7(\"20240615^S\")", + "result": "false (a degree finer than the digits)" + }, + { + "call": "isValidHL7(\"20240230\")", + "result": "false (30 February)" + }, + { + "call": "isValidHL7(\"\")", + "result": "false (not the null value)" + } + ] + }, { "url": "/reference/types/LocalTimeClassification", "page": "/reference/types/LocalTimeClassification", @@ -21727,6 +21862,75 @@ } ] }, + { + "url": "/reference/healthcare/format/formatHL7#hl7precision", + "page": "/reference/healthcare/format/formatHL7", + "name": "Hl7Precision", + "namespace": "types", + "module": "hl7", + "kind": "type", + "signature": "", + "description": "The precision of an HL7 v2 date-time, coarsest first. HL7 v2.5.1 ch. 2A 2.A.22 (headed 2.A.1.22 in the [hl7.eu v2.5.1 copy](https://www.hl7.eu/HL7v2x/v251/std251/ch02a.html)): \"The number of characters populated (excluding the time zone specification) specifies the precision\". The characters before the offset, per member:", + "sourcePath": "packages/gmt/src/types/hl7.ts", + "examples": [], + "inlineOn": "formatHL7" + }, + { + "url": "/reference/types/Hl7PartialPrecision", + "page": "/reference/types/Hl7PartialPrecision", + "name": "Hl7PartialPrecision", + "namespace": "types", + "module": "hl7", + "kind": "type", + "signature": "", + "description": "The precision of a span: a year, month, day or hour, which names no single moment (`Hl7Precision` lists the characters each one takes).", + "sourcePath": "packages/gmt/src/types/hl7.ts", + "examples": [] + }, + { + "url": "/reference/types/Hl7MomentPrecision", + "page": "/reference/types/Hl7MomentPrecision", + "name": "Hl7MomentPrecision", + "namespace": "types", + "module": "hl7", + "kind": "type", + "signature": "", + "description": "The precision of a moment: a minute or finer (`Hl7Precision` lists the characters each one takes).", + "sourcePath": "packages/gmt/src/types/hl7.ts", + "examples": [] + }, + { + "url": "/reference/healthcare/parse/parseHL7#hl7datetime", + "page": "/reference/healthcare/parse/parseHL7", + "name": "Hl7DateTime", + "namespace": "types", + "module": "hl7", + "kind": "type", + "signature": "", + "description": "An HL7 v2 date-time (`DTM`, 2.A.22; or `TS`, 2.A.77) read as what it states. What the sender did not send is not invented: a value with no offset has no instant, and a year or a day has no moment.", + "sourcePath": "packages/gmt/src/types/hl7.ts", + "examples": [], + "inlineOn": "parseHL7" + }, + { + "url": "/reference/healthcare/format/formatHL7#hl7formatoptions", + "page": "/reference/healthcare/format/formatHL7", + "name": "Hl7FormatOptions", + "namespace": "types", + "module": "hl7", + "kind": "type", + "signature": "", + "description": "Options for `formatHL7`.", + "sourcePath": "packages/gmt/src/types/hl7.ts", + "examples": [], + "inlineOn": "formatHL7", + "members": [ + { + "name": "precision", + "description": "Lowers the precision written; never raises it. The precision is read from the form the input is written in, and a value lower than that cuts the digits (never rounds)." + } + ] + }, { "url": "/reference/types/WeekdayOrdinal", "page": "/reference/types/WeekdayOrdinal", diff --git a/apps/dox/src/generated/reference/route-manifest.ts b/apps/dox/src/generated/reference/route-manifest.ts index f631c889c..572c5a56b 100644 --- a/apps/dox/src/generated/reference/route-manifest.ts +++ b/apps/dox/src/generated/reference/route-manifest.ts @@ -81,6 +81,13 @@ export const referenceRoutes: RouteManifest = new Set([ "/reference/gnss/convert/utcToGnss", "/reference/gnss/convert/utcToGnssWeek", "/reference/gnss/convert/utcToRinexWeek", + "/reference/healthcare", + "/reference/healthcare/format", + "/reference/healthcare/format/formatHL7", + "/reference/healthcare/parse", + "/reference/healthcare/parse/parseHL7", + "/reference/healthcare/validate", + "/reference/healthcare/validate/isValidHL7", "/reference/instant", "/reference/instant/convert", "/reference/instant/convert/classifyLocal", @@ -627,6 +634,8 @@ export const referenceRoutes: RouteManifest = new Set([ "/reference/types/FreeTimeOptions", "/reference/types/GnssSystem", "/reference/types/GnssWeekCounter", + "/reference/types/Hl7MomentPrecision", + "/reference/types/Hl7PartialPrecision", "/reference/types/HolidayRule", "/reference/types/Interval", "/reference/types/IsoWeekday", diff --git a/apps/dox/src/lib/chat-constants.ts b/apps/dox/src/lib/chat-constants.ts index 77ccf0ca8..b78a8d682 100644 --- a/apps/dox/src/lib/chat-constants.ts +++ b/apps/dox/src/lib/chat-constants.ts @@ -336,6 +336,7 @@ export const EXAMPLE_AREAS = [ { id: "intermodal", label: "Intermodal" }, { id: "gnss", label: "GNSS" }, { id: "finance", label: "Finance" }, + { id: "healthcare", label: "Healthcare" }, ] as const; type ExampleArea = (typeof EXAMPLE_AREAS)[number]["id"]; @@ -736,6 +737,14 @@ export const CHAT_STARTERS: readonly { firmwareNotBefore: "2020-01-01T00:00:00Z", }, }, + { + text: "An HL7 time of 20240615103000, no offset, from a Kolkata facility. What instant is it?", + widget: "showHl7TimestampReader", + area: "healthcare", + // The question names the IANA zone, so the seed carries it as a literal + // field; the value states no zone. + args: { value: "20240615103000", zone1: "Asia/Kolkata" }, + }, { text: "How many leap seconds were inserted from 2000 to 2024, and what was TAI - UTC in 2000?", widget: "showLeapSecondTimeline", diff --git a/apps/dox/src/lib/dox-tools.ts b/apps/dox/src/lib/dox-tools.ts index f95b850cd..70af2c00f 100644 --- a/apps/dox/src/lib/dox-tools.ts +++ b/apps/dox/src/lib/dox-tools.ts @@ -629,6 +629,21 @@ export const showFixTimestampReaderInput = z.object({ instant: z.string().max(64).optional(), }); +/** + * The HL7 Timestamp Reader: one HL7 v2 date-time (a `DTM`, or a `TS` with its degree of + * precision after `^`), read by `parseHL7`. `zone1` to `zone4` are zones the reader named, to + * read a value with no offset in. The value is kept as typed, so it is not trimmed. The widget + * judges the value itself: one the library does not read is the widget's NO SIGNAL, not a + * failed tool call. + */ +export const showHl7TimestampReaderInput = z.object({ + value: z.string().min(1).max(64), + zone1: zoneSchema.optional(), + zone2: zoneSchema.optional(), + zone3: zoneSchema.optional(), + zone4: zoneSchema.optional(), +}); + /** Typed as the library's `IsoWeekday`, so a parsed shift is a `HolidayRule` shift. */ const isoWeekdaySchema = z .number() @@ -1258,7 +1273,8 @@ export type DoxToolName = | "showDatabaseTimestampReader" | "showTai64nLogReader" | "showTerrestrialTimeStack" - | "showFixTimestampReader"; + | "showFixTimestampReader" + | "showHl7TimestampReader"; /** Prompt copy, kept beside the schemas so the two cannot drift. */ export const DOX_TOOL_DOCS: { @@ -1582,6 +1598,13 @@ export const DOX_TOOL_DOCS: { when: "the reader asks what a FIX UTCTimestamp or a SendingTime or TransactTime value means, its precision, whether a second 60 in it is real, or how to write an instant at milli-, micro-, nano- or picosecond precision", args: "stamp: optional, the FIX UTCTimestamp exactly as the reader gave it, never trimmed or corrected; instant: optional, an instant with Z or an offset to write at the five precisions, only when the reader gave one.", }, + { + name: "showHl7TimestampReader", + purpose: + "An HL7 v2 date-time (a DTM, or a TS with its degree of precision after ^) read by parseHL7: its kind, precision and offset; a value with no offset read in the zones the reader picks with resolveLocal, beside the instant a parser that assumes UTC gets; and the value written back by formatHL7 at each precision.", + when: "the reader asks what an HL7 v2 DTM or TS value means, what instant an HL7 time with no offset names, what a TS degree of precision such as ^L or ^D does, or how to write an instant as an HL7 DTM", + args: "value (the HL7 date-time exactly as the reader gave it, such as 20240615103000 or 199904011200^L; at most 64 characters; never corrected, and never given an offset the reader did not send), zone1 to zone4 (optional IANA ids to read a value with no offset in; only zones the reader named: never choose one from a facility, a place, a vendor or an abbreviation, because the value states none).", + }, ]; /** @@ -1770,6 +1793,10 @@ export const DOX_TOOLS = { description: DOX_TOOL_DOCS[44].purpose, inputSchema: showFixTimestampReaderInput, }), + showHl7TimestampReader: tool({ + description: DOX_TOOL_DOCS[45].purpose, + inputSchema: showHl7TimestampReaderInput, + }), } as const; export const DOX_TOOL_NAMES = Object.keys(DOX_TOOLS) as DoxToolName[]; @@ -1838,6 +1865,7 @@ export const ENABLED_TOOL_NAMES = [ "showTai64nLogReader", "showTerrestrialTimeStack", "showFixTimestampReader", + "showHl7TimestampReader", ] as const satisfies readonly DoxToolName[]; /** Prompt copy for the offered tools only. */ diff --git a/apps/dox/src/lib/edi-picture.test.ts b/apps/dox/src/lib/edi-picture.test.ts index 872ac04f0..19fe24c1c 100644 --- a/apps/dox/src/lib/edi-picture.test.ts +++ b/apps/dox/src/lib/edi-picture.test.ts @@ -148,6 +148,83 @@ describe("timelineLayout", () => { expect(timelineLayout([])).toBeNull(); }); + describe("the reference mark", () => { + const zones = [ + { n: 1, instant: "2024-06-15T05:00:00Z" }, + { n: 2, instant: "2024-06-15T09:30:00Z" }, + ]; + + it("is null without a reference, and the layout is unchanged", () => { + const without = timelineLayout(zones)!; + expect(without.reference).toBeNull(); + expect(timelineLayout(zones, null)).toEqual(without); + }); + + it("widens the axis to span the reference", () => { + const without = timelineLayout(zones)!; + const withLater = timelineLayout(zones, "2024-06-15T14:30:00Z")!; + expect(withLater.ticks.length).toBeGreaterThan(without.ticks.length); + expect(withLater.reference!.at).toBeGreaterThan(0); + expect(withLater.reference!.at).toBeLessThan(100); + expect(withLater.marks.every((m) => m.at < withLater.reference!.at)).toBe( + true, + ); + }); + + it("leaves the span (the widest gap) among the zones", () => { + const without = timelineLayout(zones)!; + const withFar = timelineLayout(zones, "2024-06-16T10:30:00Z")!; + const gapWidth = (l: typeof without) => l.span!.to - l.span!.from; + // The span is still the zones' two marks: a wider axis makes it a smaller share. + expect(gapWidth(withFar)).toBeLessThan(gapWidth(without)); + expect(withFar.marks.map((m) => m.n)).toEqual([1, 2]); + }); + + it("writes its label on the side with room", () => { + expect( + timelineLayout(zones, "2024-06-15T05:00:00Z")!.reference!.side, + ).toBe("end"); + expect( + timelineLayout(zones, "2024-06-15T09:30:00Z")!.reference!.side, + ).toBe("start"); + }); + + it("takes a lane with no zone mark near its label", () => { + const stacked = timelineLayout( + [ + { n: 1, instant: "2024-06-15T12:00:00Z" }, + { n: 2, instant: "2024-06-15T12:00:00Z" }, + ], + "2024-06-15T12:00:00Z", + )!; + expect(stacked.marks.map((m) => m.lane)).toEqual([0, 1]); + expect(stacked.reference!.lane).toBe(2); + }); + + it("never takes a fifth lane", () => { + const four = [1, 2, 3, 4].map((n) => ({ + n, + instant: "2024-06-15T12:00:00Z", + })); + expect( + timelineLayout(four, "2024-06-15T12:00:00Z")!.reference!.lane, + ).toBe(0); + }); + }); + + it("adds the reference to the spoken line, after the gap", () => { + expect( + timelineAria( + [{ n: 1, zone: "Europe/Berlin", instant: "2024-06-15T12:30:00Z" }], + "", + "", + { label: "Read as UTC", instant: "2024-06-15T10:30:00Z" }, + ), + ).toBe( + "A UTC timeline with 1 zone marked: 1, Europe/Berlin, 2024-06-15T12:30:00Z. Read as UTC: 2024-06-15T10:30:00Z.", + ); + }); + it("says each zone's instant in words", () => { expect( timelineAria( diff --git a/apps/dox/src/lib/edi-picture.ts b/apps/dox/src/lib/edi-picture.ts index b0ccf4ae6..c947fa167 100644 --- a/apps/dox/src/lib/edi-picture.ts +++ b/apps/dox/src/lib/edi-picture.ts @@ -348,16 +348,32 @@ interface TimelineMarkPos { lane: number; } +/** Where the reference mark sits: along the axis, in a pin lane, and which side its label is on. */ +interface TimelineReferencePos { + at: number; + lane: number; + /** The side of the pin the label is written on: toward the nearer end of the axis' room. */ + side: "start" | "end"; +} + export interface TimelineLayout { ticks: TimelineTick[]; marks: TimelineMarkPos[]; - /** The outermost marks, as positions along the axis, when there are two. */ + /** The outermost zone marks, as positions along the axis, when there are two. */ span: { from: number; to: number } | null; + /** The reference mark, when the caller passed one. */ + reference: TimelineReferencePos | null; } /** The marks nearer than this, in percent of the axis, share no lane. */ const LANE_GAP = 8; +/** The pin lanes the plot holds: the reference mark takes one of them and never a fifth. */ +const LANES = 4; + +/** The room, in percent of the axis, the reference mark's label needs beside its pin. */ +const REFERENCE_CLEAR = 30; + /** How many tick labels the axis holds before it skips ticks. */ const MAX_LABELS = 8; @@ -376,18 +392,28 @@ function utcHour(ms: number): { hour: number; day: string } { * after the latest (a few more for one instant alone), with a tick on every whole * hour and a label on every n-th so the labels never touch. A mark takes the * first lane in which the one before it is far enough away. + * + * A `reference` instant (a value read some other way, drawn as its own mark) is part of the + * axis' domain, so the axis spans it. It takes no part in the zone marks' lanes, the span or + * the widest gap: it goes in the first lane with no zone mark near its label. */ export function timelineLayout( inputs: readonly { n: number; instant: string }[], + reference: string | null = null, ): TimelineLayout | null { if (inputs.length === 0) return null; const ms = inputs.map( (i) => Temporal.Instant.from(i.instant).epochMilliseconds, ); - const lowest = Math.min(...ms); - const highest = Math.max(...ms); + const referenceMs = + reference === null + ? null + : Temporal.Instant.from(reference).epochMilliseconds; + const everyMs = referenceMs === null ? ms : [...ms, referenceMs]; + const lowest = Math.min(...everyMs); + const highest = Math.max(...everyMs); const hours = Math.max(0, Math.ceil((highest - lowest) / HOUR)); - const pad = inputs.length === 1 ? 3 : Math.max(1, Math.ceil(hours / 10)); + const pad = everyMs.length === 1 ? 3 : Math.max(1, Math.ceil(hours / 10)); const from = Math.floor(lowest / HOUR) * HOUR - pad * HOUR; const to = Math.ceil(highest / HOUR) * HOUR + pad * HOUR; const total = to - from; @@ -417,11 +443,36 @@ export function timelineLayout( laneEnds[lane] = m.at; return { n: m.n, at: m.at, lane }; }); + const zoneLowest = Math.min(...ms); + const zoneHighest = Math.max(...ms); const span = - inputs.length > 1 && highest > lowest - ? { from: at(lowest), to: at(highest) } + inputs.length > 1 && zoneHighest > zoneLowest + ? { from: at(zoneLowest), to: at(zoneHighest) } : null; - return { ticks, marks, span }; + return { + ticks, + marks, + span, + reference: + referenceMs === null ? null : referencePos(at(referenceMs), marks), + }; +} + +/** The first pin lane with no zone mark within the label's room, else the first lane. */ +function referencePos( + position: number, + marks: readonly TimelineMarkPos[], +): TimelineReferencePos { + const free = Array.from({ length: LANES }, (_, lane) => lane).find((lane) => + marks.every( + (m) => m.lane !== lane || Math.abs(m.at - position) >= REFERENCE_CLEAR, + ), + ); + return { + at: position, + lane: free ?? 0, + side: position > 100 - REFERENCE_CLEAR ? "start" : "end", + }; } /** @@ -432,6 +483,7 @@ export function timelineAria( inputs: readonly TimelineInput[], gap: string, stated: string, + reference: { label: string; instant: string } | null = null, ): string { if (stated !== "") return `The instant the value states, ${stated}, on a UTC timeline.`; @@ -439,7 +491,9 @@ export function timelineAria( .filter((i) => i.instant !== "") .map((i) => `${i.n}, ${i.zone}, ${i.instant}`) .join("; "); - return `A UTC timeline with ${inputs.length} ${inputs.length === 1 ? "zone" : "zones"} marked: ${marks}${gap === "" ? "" : `. ${gap}`}.`; + const read = + reference === null ? "" : ` ${reference.label}: ${reference.instant}.`; + return `A UTC timeline with ${inputs.length} ${inputs.length === 1 ? "zone" : "zones"} marked: ${marks}${gap === "" ? "" : `. ${gap}`}.${read}`; } // --------------------------------------------------------------------------- diff --git a/apps/dox/src/lib/edi-widgets.test.ts b/apps/dox/src/lib/edi-widgets.test.ts index 4be323144..a501e4a28 100644 --- a/apps/dox/src/lib/edi-widgets.test.ts +++ b/apps/dox/src/lib/edi-widgets.test.ts @@ -213,6 +213,8 @@ describe("durationText", () => { ["PT45M", "45 min"], ["PT1H30S", "1 h 30 s"], ["P1D", "P1D"], + ["PT2H59M59.8766S", "2 h 59 min 59.8766 s"], + ["PT0.5S", "0.5 s"], ])("%s is %s", (iso, text) => { expect(durationText(iso)).toBe(text); }); diff --git a/apps/dox/src/lib/edi-widgets.ts b/apps/dox/src/lib/edi-widgets.ts index 28b724e3f..037171713 100644 --- a/apps/dox/src/lib/edi-widgets.ts +++ b/apps/dox/src/lib/edi-widgets.ts @@ -359,9 +359,10 @@ export function unreadCodeText( // Drawing text // --------------------------------------------------------------------------- -const DURATION = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/; +const DURATION = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?$/; -/** `PT15H` as `15 h`, `PT9H30M` as `9 h 30 min`, `PT0S` as `0 h`. A regular +/** `PT15H` as `15 h`, `PT9H30M` as `9 h 30 min`, `PT0S` as `0 h`, and a fraction of a + * second as it came (`PT2H59M59.8766S` as `2 h 59 min 59.8766 s`). A regular * expression over the returned string; no arithmetic. */ export function durationText(iso: string): string { const m = DURATION.exec(iso); @@ -394,7 +395,7 @@ export function readoutOf( export function resolveReason( local: string, zone: string, - lib: EdiLib, + lib: Pick, ): string { const time = local.slice(11, 16); switch (lib.classifyLocal(local, zone)) { @@ -434,7 +435,7 @@ interface ZoneResolution { export function resolveInZone( local: string, rawZone: string, - lib: EdiLib, + lib: Pick, ): ZoneResolution { const zone = rawZone.trim(); const row: ZoneResolution = { zone, instant: "", offset: "", reason: "" }; @@ -462,7 +463,7 @@ export interface WidestGap { * `minUtc`, `maxUtc` and `diffUtcAsDuration`. `null` with fewer than two. */ export function widestGap( rows: readonly { zone: string; instant: string }[], - lib: EdiLib, + lib: Pick, ): WidestGap | null { const resolved = rows.filter((r) => r.instant !== ""); if (resolved.length < 2) return null; diff --git a/apps/dox/src/lib/gmt-modules.ts b/apps/dox/src/lib/gmt-modules.ts index 16184d1fd..53cc55088 100644 --- a/apps/dox/src/lib/gmt-modules.ts +++ b/apps/dox/src/lib/gmt-modules.ts @@ -81,6 +81,11 @@ export const GMT_MODULES: Record< "intermodal/parse": () => import("@northguild/gmt/intermodal/parse"), "intermodal/validate": () => import("@northguild/gmt/intermodal/validate"), + // --- healthcare --- + "healthcare/format": () => import("@northguild/gmt/healthcare/format"), + "healthcare/parse": () => import("@northguild/gmt/healthcare/parse"), + "healthcare/validate": () => import("@northguild/gmt/healthcare/validate"), + // --- duration --- "duration/calculate": () => import("@northguild/gmt/duration/calculate"), "duration/compare": () => import("@northguild/gmt/duration/compare"), diff --git a/apps/dox/src/lib/hl7-lib.test.ts b/apps/dox/src/lib/hl7-lib.test.ts new file mode 100644 index 000000000..758bec153 --- /dev/null +++ b/apps/dox/src/lib/hl7-lib.test.ts @@ -0,0 +1,55 @@ +/** + * `loadHl7Lib` against the real gmt modules, and `Hl7Lib` against the library's own signatures. + */ +import type { formatHL7 } from "@northguild/gmt/healthcare/format"; +import type { parseHL7 } from "@northguild/gmt/healthcare/parse"; +import { hl7Lib } from "~/test/hl7-lib"; +import { GMT_MODULES } from "./gmt-modules"; +import { loadHl7Lib, type Hl7Lib } from "./hl7-lib"; +import { WidgetLoadError } from "./widget-mount"; + +describe("Hl7Lib", () => { + it("is the library's own parseHL7 and formatHL7", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); +}); + +describe("loadHl7Lib", () => { + it("hands back the functions the Reader calls, and nothing else", async () => { + const lib = await loadHl7Lib(); + expect(Object.keys(lib).sort()).toEqual(Object.keys(hl7Lib).sort()); + for (const value of Object.values(lib)) { + expect(typeof value).toBe("function"); + } + }); + + it("answers a real call", async () => { + const lib = await loadHl7Lib(); + expect(lib.parseHL7("20240615103000+0200")).toMatchObject({ + kind: "instant", + instant: "2024-06-15T08:30:00Z", + }); + }); + + it("turns a rejected import into a WidgetLoadError", async () => { + const original = GMT_MODULES["healthcare/parse"]; + GMT_MODULES["healthcare/parse"] = () => + Promise.reject(new Error("offline")); + try { + await expect(loadHl7Lib()).rejects.toBeInstanceOf(WidgetLoadError); + } finally { + GMT_MODULES["healthcare/parse"] = original; + } + }); + + it("turns a module that lacks a name into a WidgetLoadError", async () => { + const original = GMT_MODULES["healthcare/format"]; + GMT_MODULES["healthcare/format"] = () => Promise.resolve({}); + try { + await expect(loadHl7Lib()).rejects.toBeInstanceOf(WidgetLoadError); + } finally { + GMT_MODULES["healthcare/format"] = original; + } + }); +}); diff --git a/apps/dox/src/lib/hl7-lib.ts b/apps/dox/src/lib/hl7-lib.ts new file mode 100644 index 000000000..057f62723 --- /dev/null +++ b/apps/dox/src/lib/hl7-lib.ts @@ -0,0 +1,68 @@ +/** + * Loads the functions the HL7 Timestamp Reader needs, at module granularity, and hands them back + * as an `Hl7Lib`. + * + * Four modules: `healthcare/parse` (`parseHL7`), `healthcare/format` (`formatHL7`), + * `instant/convert` (`resolveLocal`, `classifyLocal`, `toOffsetInstant`, `fromOffsetInstant`) and `utc/calculate` + * (`minUtc`, `maxUtc`, `diffUtcAsDuration`). Each name is picked and nothing else is read. + * `Hl7Lib` is a superset of what `resolveInZone` and `widestGap` take (`edi-widgets.ts`). + * + * A heavy module: it is never imported statically from the chat island. Only the widget's mount + * reaches it, so a rejected import, or a name a module no longer exports, becomes a + * `WidgetLoadError` rather than a dead control. + */ +import type { Hl7DateTime, Hl7FormatOptions } from "@northguild/gmt/types"; +import type { EdiLib } from "./edi-widgets"; +import { GMT_MODULES } from "./gmt-modules"; +import { WidgetLoadError } from "./widget-mount"; + +/** The functions the Reader calls, as the library declares them. */ +export interface Hl7Lib extends Pick< + EdiLib, + | "resolveLocal" + | "classifyLocal" + | "toOffsetInstant" + | "fromOffsetInstant" + | "minUtc" + | "maxUtc" + | "diffUtcAsDuration" +> { + parseHL7(value: string): Hl7DateTime | null; + formatHL7(value: string, options?: Hl7FormatOptions): string; +} + +/** Reads each name from a module, and fails loudly on a name it lacks. */ +function pick(module: Record, names: readonly string[]) { + return Object.fromEntries( + names.map((name) => { + if (typeof module[name] !== "function") { + throw new Error(`The library module has no ${name}.`); + } + return [name, module[name]]; + }), + ); +} + +export async function loadHl7Lib(): Promise { + try { + const [parse, format, convert, utcCalculate] = await Promise.all([ + GMT_MODULES["healthcare/parse"](), + GMT_MODULES["healthcare/format"](), + GMT_MODULES["instant/convert"](), + GMT_MODULES["utc/calculate"](), + ]); + return { + ...pick(parse, ["parseHL7"]), + ...pick(format, ["formatHL7"]), + ...pick(convert, [ + "resolveLocal", + "classifyLocal", + "toOffsetInstant", + "fromOffsetInstant", + ]), + ...pick(utcCalculate, ["minUtc", "maxUtc", "diffUtcAsDuration"]), + } as unknown as Hl7Lib; + } catch (cause) { + throw new WidgetLoadError(cause); + } +} diff --git a/apps/dox/src/lib/hl7-timestamp-reader-mount.test.tsx b/apps/dox/src/lib/hl7-timestamp-reader-mount.test.tsx new file mode 100644 index 000000000..c2fd2dbbf --- /dev/null +++ b/apps/dox/src/lib/hl7-timestamp-reader-mount.test.tsx @@ -0,0 +1,411 @@ +/** + * @vitest-environment jsdom + * + * The HL7 Timestamp Reader end to end: template -> mount -> interact -> assert, against the real + * `@northguild/gmt`, through roles and accessible names the way a person (or a screen reader) + * meets the page. + */ +import { screen, within } from "@testing-library/dom"; +import { + WIDGET_REGISTRY, + type AnyWidgetEntry, +} from "~/components/ask/widget-registry"; +import { installJsdomShims } from "~/test/jsdom-shims"; +import { + cellsInColumn, + expectNoAxeViolations, + renderWidget, + type RenderedWidget, +} from "~/test/render-widget"; +import { HL7_PRESETS, hl7Texts, presetState } from "./hl7-timestamp-reader"; +import { encodeWidgetPermalink, seedFromLocation } from "./widget-permalink"; + +installJsdomShims(); + +const entry = WIDGET_REGISTRY["showHl7TimestampReader"] as AnyWidgetEntry; + +/** preset id → [verdict, what the call returned (the head of it)]. */ +const EXPECTED: Record = { + "no-offset": ["No offset: the sender's local time", '"local"'], + offset: ["Offset stated", '"instant"'], + "minus-zero": ["Offset stated", '"+00:00"'], + fraction: ["Offset stated", '"2024-06-15T10:30:45.1234Z"'], + "fall-back": ["No offset: the sender's local time", '"local"'], + "spring-forward": ["No offset: the sender's local time", '"local"'], + midnight: ["No offset: the sender's local time", '"local"'], + "ts-month": ["A span, not a moment", '"partial"'], + "ts-day": ["A span, not a moment", '"partial"'], + "ts-finer": ["", "NO SIGNAL"], + "birth-year": ["A span, not a moment", '"partial"'], + "null-value": ["The HL7 null value", '"null"'], + "five-digits": ["", "NO SIGNAL"], +}; + +const open = (args = {}, idPrefix = "test") => + renderWidget(entry, { args, idPrefix }); + +const preset = () => screen.getByRole("combobox", { name: "Preset" }); +const input = () => + screen.getByRole("textbox", { name: "HL7 value (DTM or TS)" }); +const zone = (n: number) => screen.getByRole("combobox", { name: `Zone ${n}` }); +const section = (name: RegExp) => screen.getByRole("region", { name }); +const states = () => section(/^2\. /); +const lands = () => section(/^3\. /); +const back = () => section(/^4\. /); +const verdict = () => screen.getByRole("status", { name: "Verdict" }); +const parseOutput = () => + within(states()).getByRole("status", { name: "What the call returned" }); +const parseCall = () => + within(states()).queryByRole("group", { name: "Call made" }); +const reason = () => within(states()).queryByRole("complementary"); +const stripNote = () => + screen.getByRole("note", { name: "Where a value with no offset lands" }); +const gap = () => screen.getByRole("status", { name: "Widest gap" }); +const strip = () => screen.getByRole("table", { name: /four zones/ }); +const column = (name: string | RegExp) => + cellsInColumn(strip(), name).map((c) => c.textContent!.trim()); +const ladder = () => + within(back()).getByRole("table", { + name: "The value written at each precision", + }); +const ladderNote = () => + screen.getByRole("note", { name: "About the written values" }); + +async function choose(w: RenderedWidget, id: string) { + await w.user.selectOptions(preset(), id); +} +async function retype(w: RenderedWidget, box: HTMLElement, value: string) { + await w.user.clear(box); + if (value !== "") await w.user.type(box, value); +} + +describe("renderHl7TimestampReaderTemplate", () => { + it("is a named region with four numbered sections and named controls", async () => { + await open(); + expect( + screen.getByRole("region", { name: "HL7 Timestamp Reader" }), + ).toBeInTheDocument(); + expect( + screen.getAllByRole("heading", { level: 4 }).map((h) => h.textContent), + ).toEqual([ + "1. Type an HL7 date-time", + "2. What the value states", + "3. Where a value with no offset lands", + "4. Written back by formatHL7", + ]); + for (const c of [preset(), input(), zone(1), zone(4)]) { + expect(c).toBeInTheDocument(); + } + }); + + it("does not run a hostile seed", async () => { + await open({ + value: '">', + zone1: '">', + }); + expect(input()).toHaveValue('">'); + expect(parseOutput()).toHaveTextContent("NO SIGNAL"); + }); +}); + +describe("every preset, against the real library", () => { + it("has an expectation for every preset", () => { + expect(Object.keys(EXPECTED).sort()).toEqual( + HL7_PRESETS.map((p) => p.id).sort(), + ); + }); + + it.each(HL7_PRESETS.map((p) => [p.id]))("%s", async (id) => { + const w = await open(); + await choose(w, id!); + const [verdictWords, returned] = EXPECTED[id!]!; + expect(input()).toHaveValue( + presetState(HL7_PRESETS.find((p) => p.id === id)!).value, + ); + expect(verdict()).toHaveTextContent( + verdictWords === "" ? /^$/ : verdictWords, + ); + expect(parseOutput()).toHaveTextContent(returned); + expect(parseCall()).toHaveTextContent("parseHL7("); + if (returned === "NO SIGNAL") expect(reason()).toBeInTheDocument(); + else expect(reason()).not.toBeInTheDocument(); + await expectNoAxeViolations(w.root); + }); + + it("explains a refused value without blaming a blank", async () => { + const w = await open(); + await choose(w, "five-digits"); + expect(parseOutput()).toHaveTextContent("NO SIGNAL"); + expect(reason()).toBeInTheDocument(); + await expectNoAxeViolations(w.root); + }); +}); + +describe("the strip", () => { + it("opens on the starter: Kolkata is 5 h 30 min before the same digits read as UTC", async () => { + const w = await open({ value: "20240615103000", zone1: "Asia/Kolkata" }); + expect(column("Instant")[0]).toBe("2024-06-15T05:00:00Z"); + expect(column("Read as UTC")[0]).toBe("5 h 30 min later"); + await expectNoAxeViolations(w.root); + }); + + it("reads the first preset in its example zones and names the widest gap", async () => { + const w = await open(); + expect(column("Instant")[0]).toBe("2024-06-15T05:00:00Z"); + expect(gap()).toHaveTextContent("Widest gap:"); + await expectNoAxeViolations(w.root); + }); + + it("changes a row when its zone changes, and leaves the preset for Custom", async () => { + const w = await open(); + await w.user.selectOptions(zone(3), "Asia/Tokyo"); + expect(column("Instant")[2]).toBe("2024-06-15T01:30:00Z"); + expect(preset()).toHaveValue("custom"); + await expectNoAxeViolations(w.root); + }); + + it("says no zone chosen for a blank slot", async () => { + await open(); + expect(column("Instant")[3]).toBe("no zone chosen"); + }); + + it("disables the zone selects when the value states its offset", async () => { + const w = await open(); + await choose(w, "offset"); + for (const n of [1, 2, 3, 4]) expect(zone(n)).toBeDisabled(); + expect(stripNote()).toHaveTextContent( + "The value states its offset, so there is nothing to choose.", + ); + await expectNoAxeViolations(w.root); + }); + + it("applies no zone to a span", async () => { + const w = await open(); + await choose(w, "ts-month"); + for (const n of [1, 2, 3, 4]) expect(zone(n)).toBeDisabled(); + expect(stripNote()).toHaveTextContent("A span has no instant"); + await expectNoAxeViolations(w.root); + }); + + it("never fills a zone from the value typed", async () => { + const w = await open(); + for (const n of [1, 2, 3, 4]) await w.user.selectOptions(zone(n), ""); + await retype(w, input(), "20240615103000"); + for (const n of [1, 2, 3, 4]) expect(zone(n)).toHaveValue(""); + await expectNoAxeViolations(w.root); + }); + + it("refuses a time the clock shows twice, with its reason, in the zone that shows it", async () => { + const w = await open(); + await choose(w, "fall-back"); + expect(zone(1)).toHaveValue("Europe/London"); + expect(column("Instant")[0]).toBe("NO SIGNAL"); + expect(column("Instant")[1]).toBe("2024-10-26T16:30:00Z"); + expect( + within(lands()).getAllByRole("complementary").length, + ).toBeGreaterThan(0); + await expectNoAxeViolations(w.root); + }); +}); + +describe("the writer ladder", () => { + it("writes seven precisions, and a finer one than the value carries is no result", async () => { + const w = await open(); + expect( + cellsInColumn(ladder(), "Precision").map((c) => c.textContent), + ).toEqual(["year", "month", "day", "hour", "minute", "second", "fraction"]); + const sent = cellsInColumn(ladder(), "As sent").map((c) => + c.textContent!.trim(), + ); + expect(sent[0]).toBe("2024"); + expect(sent[5]).toBe("20240615103000"); + expect(sent[6]).toBe("no result"); + expect(ladderNote()).toHaveTextContent("formatHL7"); + await expectNoAxeViolations(w.root); + }); + + it("says nothing to write for a blank field", async () => { + const w = await open(); + await retype(w, input(), ""); + expect(ladderNote()).toHaveTextContent( + "Nothing to write: there is no value.", + ); + await expectNoAxeViolations(w.root); + }); +}); + +describe("the blank form", () => { + it("makes no call and says nothing to read, never amber", async () => { + const w = await open(); + await retype(w, input(), ""); + expect(parseOutput()).toHaveTextContent("nothing to read"); + expect(parseOutput()).not.toHaveTextContent("NO SIGNAL"); + expect(parseCall()).not.toBeInTheDocument(); + expect(reason()).not.toBeInTheDocument(); + expect(verdict()).toHaveTextContent(/^$/); + expect(stripNote()).toHaveTextContent("No value to place."); + await expectNoAxeViolations(w.root); + }); + + it("goes from blank to a refused value to a result and back", async () => { + const w = await open(); + await retype(w, input(), ""); + await retype(w, input(), "2024061510300"); + expect(parseOutput()).toHaveTextContent("NO SIGNAL"); + await retype(w, input(), "20240615103000+0200"); + expect(verdict()).toHaveTextContent("Offset stated"); + await retype(w, input(), ""); + expect(parseOutput()).toHaveTextContent("nothing to read"); + await expectNoAxeViolations(w.root); + }); +}); + +describe("seeding and permalinks", () => { + it("seeds a named preset", async () => { + await open({ preset: "ts-month" }); + expect(preset()).toHaveValue("ts-month"); + expect(verdict()).toHaveTextContent("A span, not a moment"); + }); + + it("seeds an unlisted zone without dropping it", async () => { + await open({ value: "20240615103000", zone1: "Pacific/Auckland" }); + expect(zone(1)).toHaveValue("Pacific/Auckland"); + expect(column("Instant")[0]).toBe("2024-06-14T22:30:00Z"); + }); + + it.each(HL7_PRESETS.map((p) => [p.id]))( + "round-trips %s as a permalink of strings", + async (id) => { + const first = await open(); + await choose(first, id!); + const url = first.permalink(); + expect(url).toMatch(/\?w=hl7&wa=[^)"'\s]+$/); + const state = seedFromLocation( + "hl7", + url.slice(url.indexOf("?")), + ) as Record; + expect( + Object.values(state).every( + (v) => typeof v === "string" && v.length > 0 && v.length <= 64, + ), + ).toBe(true); + expect(encodeWidgetPermalink("hl7", state)).toBe(url); + first.destroy(); + + await open(state, "second"); + expect(preset()).toHaveValue(id); + expect(parseOutput()).toHaveTextContent(EXPECTED[id!]![1]); + }, + ); + + it("carries a custom value untrimmed", async () => { + const w = await open(); + await retype(w, input(), "20240615103001"); + const url = w.permalink(); + expect(seedFromLocation("hl7", url.slice(url.indexOf("?")))).toMatchObject({ + value: "20240615103001", + }); + }); +}); + +describe("naming", () => { + it("names no regulator or statute, and never calls the library GMT", async () => { + const forbidden = /\b(HIPAA|CFR|statut|regulat|FDA|agency|GMT)\b/; + const w = await open(); + expect(w.root).not.toHaveTextContent(forbidden); + for (const p of HL7_PRESETS) { + expect(`${p.label} ${p.description}`).not.toMatch(forbidden); + await choose(w, p.id); + expect(w.root).not.toHaveTextContent(forbidden); + } + }); +}); + +describe("lifecycle", () => { + it("an aborted mount is inert, and destroying twice is safe", async () => { + const w = await renderWidget(entry, { args: {}, aborted: true }); + // The host's static shell is there; the mount wrote nothing into it. + expect(verdict()).toBeEmptyDOMElement(); + expect(parseOutput()).toHaveTextContent("nothing to read"); + expect(ladderNote()).toBeEmptyDOMElement(); + expect(() => { + w.destroy(); + w.destroy(); + }).not.toThrow(); + }); +}); + +describe("holds still", () => { + const norm = (t: string | null) => (t ?? "").replace(/\s+/g, " ").trim(); + // A hold draws every text its region can show as a hidden ghost beside the live one. + const ghosts = (region: HTMLElement, sample: string) => + within(region).queryAllByText( + (_, el) => + el?.getAttribute("aria-hidden") === "true" && + norm(el.textContent).includes(norm(sample)), + ); + const longest = (list: readonly string[]) => + list.reduce((a, b) => (b.length > a.length ? b : a)); + // Each sample with the numbered section whose hold draws it. The verdict holds every title + // and every detail (`verdictHold`); the reason aside holds only its longest (`asideHold`). + const everyText = (): [() => HTMLElement, string][] => { + const t = hl7Texts(); + return [ + ...t.stripNotes.map((s): [() => HTMLElement, string] => [lands, s]), + ...t.gaps.map((s): [() => HTMLElement, string] => [lands, s]), + ...t.ladderNotes.map((s): [() => HTMLElement, string] => [back, s]), + ...t.verdicts.map((s): [() => HTMLElement, string] => [states, s]), + ...t.details.map((s): [() => HTMLElement, string] => [states, s]), + [states, longest(t.reasons)], + [states, t.parseCall], + [states, t.parseOutput], + [lands, t.stripCall], + [lands, t.stripOutput], + ]; + }; + + it("has every region present in every preset", async () => { + const w = await open(); + for (const p of HL7_PRESETS) { + await choose(w, p.id); + for (const name of [/^1\. /, /^2\. /, /^3\. /, /^4\. /]) { + expect(section(name), p.id).toBeInTheDocument(); + } + expect(preset(), p.id).toBeInTheDocument(); + expect(input(), p.id).toBeInTheDocument(); + expect(verdict(), p.id).toBeInTheDocument(); + expect(parseOutput(), p.id).toBeInTheDocument(); + expect(stripNote(), p.id).toBeInTheDocument(); + expect(gap(), p.id).toBeInTheDocument(); + expect(strip(), p.id).toBeInTheDocument(); + expect(ladder(), p.id).toBeInTheDocument(); + expect(ladderNote(), p.id).toBeInTheDocument(); + } + }); + + it("holds every text a region can show, in every preset", async () => { + const w = await open(); + for (const p of HL7_PRESETS) { + await choose(w, p.id); + for (const [region, sample] of everyText()) { + expect( + ghosts(region(), sample).length, + `${p.id}: ${sample.slice(0, 40)}`, + ).toBeGreaterThan(0); + } + } + }); + + it("keeps the hold of a text region while its live text changes", async () => { + const w = await open(); + await choose(w, HL7_PRESETS[0]!.id); + const before = everyText().map(([r, s]) => ghosts(r(), s).length); + for (const p of HL7_PRESETS) { + await choose(w, p.id); + expect( + everyText().map(([r, s]) => ghosts(r(), s).length), + p.id, + ).toEqual(before); + } + }); +}); diff --git a/apps/dox/src/lib/hl7-timestamp-reader-mount.ts b/apps/dox/src/lib/hl7-timestamp-reader-mount.ts new file mode 100644 index 000000000..59d3f25ac --- /dev/null +++ b/apps/dox/src/lib/hl7-timestamp-reader-mount.ts @@ -0,0 +1,598 @@ +/** + * The HL7 Timestamp Reader widget (HLTH-93), mountable on its tool page and in the chat rail. + * + * One HL7 v2 date-time, a `DTM` or a `TS` with its degree of precision after `^`, read by + * `parseHL7`. The widget shows the kind the value is (an instant, a local time, a span or the + * null value), the same digits taken apart by the standard's own picture, and, for a value with no + * offset, the instants it names in the zones the reader chooses beside the one a parser that + * assumes UTC gets. A ladder writes the value back at every precision with `formatHL7`. Every + * printed call and result is the real one. + * + * `null` from the library renders as NO SIGNAL with one sentence saying why. A blank form makes + * no call and reads "nothing to read", never amber. + * + * Built on the component kit: `renderHl7TimestampReaderTemplate` writes the markup from builders + * only, with ids from `idScope(idPrefix)`. `mount` finds its parts by those ids and listens once + * on the widget with the mount's `signal`, so the host dropping the subtree is a complete + * teardown. Nothing in the server-rendered template holds a result. + */ +import { defineElements } from "~/widgets/define"; +import { + field, + fieldGrid, + findWidget, + html, + idScope, + section, + setHtml, + srOnly, + table, + textInput, + widget, + type SafeHtml, +} from "~/widgets/builders"; +import { + callFrameContent, + callFrameHold, + emptyOutput, + lostOutput, + outputContent, + outputHold, + outputOf, + valueOutput, +} from "~/widgets/families/edi/edi-call"; +import { + ediFigure, + figureContent, + type FigureValue, +} from "~/widgets/families/edi/edi-figure"; +import { holdText } from "~/widgets/families/edi/edi-hold"; +import { + memberTable, + setMember, + zoneStrip, +} from "~/widgets/families/edi/edi-table"; +import { + ediTimeline, + timelineContent, +} from "~/widgets/families/edi/edi-timeline"; +import { + asideContent, + asideHold, + drawStripRows, + refusalParagraphs, + setSummary, + stripSummary, + verdictContent, + verdictHold, + type StripRow, +} from "~/widgets/families/edi/edi-view"; +import { preset, type GmtPreset } from "~/widgets/primitives/preset/preset"; +import styles from "~/widgets/tools/hl7-timestamp-reader.module.css"; +import { lit } from "./edi-picture"; +import { GAP_PROMPT, formatValue } from "./edi-widgets"; +import type { Hl7Lib } from "./hl7-lib"; +import { loadHl7Lib } from "./hl7-lib"; +import { + CUSTOM_PRESET_ID, + HL7_PRESETS, + LADDER_HEAD_OFFSET, + MEMBER_ROWS, + READ_AS_UTC, + detailText, + hl7Blank, + hl7Figure, + hl7Texts, + isSeeded, + ladderOf, + matchPreset, + memberReadout, + permalinkOf, + presetState, + readArgs, + readHl7, + sentinelText, + stripApplies, + stripNote, + stripOf, + timelineEmptyText, + verdictText, + type Hl7Args, + type Hl7Read, + type Hl7State, +} from "./hl7-timestamp-reader"; +import { onceDestroy, type MountFn } from "./widget-mount"; + +export type { Hl7Args } from "./hl7-timestamp-reader"; + +const WIDGET_NAME = "hl7-timestamp-reader"; + +const PRECISION_ROWS = [ + "year", + "month", + "day", + "hour", + "minute", + "second", + "fraction", +] as const; + +/** The characters the widest ladder cell can hold: `20240615103045.1234+0530`. */ +const LADDER_CELL_WIDTH = 24; + +/** The tallest picture the figure draws: every kind of field in one value. */ +const RESERVED_FIGURES: readonly FigureValue[] = [ + { + halves: [ + { + label: "", + fields: [ + lit("2024", "YYYY", "date"), + lit("06", "MM", "date"), + lit("15", "DD", "date"), + lit("10", "HH", "time"), + lit("30", "MM", "time"), + lit("45", "SS", "time"), + lit(".1234", ".SSSS", "time"), + lit("0", "", "none"), + lit("+0530", "±HHMM", "offset"), + lit("^S", "^D", "neutral"), + ], + }, + ], + separator: "", + closing: "", + }, +]; + +const EMPTY_FIGURE = "Type a value to take it apart."; +const NO_ZONE = "no zone chosen"; +const NOTHING_TO_READ = "nothing to read"; + +/** The ladder: seven rows, a precision and two writes of the value. Cells are written by `mount`. */ +function ladderTable(id: (local: string) => string, third: string): SafeHtml { + return table({ + caption: "The value written at each precision", + rowHeader: "precision", + layout: "fixed", + widths: ["16%", null, null], + columns: [ + { key: "precision", header: "Precision", align: "start", numeric: false }, + { key: "sent", header: "As sent", align: "start", numeric: true }, + { key: "third", header: third, align: "start", numeric: true }, + ], + rows: PRECISION_ROWS.map((p) => ({ + precision: html`${p}`, + sent: html` `, + third: html` `, + })), + }); +} + +/** + * The widget's chrome, seeded with `args` so the first paint shows them. With no value it shows the + * first preset. Results are drawn by `mount`, because they come from the real library calls. + */ +export function renderHl7TimestampReaderTemplate( + idPrefix: string, + args: Hl7Args = {}, +): SafeHtml { + const id = idScope(idPrefix); + const state: Hl7State = isSeeded(args) + ? readArgs(args) + : presetState(HL7_PRESETS[0]!); + const presetId = matchPreset(state); + const t = hl7Texts(); + + const input = section( + { id: id("input"), heading: "1. Type an HL7 date-time", level: 4 }, + html`
${preset({ + id: id("preset"), + label: "Preset", + value: presetId, + options: [ + { value: CUSTOM_PRESET_ID, label: "Custom", description: "" }, + ...HL7_PRESETS.map((p) => ({ + value: p.id, + label: p.label, + description: p.description, + })), + ], + })}${fieldGrid( + html`
${field({ + id: id("value"), + label: "HL7 value (DTM or TS)", + control: ({ id: cid, describedBy }) => + textInput({ + id: cid, + value: state.value, + autocomplete: "off", + spellcheck: false, + maxLength: 64, + describedBy, + }), + })}
`, + )}
`, + ); + + const states = section( + { id: id("states"), heading: "2. What the value states", level: 4 }, + html`
+
+
${ediFigure({ + id: id("figure"), + spec: { kind: "empty", text: EMPTY_FIGURE }, + reserve: RESERVED_FIGURES, + })}${asideHold({ + id: id("reason"), + paragraphs: [], + reasons: t.reasons, + })}
+ ${callFrameHold({ + id: id("parse-call"), + spec: { label: "Call made", calls: [] }, + samples: [t.parseCall], + })} +
+
${verdictHold({ + id: id("verdict"), + titles: t.verdicts, + details: t.details, + })}${memberTable({ + id, + caption: "What the parser returned, member by member", + prefix: "member", + rows: MEMBER_ROWS.map((r) => ({ key: r.key, label: r.label })), + })}${outputHold({ + id: id("parse-output"), + label: "What the call returned", + state: emptyOutput(NOTHING_TO_READ), + samples: [t.parseOutput], + })}
+
`, + ); + + const lands = section( + { + id: id("lands"), + heading: "3. Where a value with no offset lands", + level: 4, + }, + html`${holdText({ + id: id("strip-note"), + role: "note", + label: "Where a value with no offset lands", + text: "", + samples: t.stripNotes, + })} +
+
+
${ediTimeline({ + id: id("timeline"), + spec: { kind: "empty", text: "" }, + })}
+ ${holdText({ + id: id("gap"), + role: "status", + label: "Widest gap", + text: "", + samples: [...t.gaps, GAP_PROMPT], + })} +
+
+
${zoneStrip({ + id, + caption: "The same local time in up to four zones", + third: READ_AS_UTC, + zones: state.zones, + disabled: false, + widths: { instant: 20, third: 18 }, + })}
+

${srOnly("")}

+ ${asideHold({ + id: id("strip-aside"), + paragraphs: [], + reasons: t.reasons, + count: 2, + })} + ${callFrameHold({ + id: id("strip-call"), + spec: { label: "Calls made", calls: [] }, + samples: [t.stripCall], + })}${outputHold({ + id: id("strip-output"), + label: "What the calls returned", + state: emptyOutput(NO_ZONE), + samples: [t.stripOutput], + })} +
+
`, + ); + + const back = section( + { + id: id("back"), + heading: "4. Written back by formatHL7", + level: 4, + }, + html`
${ladderTable(id, LADDER_HEAD_OFFSET)}
${holdText( + { + id: id("ladder-note"), + role: "note", + label: "About the written values", + text: "", + samples: t.ladderNotes, + }, + )}
`, + ); + + return widget( + { name: WIDGET_NAME, label: "HL7 Timestamp Reader", scope: idPrefix }, + html`${input}${states}${lands}${back}`, + ); +} + +// --------------------------------------------------------------------------- +// Wiring +// --------------------------------------------------------------------------- + +interface Controller { + readState(): Hl7State; + apply(s: Hl7State): void; + render(): void; + syncPreset(s: Hl7State): void; +} + +function setupWidget( + root: HTMLElement, + lib: Hl7Lib, + signal: AbortSignal, +): Controller { + const { el: widgetEl, part: el, id } = findWidget(root, WIDGET_NAME); + const presetEl = widgetEl.querySelector("gmt-preset")!; + const valueEl = el("value"); + const zone = (n: number) => el(`zone-${n}`); + + let destroyed = false; + let ladderHead = LADDER_HEAD_OFFSET; + signal.addEventListener("abort", () => { + destroyed = true; + }); + + const readState = (): Hl7State => ({ + value: valueEl.value, + zones: [1, 2, 3, 4].map((n) => zone(n).value) as Hl7State["zones"], + }); + + function syncPreset(s: Hl7State): void { + presetEl.value = matchPreset(s); + } + + function renderStrip(s: Hl7State, read: Hl7Read): void { + const applies = stripApplies(read); + const parsed = read.parsed; + el("strip-note").textContent = stripNote(read); + + const strip = + applies && parsed?.kind === "local" + ? stripOf(parsed.local, s.zones, lib) + : null; + const rows: StripRow[] = + strip !== null + ? strip.rows + : s.zones.map((z) => ({ + zone: z.trim(), + instant: "", + offset: "", + third: "", + reason: "", + })); + drawStripRows(el, rows, applies); + + const gap = strip?.gap ?? null; + el("gap").textContent = applies ? (gap ? gap.text : GAP_PROMPT) : ""; + + // The one shared UTC timeline: the zones' marks and the instant a UTC parser would name, the + // one instant a value states, or an empty state in words. + setHtml( + el("timeline"), + strip !== null + ? timelineContent({ + kind: "marks", + rows: rows + .map((r, i) => ({ n: i + 1, zone: r.zone, instant: r.instant })) + .filter((r) => r.zone !== ""), + gap, + reference: + strip.utcReading === "" + ? null + : { instant: strip.utcReading, label: READ_AS_UTC }, + }) + : parsed?.kind === "instant" + ? timelineContent({ kind: "stated", instant: parsed.instant }) + : timelineContent({ kind: "empty", text: timelineEmptyText(read) }), + ); + + setSummary( + el("strip-summary"), + strip !== null + ? `${stripSummary(rows, gap ? gap.text : "", READ_AS_UTC.toLowerCase())}${strip.utcReading === "" ? "" : ` Read as UTC: ${strip.utcReading}.`}` + : stripNote(read), + ); + setHtml(el("strip-aside"), asideContent(refusalParagraphs(rows))); + + // The calls the strip made, as the real ones, and what each returned. + const calls = strip?.calls ?? []; + setHtml(el("strip-call"), callFrameContent({ label: "Calls made", calls })); + setHtml( + el("strip-output"), + outputContent( + "What the calls returned", + calls.length === 0 + ? emptyOutput(applies ? NO_ZONE : NOTHING_TO_READ) + : outputOf( + calls.some((c) => c.result === "" || c.result === null) + ? "sentinel" + : "ok", + calls, + ), + ), + ); + + drawLadder(read, strip); + } + + /** The ladder: seven rows of real `formatHL7` calls, or the empty state. */ + function drawLadder( + read: Hl7Read, + strip: ReturnType | null, + ): void { + const ladder = ladderOf(read, strip, lib); + if (ladder.third !== ladderHead) { + ladderHead = ladder.third; + setHtml(el("ladder"), ladderTable(id, ladder.third)); + } + for (const row of ladder.rows) { + for (const [col, cell] of [ + ["sent", row.sent], + ["third", row.offset], + ] as const) { + const target = el(`ladder-${row.precision}-${col}`); + target.textContent = cell.text === "" ? " " : cell.text; + target.dataset["state"] = cell.state; + } + } + el("ladder-note").textContent = ladder.note; + } + + function render(): void { + if (destroyed) return; + const s = readState(); + + // Section 2: the one call. A blank form makes none: it is the empty state, never the sentinel. + const blank = hl7Blank(s); + const read = readHl7(s, lib); + setHtml( + el("parse-call"), + callFrameContent({ + label: "Call made", + calls: read.parse === null ? [] : [read.parse], + }), + ); + setHtml( + el("parse-output"), + outputContent( + "What the call returned", + blank + ? emptyOutput(NOTHING_TO_READ) + : read.parsed === null + ? lostOutput() + : valueOutput(formatValue(read.parsed)), + ), + ); + const refused = !blank && read.parsed === null; + setHtml( + el("verdict"), + read.parsed === null + ? verdictContent("", "") + : verdictContent(verdictText(read), detailText(read)), + ); + for (const row of MEMBER_ROWS) { + const r = memberReadout(read, row.key); + setMember(el(`member-${row.key}`), r.text, r.state); + } + if (blank) { + setHtml( + el("figure"), + figureContent({ kind: "empty", text: EMPTY_FIGURE }), + ); + } else { + const fig = hl7Figure(read, lib); + setHtml( + el("figure"), + figureContent({ + kind: "value", + halves: fig.halves, + separator: fig.separator, + closing: fig.closing, + aria: fig.aria, + }), + ); + } + setHtml( + el("reason"), + asideContent(refused ? [sentinelText(read, lib)] : []), + ); + + // Sections 3 and 4: the strip and the ladder. + renderStrip(s, read); + } + + /** Write a whole state onto the controls. */ + function apply(s: Hl7State): void { + valueEl.value = s.value; + [1, 2, 3, 4].forEach((n) => { + zone(n).value = s.zones[n - 1] ?? ""; + }); + } + + widgetEl.addEventListener( + "input", + (e) => { + if (destroyed) return; + if (e.target !== valueEl) return; + syncPreset(readState()); + render(); + }, + { signal }, + ); + + widgetEl.addEventListener( + "change", + (e) => { + if (destroyed) return; + const target = e.target; + if (target === presetEl) { + const chosen = HL7_PRESETS.find((p) => p.id === presetEl.value); + if (!chosen) return; + apply(presetState(chosen)); + syncPreset(readState()); + render(); + return; + } + if ([1, 2, 3, 4].some((n) => target === zone(n))) { + syncPreset(readState()); + render(); + } + }, + { signal }, + ); + + syncPreset(readState()); + render(); + + return { readState, apply, render, syncPreset }; +} + +export const mountHl7TimestampReader: MountFn = async ( + root, + args, + signal, +) => { + defineElements(); + // `loadHl7Lib` already throws a `WidgetLoadError`; the host decides what to show. + const lib = await loadHl7Lib(); + if (signal.aborted) return onceDestroy(() => {}); + + const reader = setupWidget(root, lib, signal); + if (isSeeded(args)) { + reader.apply(readArgs(args)); + reader.syncPreset(reader.readState()); + reader.render(); + } + + return onceDestroy( + () => {}, + () => permalinkOf(reader.readState()), + ); +}; diff --git a/apps/dox/src/lib/hl7-timestamp-reader.test.ts b/apps/dox/src/lib/hl7-timestamp-reader.test.ts new file mode 100644 index 000000000..646a5046f --- /dev/null +++ b/apps/dox/src/lib/hl7-timestamp-reader.test.ts @@ -0,0 +1,462 @@ +/** + * The HL7 Timestamp Reader's pure module against the real `@northguild/gmt`: presets, what each + * kind of value states, the strip, the writer ladder and the permalink round trip. + */ +import { hl7Lib as lib } from "~/test/hl7-lib"; +import { + CUSTOM_PRESET_ID, + HL7_PRESETS, + LADDER_HEAD_OFFSET, + MEMBER_ROWS, + REASON_DEGREE, + REASON_PICTURE, + LADDER_HEAD_UTC, + detailText, + hl7Blank, + hl7Figure, + hl7Texts, + isSeeded, + ladderOf, + laterText, + matchPreset, + memberReadout, + permalinkOf, + presetState, + readArgs, + readHl7, + sentinelText, + stripApplies, + stripNote, + stripOf, + timelineEmptyText, + verdictText, +} from "./hl7-timestamp-reader"; + +const stateOf = (value: string, ...zones: string[]) => ({ + value, + zones: [zones[0] ?? "", zones[1] ?? "", zones[2] ?? "", zones[3] ?? ""] as [ + string, + string, + string, + string, + ], +}); +const read = (value: string) => readHl7(stateOf(value), lib); + +describe("presets", () => { + it("have unique ids, and each one is matched back by its own state", () => { + const ids = HL7_PRESETS.map((p) => p.id); + expect(new Set(ids).size).toBe(ids.length); + for (const p of HL7_PRESETS) { + expect(matchPreset(presetState(p))).toBe(p.id); + } + }); + + it("is custom once a value or a zone differs", () => { + const first = HL7_PRESETS[0]!; + expect(matchPreset({ ...presetState(first), value: "2024" })).toBe( + CUSTOM_PRESET_ID, + ); + expect( + matchPreset({ ...presetState(first), zones: ["UTC", "", "", ""] }), + ).toBe(CUSTOM_PRESET_ID); + }); + + it("states the kind each one is named for", () => { + const kinds: Record = { + "no-offset": "local", + offset: "instant", + "minus-zero": "instant", + fraction: "instant", + "fall-back": "local", + "spring-forward": "local", + midnight: "local", + "ts-month": "partial", + "ts-day": "partial", + "ts-finer": "", + "birth-year": "partial", + "null-value": "null", + "five-digits": "", + }; + expect(Object.keys(kinds).sort()).toEqual( + HL7_PRESETS.map((p) => p.id).sort(), + ); + for (const p of HL7_PRESETS) { + const r = readHl7(presetState(p), lib); + expect(r.parsed?.kind ?? "", p.id).toBe(kinds[p.id]); + } + }); +}); + +describe("args and permalinks", () => { + it("seeds from a value, or from a known preset", () => { + expect(isSeeded({ value: "2024" })).toBe(true); + expect(isSeeded({ preset: "ts-month" })).toBe(true); + expect(isSeeded({ preset: "nope" })).toBe(false); + expect(isSeeded({})).toBe(false); + expect(readArgs({ preset: "ts-month" }).value).toBe("199904011200^L"); + }); + + it("keeps a typed value untrimmed and blanks an absent key", () => { + expect(readArgs({ value: " 2024 ", zone2: "UTC" })).toEqual({ + value: " 2024 ", + zones: ["", "UTC", "", ""], + }); + }); + + it("names the preset alone while the state matches one", () => { + expect(permalinkOf(presetState(HL7_PRESETS[0]!))).toEqual({ + preset: HL7_PRESETS[0]!.id, + }); + }); + + it("round-trips a custom state through its link", () => { + const state = stateOf(" 20240615103000", " Europe/Oslo ", "", "UTC"); + const link = permalinkOf(state); + expect(link).toEqual({ + value: " 20240615103000", + zone1: "Europe/Oslo", + zone3: "UTC", + }); + const back = readArgs(link); + expect(back.value).toBe(state.value); + expect(back.zones.map((z) => z.trim())).toEqual( + state.zones.map((z) => z.trim()), + ); + }); + + it("calls only an untouched field blank", () => { + expect(hl7Blank(stateOf(""))).toBe(true); + expect(hl7Blank(stateOf(" "))).toBe(false); + expect(hl7Blank(stateOf('""'))).toBe(false); + }); +}); + +describe("reading", () => { + it("makes no call for a blank field", () => { + const r = read(""); + expect(r.parse).toBeNull(); + expect(verdictText(r)).toBe(""); + }); + + it("says what each kind states", () => { + expect(verdictText(read("20240615103000"))).toBe( + "No offset: the sender's local time", + ); + expect(verdictText(read("20240615103000+0200"))).toBe("Offset stated"); + expect(verdictText(read("202406"))).toBe("A span, not a moment"); + expect(verdictText(read('""'))).toBe("The HL7 null value"); + expect(verdictText(read("2024061510300"))).toBe(""); + expect(detailText(read("20240615103000"))).toContain("not UTC"); + expect(detailText(read("202406"))).toContain("month"); + expect(detailText(read('""'))).toContain("delete"); + }); + + it("reads -0000 and +0000 as the same offset", () => { + for (const v of ["20240615103000-0000", "20240615103000+0000"]) { + expect(read(v).parsed).toMatchObject({ offset: "+00:00" }); + } + }); + + it("gives the member rows a readout for every kind", () => { + for (const v of ["20240615103000", "20240615103000+0200", "202406", '""']) { + expect(memberReadout(read(v), "kind")).not.toBe(""); + } + }); + + it("reads the sentinel apart from a legitimately empty result", () => { + expect(read("20240615^S").parsed).toBeNull(); + expect(read('""').parsed).toEqual({ kind: "null" }); + expect(sentinelText(read("20240615^S"), lib)).not.toBe(""); + }); + + it("names the degree only when the DTM before any & reads", () => { + expect(sentinelText(read("20240615^S"), lib)).toBe(REASON_DEGREE); + // what is not expected is ignored (ch. 2 §2.6.2) + expect(sentinelText(read("20240615^S^"), lib)).toBe(REASON_DEGREE); + expect(sentinelText(read("20240615^S^X"), lib)).toBe(REASON_DEGREE); + expect(sentinelText(read("20240615&X^S"), lib)).toBe(REASON_DEGREE); + expect(sentinelText(read("2024061^D"), lib)).toBe(REASON_PICTURE); + expect(sentinelText(read("&X^D"), lib)).toBe(REASON_PICTURE); + expect(sentinelText(read("20240615~D"), lib)).toBe(REASON_PICTURE); + }); + + it("applies the strip to a local value only", () => { + expect(stripApplies(read("20240615103000"))).toBe(true); + expect(stripApplies(read("20240615103000+0200"))).toBe(false); + expect(stripApplies(read("202406"))).toBe(false); + expect(stripApplies(null)).toBe(false); + expect(stripNote(read("20240615103000"))).toContain("reject"); + expect(stripNote(read("202406"))).toContain("span"); + expect(timelineEmptyText(read("202406"))).toContain("span"); + expect(timelineEmptyText(null)).toContain("No value"); + }); +}); + +describe("the strip", () => { + it("reads Kolkata 5 h 30 min before the same digits read as UTC", () => { + const s = stripOf("2024-06-15T10:30:00", ["Asia/Kolkata", ""], lib); + expect(s.rows[0]).toMatchObject({ + zone: "Asia/Kolkata", + instant: "2024-06-15T05:00:00Z", + third: "5 h 30 min later", + }); + expect(s.rows[1]!.zone).toBe(""); + expect(s.utcReading).toBe("2024-06-15T10:30:00Z"); + }); + + // A fraction in the widest gap is kept, not rounded away: edi-widgets.test.ts (durationText). + it("names the widest gap and the two zones it lies between", () => { + const s = stripOf("2024-06-15T10:30:00", ["Asia/Kolkata", "UTC"], lib); + expect(s.gap?.text).toBe( + "Widest gap: 5 h 30 min, between Asia/Kolkata and UTC", + ); + }); + + it("refuses a time the clock shows twice, and says why", () => { + const s = stripOf("2024-11-03T01:30:00", ["America/New_York"], lib); + expect(s.rows[0]!.instant).toBe(""); + expect(s.rows[0]!.reason).not.toBe(""); + }); + + it("words the distance both ways", () => { + expect(laterText("PT0S")).toBe("the same time"); + expect(laterText("-PT4H")).toBe("4 h earlier"); + expect(laterText("PT4H")).toBe("4 h later"); + }); +}); + +describe("the writer ladder", () => { + it("has seven rows from year to fraction", () => { + const l = ladderOf(read("20240615103045.1234+0000"), null, lib); + expect(l.rows.map((r) => r.precision)).toEqual([ + "year", + "month", + "day", + "hour", + "minute", + "second", + "fraction", + ]); + expect(l.third).toBe(LADDER_HEAD_UTC); + expect(l.rows[0]!.sent).toEqual({ text: "2024+0000", state: "value" }); + }); + + it("never rounds up, and says no result for a finer precision", () => { + const l = ladderOf(read("20240615103000"), null, lib); + expect(l.rows[6]!.sent.state).toBe("none"); + expect(l.rows[5]!.sent.text).toBe("20240615103000"); + expect(l.third).toBe(LADDER_HEAD_OFFSET); + }); + + it("keeps the fraction digits as sent, trailing zeros too", () => { + const l = ladderOf(read("20240615103000.1000+0000"), null, lib); + expect(l.rows[6]!.sent).toEqual({ + text: "20240615103000.1000+0000", + state: "value", + }); + expect(l.rows[6]!.offset).toEqual({ + text: "20240615103000.1000+0000", + state: "value", + }); + expect(l.note).toContain('"2024-06-15T10:30:00.1000+00:00"'); + }); + + it("writes a fraction of zeros, which is still a fraction", () => { + const l = ladderOf(read("20240615103000.0000+0200"), null, lib); + expect(l.rows[6]!.sent.text).toBe("20240615103000.0000+0200"); + expect(l.rows[6]!.offset.text).toBe("20240615083000.0000+0000"); + }); + + it("makes up no seconds for a value sent to the minute", () => { + const l = ladderOf(read("202406151030+0200"), null, lib); + expect(l.rows[4]!.sent.text).toBe("202406151030+0200"); + expect(l.rows[4]!.offset.text).toBe("202406150830+0000"); + expect(l.rows[5]!.sent.state).toBe("none"); + expect(l.rows[5]!.offset.state).toBe("none"); + expect( + ladderOf(read("20240615103000^M"), null, lib).rows[5]!.sent.state, + ).toBe("none"); + }); + + it("writes a local value in zone 1 with the digits as sent", () => { + const zoned = ladderOf( + read("20240615103000.1000"), + stripOf("2024-06-15T10:30:00.1000", ["Europe/Helsinki"], lib), + lib, + ); + expect(zoned.rows[6]!.sent.text).toBe("20240615103000.1000"); + expect(zoned.rows[6]!.offset.text).toBe("20240615103000.1000+0300"); + + const minute = ladderOf( + read("202406151030"), + stripOf("2024-06-15T10:30:00", ["Europe/Helsinki"], lib), + lib, + ); + expect(minute.rows[4]!.offset.text).toBe("202406151030+0300"); + expect(minute.rows[5]!.sent.state).toBe("none"); + expect(minute.rows[5]!.offset.state).toBe("none"); + }); + + it("makes no call for a partial value that carries an offset", () => { + const l = ladderOf(read("202406-0500"), null, lib); + expect(l.note).toMatch(/makes no call/); + expect(l.rows.every((r) => r.sent.state === "empty")).toBe(true); + }); + + it("is empty for a blank field", () => { + const l = ladderOf(read(""), null, lib); + expect(l.note).toBe("Nothing to write: there is no value."); + expect(l.rows.every((r) => r.sent.state === "empty")).toBe(true); + }); +}); + +describe("figure widths", () => { + it("reserves the width the longest value takes, read off formatHL7", () => { + const widest = hl7Texts().ladderWidest; + expect( + lib.formatHL7("2024-06-15T10:30:45.1234+05:30", { + precision: "fraction", + }), + ).toBe(widest); + }); + + it("draws every preset", () => { + for (const p of HL7_PRESETS) { + expect(() => hl7Figure(readHl7(presetState(p), lib), lib)).not.toThrow(); + } + }); +}); + +describe("hl7Texts", () => { + const t = hl7Texts(); + + it("covers every preset description and every verdict", () => { + expect(t.descriptions).toHaveLength(HL7_PRESETS.length); + for (const p of HL7_PRESETS) { + const v = verdictText(readHl7(presetState(p), lib)); + if (v !== "") expect(t.verdicts).toContain(v); + } + }); + + it("covers every detail each preset shows", () => { + for (const p of HL7_PRESETS) { + const r = readHl7(presetState(p), lib); + if (r.parsed !== null) expect(t.details).toContain(detailText(r)); + } + }); + + it("covers every reason a refused value can give", () => { + for (const p of HL7_PRESETS) { + const r = readHl7(presetState(p), lib); + if (r.parse !== null && r.parsed === null) { + expect(t.reasons).toContain(sentinelText(r, lib)); + } + } + expect(t.reasons).toContain(REASON_DEGREE); + expect(t.reasons).toContain(REASON_PICTURE); + expect(t.refusals.length).toBeGreaterThan(0); + }); + + it("covers every strip note and ladder note", () => { + for (const p of HL7_PRESETS) { + const r = readHl7(presetState(p), lib); + expect(t.stripNotes).toContain(stripNote(r)); + } + expect(t.stripNotes).toContain(stripNote(null)); + expect(t.ladderNotes).toContain(ladderOf(read(""), null, lib).note); + }); + + it("gives every member row a text for every preset", () => { + for (const p of HL7_PRESETS) { + const r = readHl7(presetState(p), lib); + for (const row of MEMBER_ROWS) { + const m = memberReadout(r, row.key); + expect(m.text, `${p.id}: ${row.label}`).not.toBe(""); + } + } + const r = read("202406"); + expect(memberReadout(r, "instant").text).toBe("none (a span)"); + expect(memberReadout(read("20240615103000"), "offset").text).toBe( + "not sent", + ); + expect(memberReadout(read('""'), "local").text).toBe("no result"); + }); + + it("reads picture widths off formatHL7, each group the characters its precision adds", () => { + const source = "20240615103045.1234+0530"; + expect(t.ladderWidest).toBe(source); + const r = read(source); + expect(r.parsed?.kind).toBe("instant"); + const fields = hl7Figure(r, lib).halves.flatMap((h) => h.fields); + const precisions = [ + "year", + "month", + "day", + "hour", + "minute", + "second", + "fraction", + ] as const; + const local = r.parsed!.kind === "instant" ? r.parsed!.local : ""; + let written = ""; + const widths: string[] = []; + for (const p of precisions) { + const next = lib.formatHL7(local, { precision: p }); + widths.push(next.slice(written.length)); + written = next; + } + expect(fields.slice(0, precisions.length).map((f) => f.text)).toEqual( + widths, + ); + expect(written + "+0530").toBe(source); + }); + + it("reads a figure for every preset that parses, widths summing to what was sent", () => { + for (const p of HL7_PRESETS) { + const r = readHl7(presetState(p), lib); + const fig = hl7Figure(r, lib); + expect(fig.halves[0]!.fields.map((f) => f.text).join(""), p.id).toBe( + r.value, + ); + } + }); + it("draws what is not expected as its own box, ignored and not read (ch. 2 §2.6.2)", () => { + const boxes = (v: string) => + hl7Figure(read(v), lib).halves[0]!.fields.map((f) => ({ + text: f.text, + group: f.group, + bracket: f.bracket, + })); + const ignored = (text: string) => ({ + text, + group: "none", + bracket: "ignored, not read", + }); + expect(boxes("20240615^D^X")).toEqual([ + { text: "2024", group: "date", bracket: undefined }, + { text: "06", group: "date", bracket: undefined }, + { text: "15", group: "date", bracket: undefined }, + { text: "^D", group: "neutral", bracket: "degree" }, + ignored("^X"), + ]); + expect(boxes("20240615103000&X^D").map((f) => f.text)).toEqual([ + "2024", + "06", + "15", + "103000", + "&X", + "^D", + ]); + const cutThenIgnored = hl7Figure(read("20240615103000&X^D"), lib) + .halves[0]!.fields.slice(3, 5) + .map((f) => f.run); + expect(cutThenIgnored).toEqual([undefined, "ignored"]); + expect(boxes("202406151030-0500&X^M&Y").slice(-4)).toEqual([ + { text: "-0500", group: "offset", bracket: undefined }, + ignored("&X"), + { text: "^M", group: "neutral", bracket: "degree" }, + ignored("&Y"), + ]); + }); +}); diff --git a/apps/dox/src/lib/hl7-timestamp-reader.ts b/apps/dox/src/lib/hl7-timestamp-reader.ts new file mode 100644 index 000000000..566e5845d --- /dev/null +++ b/apps/dox/src/lib/hl7-timestamp-reader.ts @@ -0,0 +1,938 @@ +/** + * Pure helpers for the HL7 Timestamp Reader (HLTH-93): one HL7 v2 date-time, a `DTM` or a `TS` + * with its degree of precision after `^`, read by `parseHL7`. + * + * `parseHL7` answers with one of four kinds: `instant` (an offset and a minute or finer), + * `local` (no offset: the sender's local time), `partial` (a year, month, day or hour: a span) + * and `null` (the HL7 null value `""`), or with the sentinel for anything it does not read. A + * `local` value is read in the zones the reader picks with `resolveLocal` and + * `disambiguation: "reject"`, beside the instant a parser that assumes UTC gets + * (`resolveLocal(local, "UTC")`, a library call and never `local + "Z"`). `formatHL7` writes + * the value back at each precision. + * + * Every printed call, and every result beside it, is a real `Hl7Lib` call. The picture's group + * widths are read off `formatHL7`'s own output, and the site holds no table of the `DTM` + * picture. + * + * No DOM and no gmt import: the library comes in from the mount. + * + * Naming rule: strings here name the HL7 v2 standard as data (chapter 2, section 2.A.22, the + * `DTM` and `TS` data types, table 0529) and nothing else: no law, no rule-making body, no + * facility or vendor. Nothing maps a place or a facility to a zone. + */ +import type { Hl7DateTime, Hl7Precision } from "@northguild/gmt/types"; +import { + figureAria, + plainHalves, + type PicField, + type PicHalf, +} from "./edi-picture"; +import { callResultsText } from "./edi-render"; +import { callArgs } from "./punctuality-widgets"; +import { + LONGEST_ZONE, + NO_RESULT_TEXT, + REJECT, + durationText, + readoutOf, + resolveInZone, + resolveReason, + runCall, + widestGap, + type EdiCall, + type WidestGap, +} from "./edi-widgets"; +import type { Hl7Lib } from "./hl7-lib"; + +export const CUSTOM_PRESET_ID = "custom"; + +/** The strip's third column, and the timeline's reference label. */ +export const READ_AS_UTC = "Read as UTC"; + +// --------------------------------------------------------------------------- +// State and args +// --------------------------------------------------------------------------- + +/** What a chat call or a permalink hands over. `preset` is a permalink's alone. */ +export interface Hl7Args { + value?: string; + preset?: string; + zone1?: string; + zone2?: string; + zone3?: string; + zone4?: string; +} + +/** What the DOM holds: all strings. The value is never trimmed. */ +export interface Hl7State { + value: string; + zones: [string, string, string, string]; +} + +// --------------------------------------------------------------------------- +// Presets +// --------------------------------------------------------------------------- + +interface Hl7Preset { + id: string; + label: string; + description: string; + value: string; + zones: [string, string, string, string]; +} + +const NO_ZONES: [string, string, string, string] = ["", "", "", ""]; +const zones = (...picked: string[]): [string, string, string, string] => [ + picked[0] ?? "", + picked[1] ?? "", + picked[2] ?? "", + picked[3] ?? "", +]; + +const ZONE_NOTE = + "The zones are the example's picks, never something the value says: change them."; + +/** The examples. Zones are literal fields, hand-written beside a description that says so. */ +export const HL7_PRESETS: readonly Hl7Preset[] = [ + { + id: "no-offset", + label: "No offset: the sender's local time", + description: `A DTM with no offset. HL7 says it is the sender's local time, so it names no instant until you know the sender's zone. ${ZONE_NOTE}`, + value: "20240615103000", + zones: zones("Asia/Kolkata", "Europe/London"), + }, + { + id: "offset", + label: "An offset sent: +0200", + description: + "The same digits with +0200 after them. The value names one instant, and the offset it sent is the offset in force.", + value: "20240615103000+0200", + zones: NO_ZONES, + }, + { + id: "minus-zero", + label: "-0000: an offset of zero", + description: + "-0000 and +0000 both read as an offset of +00:00, so both name the same instant.", + value: "20240615103000-0000", + zones: NO_ZONES, + }, + { + id: "fraction", + label: "Four fraction digits", + description: + "A fraction of up to four digits after the seconds. The ladder below cuts the value to a coarser precision and never rounds it.", + value: "20240615103045.1234+0000", + zones: NO_ZONES, + }, + { + id: "fall-back", + label: "Clocks go back: a time that happens twice", + description: `01:30 on 27 October 2024 happens twice on a London clock, so resolveLocal with disambiguation: "reject" does not pick one. Tokyo has no such hour. ${ZONE_NOTE}`, + value: "20241027013000", + zones: zones("Europe/London", "Asia/Tokyo"), + }, + { + id: "spring-forward", + label: "Clocks go forward: a time that never happens", + description: `02:30 on 6 October 2024 never happens on a Sydney clock: the clock skips it. resolveLocal with disambiguation: "reject" does not pick another time. ${ZONE_NOTE}`, + value: "20241006023000", + zones: zones("Australia/Sydney", "Africa/Johannesburg"), + }, + { + id: "midnight", + label: "A value to the minute", + description: `The value of the chapter 2 example of a local time, 1988-07-05 at midnight, sent to the minute with no offset. ${ZONE_NOTE}`, + value: "198807050000", + zones: zones("Africa/Johannesburg"), + }, + { + id: "ts-month", + label: "TS with ^L: a month", + description: + "A TS carries a degree of precision after ^. L lowers the value to a month, so the digits after the month are cut by the degree and not read.", + value: "199904011200^L", + zones: NO_ZONES, + }, + { + id: "ts-day", + label: "TS with ^D: a day", + description: + "D lowers the value to a day. A day is a span, so it has no instant.", + value: "20240615103000^D", + zones: NO_ZONES, + }, + { + id: "ts-finer", + label: "TS with ^S, finer than the digits: not read", + description: + "The degree S is finer than the digits sent. A degree can only lower the precision of the digits, so the library does not read the value.", + value: "20240615^S", + zones: NO_ZONES, + }, + { + id: "birth-year", + label: "A year alone", + description: + "A date of birth in PID-7 sent as a year. It names a span of a year, not a moment.", + value: "1965", + zones: NO_ZONES, + }, + { + id: "null-value", + label: 'The null value ""', + description: + "Two double quote marks are the HL7 null value. It deletes what was stored, which is not the same as an empty field. The value here is those two characters, not an empty box.", + value: '""', + zones: NO_ZONES, + }, + { + id: "five-digits", + label: "Five fraction digits: not read", + description: + "A fraction has one to four digits. A fifth is not a precision the standard allows, so the library does not read the value.", + value: "20240615103000.12345", + zones: NO_ZONES, + }, +]; + +const trimmedZones = (state: Hl7State): string[] => + state.zones.map((z) => z.trim()); + +export function presetState(preset: Hl7Preset): Hl7State { + return { value: preset.value, zones: [...preset.zones] }; +} + +/** The preset whose value equals the state's, as typed, and whose zones equal its zones (trimmed). */ +export function matchPreset(state: Hl7State): string { + const picked = trimmedZones(state); + const hit = HL7_PRESETS.find( + (p) => p.value === state.value && p.zones.every((z, i) => z === picked[i]), + ); + return hit ? hit.id : CUSTOM_PRESET_ID; +} + +/** Whether a call or a link seeds the widget: a value, or a preset it names. */ +export function isSeeded(args: Hl7Args): boolean { + return ( + args.value !== undefined || HL7_PRESETS.some((p) => p.id === args.preset) + ); +} + +/** + * The state a chat call or a permalink seeds. A known `preset` is that preset. Otherwise a string + * is kept as typed, an absent key is blank, and nothing falls back to a preset. + */ +export function readArgs(args: Hl7Args): Hl7State { + const named = HL7_PRESETS.find((p) => p.id === args.preset); + if (named !== undefined) return presetState(named); + const text = (v: unknown): string => + typeof v === "string" ? v : typeof v === "number" ? String(v) : ""; + return { + value: text(args.value), + zones: [ + text(args.zone1), + text(args.zone2), + text(args.zone3), + text(args.zone4), + ], + }; +} + +/** + * Strings only. The link names `preset` alone while the state matches one; otherwise the + * non-empty fields. The value is never trimmed, so only an empty value is dropped. + */ +export function permalinkOf(state: Hl7State): Record { + const id = matchPreset(state); + if (id !== CUSTOM_PRESET_ID) return { preset: id }; + const out: Record = {}; + if (state.value !== "") out["value"] = state.value; + state.zones.forEach((z, i) => { + const v = z.trim(); + if (v !== "") out[`zone${i + 1}`] = v; + }); + return out; +} + +/** + * Whether nothing was typed, so no call is made and the widget says "nothing to read". Two + * double quote marks are a value (the null value); only an untouched field is blank. + */ +export function hl7Blank(state: Hl7State): boolean { + return state.value === ""; +} + +// --------------------------------------------------------------------------- +// Reading +// --------------------------------------------------------------------------- + +/** What reading a state made. */ +export interface Hl7Read { + value: string; + /** `parseHL7`'s call; `null` for a blank field, which makes none. */ + parse: EdiCall | null; + /** What it returned; `null` for the sentinel or no call. */ + parsed: Hl7DateTime | null; +} + +export function readHl7(state: Hl7State, lib: Hl7Lib): Hl7Read { + if (hl7Blank(state)) return { value: "", parse: null, parsed: null }; + const parse = runCall(lib, "parseHL7", state.value); + return { + value: state.value, + parse, + parsed: parse.result as Hl7DateTime | null, + }; +} + +// --------------------------------------------------------------------------- +// What the value states +// --------------------------------------------------------------------------- + +const PRECISION_WORDS: Record = { + year: "year", + month: "month", + day: "day", + hour: "hour", +}; + +const DETAIL_INSTANT = + "The value names one instant: the offset it sent is the offset in force."; +const DETAIL_LOCAL = + 'HL7 v2.5.1 2.A.22: "if the time zone is not included, the time zone defaults to that of the local time zone of the sender". It is not UTC. Ask for the sending facility\'s zone.'; +const DETAIL_NULL = + 'The two characters "" delete the value stored. That is not the same as an empty field, which leaves it as it was.'; +const detailPartial = (precision: string): string => + `A ${PRECISION_WORDS[precision] ?? precision} names a span of time, not a moment, so it has no instant in any zone.`; + +const VERDICT_INSTANT = "Offset stated"; +const VERDICT_LOCAL = "No offset: the sender's local time"; +const VERDICT_PARTIAL = "A span, not a moment"; +const VERDICT_NULL = "The HL7 null value"; + +/** The verdict plate's words; `""` when the value has none (blank, or the sentinel). */ +export function verdictText(read: Hl7Read): string { + switch (read.parsed?.kind) { + case "instant": + return VERDICT_INSTANT; + case "local": + return VERDICT_LOCAL; + case "partial": + return VERDICT_PARTIAL; + case "null": + return VERDICT_NULL; + default: + return ""; + } +} + +/** One line under the verdict, by the kind `parseHL7` returned. */ +export function detailText(read: Hl7Read): string { + const parsed = read.parsed; + switch (parsed?.kind) { + case "instant": + return DETAIL_INSTANT; + case "local": + return DETAIL_LOCAL; + case "partial": + return detailPartial(parsed.precision); + case "null": + return DETAIL_NULL; + default: + return ""; + } +} + +type MemberKey = "kind" | "instant" | "offset" | "local" | "precision"; + +export const MEMBER_ROWS: readonly { + key: MemberKey; + label: string; +}[] = [ + { key: "kind", label: "Kind" }, + { key: "instant", label: "Instant" }, + { key: "offset", label: "Offset" }, + { key: "local", label: "Local" }, + { key: "precision", label: "Precision" }, +]; + +const NO_INSTANT_SPAN = "none (a span)"; +const OFFSET_NOT_SENT = "not sent"; + +/** + * One member's text and state. The sentinel and a blank field give every row `no result`; the + * null value gives its kind and `no result` for the rest. A member the value does not state is + * `not stated`, `none (a span)` or `not sent`, in words. + */ +export function memberReadout( + read: Hl7Read, + key: MemberKey, +): { text: string; state: "value" | "absent" | "none" } { + const parsed = read.parsed; + if (parsed === null) return readoutOf(null, false); + if (key === "kind") return readoutOf(parsed.kind, true); + if (parsed.kind === "null") return readoutOf(null, false); + switch (key) { + case "instant": + if (parsed.kind === "instant") return readoutOf(parsed.instant, true); + return parsed.kind === "partial" + ? { text: NO_INSTANT_SPAN, state: "absent" } + : readoutOf(null, true); + case "offset": { + const offset = parsed.kind === "local" ? "" : parsed.offset; + return offset === "" + ? { text: OFFSET_NOT_SENT, state: "absent" } + : readoutOf(offset, true); + } + case "local": + return readoutOf(parsed.local, true); + case "precision": + return readoutOf(parsed.precision, true); + } +} + +// --------------------------------------------------------------------------- +// The strip: a value with no offset read in the zones the reader chose +// --------------------------------------------------------------------------- + +/** The strip applies to a value with no offset and the minute or finer: `"local"` only. */ +export function stripApplies(read: Hl7Read | null): boolean { + return read !== null && read.parsed?.kind === "local"; +} + +const STRIP_NOTE_LOCAL = + 'The value states no offset. Each zone below is a pick, from the example or from you, and not something the value says: the same digits, read there. Every row uses resolveLocal with disambiguation: "reject", so a time the clock shows twice or never is not resolved. Read as UTC is what a parser that assumes UTC gets.'; +const STRIP_NOTE_STATED = + "The value states its offset, so there is nothing to choose."; +const STRIP_NOTE_PARTIAL = + "A span has no instant, so no zone is applied to it."; +const STRIP_NOTE_NONE = "No value to place."; + +export function stripNote(read: Hl7Read | null): string { + switch (read?.parsed?.kind) { + case "local": + return STRIP_NOTE_LOCAL; + case "instant": + return STRIP_NOTE_STATED; + case "partial": + return STRIP_NOTE_PARTIAL; + default: + return STRIP_NOTE_NONE; + } +} + +/** The words the timeline shows when it has no marks to place; never amber. */ +export function timelineEmptyText(read: Hl7Read | null): string { + return read?.parsed?.kind === "partial" + ? "A span has no instant: nothing to place." + : "No value, so no instant to place."; +} + +/** One strip row: the shared `StripRow` fields, with `third` as `Read as UTC` words. */ +interface Hl7StripRow { + zone: string; + instant: string; + offset: string; + third: string; + reason: string; +} + +/** The strip's rows, the UTC reading, the widest gap and every call made, in order. */ +interface Hl7Strip { + rows: Hl7StripRow[]; + /** `resolveLocal(local, "UTC")`, `""` when the library gave none. */ + utcReading: string; + gap: WidestGap | null; + calls: EdiCall[]; +} + +/** "5 h 30 min later", "4 h earlier", "the same time": how far the UTC reading is from the instant. */ +export function laterText(iso: string): string { + if (iso.startsWith("-")) return `${durationText(iso.slice(1))} earlier`; + const text = durationText(iso); + return text === "0 h" ? "the same time" : `${text} later`; +} + +/** + * One row per zone slot: `resolveLocal(local, zone, { disambiguation: "reject" })`, the zone's + * offset, and `diffUtcAsDuration(instant, utcReading, "hours")` through `durationText`. A blank + * slot is `{ zone: "" }`; a refused time carries its `classifyLocal` reason. + */ +export function stripOf( + local: string, + zoneSlots: readonly string[], + lib: Hl7Lib, +): Hl7Strip { + const calls: EdiCall[] = []; + const utc = runCall(lib, "resolveLocal", local, "UTC", REJECT); + const utcReading = utc.result as string; + const rows: Hl7StripRow[] = zoneSlots.map((raw) => { + const resolved = resolveInZone(local, raw, lib); + const row: Hl7StripRow = { ...resolved, third: "" }; + if (resolved.zone !== "") { + calls.push({ + fn: "resolveLocal", + args: [local, resolved.zone, REJECT], + result: resolved.instant, + }); + } + return row; + }); + calls.push(utc); + if (utcReading !== "") { + for (const row of rows) { + if (row.instant === "") continue; + const diff = runCall( + lib, + "diffUtcAsDuration", + row.instant, + utcReading, + "hours", + ); + calls.push(diff); + row.third = laterText(diff.result as string); + } + } + const gap = widestGap(rows, lib); + const instants = rows.filter((r) => r.instant !== "").map((r) => r.instant); + if (gap !== null) { + const min = runCall(lib, "minUtc", instants); + const max = runCall(lib, "maxUtc", instants); + calls.push( + min, + max, + runCall(lib, "diffUtcAsDuration", min.result, max.result, "hours"), + ); + } + return { rows, utcReading, gap, calls }; +} + +// --------------------------------------------------------------------------- +// Why the sentinel +// --------------------------------------------------------------------------- + +export const REASON_DEGREE = + "The degree of precision after ^ is not one of Y L D H M S, or it is finer than the digits sent."; +export const REASON_PICTURE = + "HL7 v2.5.1 2.A.22 reads one field, YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ], and for a TS a degree of precision after ^. A field that does not exist, an hour of 24, a second of 60, more than four fraction digits or a separator other than ^ and & is not read."; + +/** + * The one sentence under NO SIGNAL, decided from a library probe, never guessed. The probe is + * the first component cut at its first `&`, the `DTM` `parseHL7` reads (what is not expected is + * ignored, ch. 2 §2.6.2). When that reads, the degree is what refused the value; when it does + * not, the picture is. + */ +export function sentinelText(read: Hl7Read, lib: Hl7Lib): string { + const [first = ""] = read.value.split("^", 1); + const [dtm = ""] = first.split("&", 1); + return lib.parseHL7(dtm) !== null ? REASON_DEGREE : REASON_PICTURE; +} + +// --------------------------------------------------------------------------- +// The picture: the value as sent, group by group +// --------------------------------------------------------------------------- + +const PRECISIONS: readonly Hl7Precision[] = [ + "year", + "month", + "day", + "hour", + "minute", + "second", + "fraction", +]; + +const RUNGS: Record< + Hl7Precision, + { mask: string; word: string; group: "date" | "time" } +> = { + year: { mask: "YYYY", word: "year", group: "date" }, + month: { mask: "MM", word: "month", group: "date" }, + day: { mask: "DD", word: "day", group: "date" }, + hour: { mask: "HH", word: "hour", group: "time" }, + minute: { mask: "MM", word: "minute", group: "time" }, + second: { mask: "SS", word: "second", group: "time" }, + fraction: { mask: ".S", word: "fraction", group: "time" }, +}; + +interface Hl7Figure { + halves: PicHalf[]; + separator: string; + /** `no offset` when the value sent none, else `""`. */ + closing: string; + aria: string; +} + +/** + * The value taken apart. The width of the group for precision p is the characters + * `formatHL7(local, { precision: p })` adds to the rung before it, for each p up to the result's + * precision. Digits sent past that precision (before any sign, `&` or `^`) are one dashed box, cut + * by the degree and not read. The offset and the `^degree` are their own boxes. What `parseHL7` + * ignores (ch. 2 §2.6.2), the subcomponents after a component's first `&` and every component + * after the second, is a dashed box of its own after the part it follows. The null value and the + * sentinel are one neutral box of the raw text. + */ +export function hl7Figure(read: Hl7Read, lib: Hl7Lib): Hl7Figure { + const raw = read.value; + const parsed = read.parsed; + const plain = (): Hl7Figure => ({ + halves: plainHalves(raw), + separator: "", + closing: "", + aria: figureAria(raw, "", plainHalves(raw), ""), + }); + if (parsed === null || parsed.kind === "null") return plain(); + + const caret = raw.indexOf("^"); + const first = caret < 0 ? raw : raw.slice(0, caret); + const amp = first.indexOf("&"); + const body = amp < 0 ? first : first.slice(0, amp); + const bodyIgnored = first.slice(body.length); + const rest = caret < 0 ? "" : raw.slice(caret); + const degreeEnd = rest.slice(1).search(/[\^&]/); + const degree = degreeEnd < 0 ? rest : rest.slice(0, degreeEnd + 1); + const restIgnored = rest.slice(degree.length); + const signAt = body.search(/[+-]/); + const digits = signAt < 0 ? body : body.slice(0, signAt); + const offsetText = signAt < 0 ? "" : body.slice(signAt); + + const fields: PicField[] = []; + let written = ""; + for (const p of PRECISIONS) { + const next = lib.formatHL7(parsed.local, { precision: p }); + if (next === "" || !next.startsWith(written)) return plain(); + if ( + p === parsed.precision || + PRECISIONS.indexOf(p) <= PRECISIONS.indexOf(parsed.precision) + ) { + const text = next.slice(written.length); + const rung = RUNGS[p]; + fields.push({ + text, + mask: + p === "fraction" + ? `.${"S".repeat(Math.max(text.length - 1, 1))}` + : rung.mask, + group: rung.group, + word: rung.word, + }); + written = next; + } + if (p === parsed.precision) break; + } + if (!digits.startsWith(written)) return plain(); + const cut = digits.slice(written.length); + if (cut !== "") { + fields.push({ + text: cut, + mask: "", + group: "none", + word: "digits cut by the degree, not read", + bracket: "cut by the degree, not read", + }); + } + if (offsetText !== "") { + fields.push({ + text: offsetText, + mask: offsetText.length <= 3 ? "±HH" : "±HHMM", + group: "offset", + word: "offset", + }); + } + if (bodyIgnored !== "") fields.push(ignoredField(bodyIgnored)); + if (degree !== "") { + fields.push({ + text: degree, + mask: "^D", + group: "neutral", + word: "degree of precision", + bracket: "degree", + }); + } + if (restIgnored !== "") fields.push(ignoredField(restIgnored)); + const halves: PicHalf[] = [{ label: "", fields }]; + const closing = offsetText === "" ? "no offset" : ""; + return { + halves, + separator: "", + closing, + aria: figureAria(raw, "", halves, closing), + }; +} + +/** A part `parseHL7` does not read, because it was not expected (ch. 2 §2.6.2). */ +const ignoredField = (text: string): PicField => ({ + text, + mask: "", + group: "none", + word: "not expected, ignored", + bracket: "ignored, not read", + run: "ignored", +}); + +// --------------------------------------------------------------------------- +// The writer ladder +// --------------------------------------------------------------------------- + +/** What a ladder cell is: a library result, `no result`, a hint, or nothing. */ +export interface LadderCell { + text: string; + state: "value" | "none" | "hint" | "empty"; +} + +const EMPTY_CELL: LadderCell = { text: "", state: "empty" }; + +interface Ladder { + /** The third column's name. */ + third: string; + rows: { precision: Hl7Precision; sent: LadderCell; offset: LadderCell }[]; + /** The calls printed once, as sentences; `""` when the ladder makes none. */ + note: string; +} + +export const LADDER_HEAD_OFFSET = "With offset"; +export const LADDER_HEAD_UTC = "In UTC (+0000)"; + +const LADDER_NOTE_NONE = "Nothing to write: there is no value."; +const LADDER_NOTE_PARTIAL_OFFSET = + "A year, month, day or hour that carries an offset has no ISO 8601 form for formatHL7 to take, so this ladder makes no call."; +const LADDER_ONLY_LOWERS = + "formatHL7 only lowers the precision, and a finer one returns no result."; + +const writeCell = (text: string): LadderCell => + text === "" + ? { text: NO_RESULT_TEXT, state: "none" } + : { text, state: "value" }; + +/** The call a ladder prints, with its source text. */ +const ladderCall = (source: string): string => + `formatHL7(${JSON.stringify(source)}, { precision })`; + +/** `YYYY-MM-DDTHH:MM`, the length of a minute-precision ISO 8601 date-time. */ +const MINUTE_FORM = "YYYY-MM-DDTHH:MM".length; + +/** + * `parseHL7`'s `local` written at the precision it was sent with. `local` always writes seconds + * from the minute on, so a minute-precision value loses its `:00`, and `formatHL7` then writes no + * second the sender did not send. + */ +export const sentLocal = (local: string, precision: Hl7Precision): string => + precision === "minute" ? local.slice(0, MINUTE_FORM) : local; + +/** + * `fromOffsetInstant`'s output written with the digits the value was sent with. That output drops + * trailing zeros from the fraction (`.1000` is `.1`, `.0000` is gone) and always writes seconds. + * An offset is whole seconds, so the fraction is the same in every offset: this puts back the + * sent fraction, and cuts a minute-precision value back to the minute. + * + * @param iso a `fromOffsetInstant` result + * @param local `parseHL7`'s `local` for the same value + * @param precision `parseHL7`'s `precision` for the same value + * @returns `iso` with the sent seconds and fraction digits; `iso` unchanged when it has no time + * + * @example inSentForm("2024-06-15T10:30:00.1+00:00", "2024-06-15T10:30:00.1000", "fraction") // "2024-06-15T10:30:00.1000+00:00" + * @example inSentForm("2024-06-15T10:30:00+02:00", "2024-06-15T10:30:00", "minute") // "2024-06-15T10:30+02:00" + */ +export function inSentForm( + iso: string, + local: string, + precision: Hl7Precision, +): string { + const t = iso.indexOf("T"); + if (t < 0) { + return iso; + } + const secondsEnd = t + "THH:MM:SS".length; + // The fraction Temporal wrote, if any: `.` and its digits. + const end = + secondsEnd + (/^\.[0-9]*/.exec(iso.slice(secondsEnd))?.[0].length ?? 0); + const dot = local.indexOf("."); + const head = + precision === "minute" + ? iso.slice(0, t + "THH:MM".length) + : iso.slice(0, secondsEnd); + const fraction = precision === "fraction" && dot >= 0 ? local.slice(dot) : ""; + return head + fraction + iso.slice(end); +} + +/** + * Seven rows, `year` to `fraction`, every cell a real `formatHL7` call. The source is the value + * as sent: `local` at its precision (`sentLocal`), with the offset for an instant, so the writer + * keeps every digit the sender wrote and makes up none. The second column writes it with an + * offset, `+00:00` for an instant and zone 1's for a local value, through `fromOffsetInstant` and + * `inSentForm`. + */ +export function ladderOf( + read: Hl7Read, + strip: Hl7Strip | null, + lib: Hl7Lib, +): Ladder { + const parsed = read.parsed; + const emptyRows = (): Ladder["rows"] => + PRECISIONS.map((precision) => ({ + precision, + sent: EMPTY_CELL, + offset: EMPTY_CELL, + })); + if (parsed === null || parsed.kind === "null") { + return { + third: LADDER_HEAD_OFFSET, + rows: emptyRows(), + note: LADDER_NOTE_NONE, + }; + } + if (parsed.kind === "partial" && parsed.offset !== "") { + return { + third: LADDER_HEAD_OFFSET, + rows: emptyRows(), + note: LADDER_NOTE_PARTIAL_OFFSET, + }; + } + const write = (source: string, precision: Hl7Precision): LadderCell => + writeCell(lib.formatHL7(source, { precision })); + + if (parsed.kind === "instant") { + const asSent = sentLocal(parsed.local, parsed.precision) + parsed.offset; + const inUtc = inSentForm( + lib.fromOffsetInstant({ instant: parsed.instant, offset: "+00:00" }), + parsed.local, + parsed.precision, + ); + return { + third: LADDER_HEAD_UTC, + rows: PRECISIONS.map((precision) => ({ + precision, + sent: write(asSent, precision), + offset: write(inUtc, precision), + })), + note: `As sent: ${ladderCall(asSent)}. In UTC: ${ladderCall(inUtc)}. ${LADDER_ONLY_LOWERS}`, + }; + } + + const local = parsed.local; + if (parsed.kind === "partial") { + return { + third: LADDER_HEAD_OFFSET, + rows: PRECISIONS.map((precision) => ({ + precision, + sent: write(local, precision), + offset: EMPTY_CELL, + })), + note: `As sent: ${ladderCall(local)}. ${LADDER_ONLY_LOWERS}`, + }; + } + + // A local value: the second column writes it with zone 1's offset. + const sent = sentLocal(local, parsed.precision); + const first = strip?.rows[0]; + const withOffset = + first !== undefined && first.instant !== "" && first.offset !== "" + ? inSentForm( + lib.fromOffsetInstant({ + instant: first.instant, + offset: first.offset, + }), + local, + parsed.precision, + ) + : ""; + const hint: LadderCell = { + text: + first === undefined || first.zone === "" + ? "choose zone 1" + : "zone 1 not resolved", + state: "hint", + }; + return { + third: LADDER_HEAD_OFFSET, + rows: PRECISIONS.map((precision) => ({ + precision, + sent: write(sent, precision), + offset: withOffset === "" ? hint : write(withOffset, precision), + })), + note: `As sent: ${ladderCall(sent)}.${withOffset === "" ? "" : ` With an offset: ${ladderCall(withOffset)}.`} ${LADDER_ONLY_LOWERS}`, + }; +} + +// --------------------------------------------------------------------------- +// Every text a region can show, for the height it reserves (`families/edi/edi-hold.ts`) +// --------------------------------------------------------------------------- + +/** The `classifyLocal` answers, to run `resolveReason` over every refusal it words. */ +const refusal = (answer: "ambiguous" | "nonexistent" | null) => + `${LONGEST_ZONE}: ${resolveReason("2024-10-27T01:30:00", LONGEST_ZONE, { + classifyLocal: () => answer, + })}`; + +/** The calls of the tallest reading: a local value in four zones with a widest gap. */ +function tallestCalls(): EdiCall[] { + const local = "2024-06-15T10:30:45.1234"; + const reading = "2024-06-15T10:30:45.1234Z"; + const at = "2024-06-15T05:00:45.1234Z"; + const instants = [at, at, at, at]; + return [ + ...[0, 1, 2, 3].map(() => ({ + fn: "resolveLocal", + args: [local, LONGEST_ZONE, REJECT], + result: at, + })), + { fn: "resolveLocal", args: [local, "UTC", REJECT], result: reading }, + ...[0, 1, 2, 3].map(() => ({ + fn: "diffUtcAsDuration", + args: [at, reading, "hours"], + result: "PT5H30M", + })), + { fn: "minUtc", args: [instants], result: at }, + { fn: "maxUtc", args: [instants], result: at }, + { fn: "diffUtcAsDuration", args: [at, at, "hours"], result: "PT0S" }, + ]; +} + +/** The texts each Reader region can show. */ +export function hl7Texts() { + const longestSource = "2024-06-15T10:30:45.1234+05:30"; + const calls = tallestCalls(); + const parse: EdiCall = { + fn: "parseHL7", + args: ["20240615103045.1234+0000^".padEnd(64, "0")], + result: { + kind: "instant", + instant: "2024-06-15T10:30:45.1234Z", + offset: "+00:00", + local: "2024-06-15T10:30:45.1234", + precision: "fraction", + }, + }; + const callText = (list: readonly EdiCall[]): string => + list.map((c) => `${c.fn}(${callArgs(c.args)[1]})`).join("\n"); + return { + descriptions: HL7_PRESETS.map((p) => p.description), + stripNotes: [ + STRIP_NOTE_LOCAL, + STRIP_NOTE_STATED, + STRIP_NOTE_PARTIAL, + STRIP_NOTE_NONE, + ], + details: [ + DETAIL_INSTANT, + DETAIL_LOCAL, + DETAIL_NULL, + ...["year", "month", "day", "hour"].map(detailPartial), + ], + verdicts: [VERDICT_INSTANT, VERDICT_LOCAL, VERDICT_PARTIAL, VERDICT_NULL], + gaps: [`Widest gap: 26 h, between ${LONGEST_ZONE} and ${LONGEST_ZONE}`], + reasons: [REASON_DEGREE, REASON_PICTURE], + refusals: [refusal("ambiguous"), refusal("nonexistent"), refusal(null)], + ladderNotes: [ + LADDER_NOTE_NONE, + LADDER_NOTE_PARTIAL_OFFSET, + `As sent: ${ladderCall(longestSource)}. With an offset: ${ladderCall(longestSource)}. ${LADDER_ONLY_LOWERS}`, + ], + parseCall: callText([parse]), + parseOutput: callResultsText([parse]), + stripCall: callText(calls), + stripOutput: callResultsText(calls), + ladderWidest: "20240615103045.1234+0530", + }; +} diff --git a/apps/dox/src/lib/industry-overview.test.ts b/apps/dox/src/lib/industry-overview.test.ts index cd9cd1827..ad871f55d 100644 --- a/apps/dox/src/lib/industry-overview.test.ts +++ b/apps/dox/src/lib/industry-overview.test.ts @@ -113,10 +113,11 @@ describe("industry overviews", () => { (id) => { for (const text of everyText(id)) { // A figure typed here would go stale; the pages state none. A function name (`{{..}}`) - // and the standard's own name (X12) are not figures. - expect(text.replace(/\{\{\w+\}\}|\bX12\b/g, ""), "digit").not.toMatch( - /\d/, - ); + // and the standards' own names (X12, HL7) are not figures. + expect( + text.replace(/\{\{\w+\}\}|\bX12\b|\bHL7\b/g, ""), + "digit", + ).not.toMatch(/\d/); expect(text, "GMT").not.toMatch(/\bGMT\b/); expect(text, "law").not.toMatch( /\b(act|statute|regulation|regulator|docket|section|§|cfr|usc)\b/i, diff --git a/apps/dox/src/lib/industry-overview.ts b/apps/dox/src/lib/industry-overview.ts index d13e7678d..898d7ddf2 100644 --- a/apps/dox/src/lib/industry-overview.ts +++ b/apps/dox/src/lib/industry-overview.ts @@ -448,6 +448,82 @@ export const INDUSTRY_OVERVIEWS: Readonly> = { }, ], }, + healthcare: { + about: + 'Healthcare is time in clinical messages. HL7 International calls version two of its HL7 messaging standard "one of the most widely implemented standards for healthcare information in the world". A date and time in an HL7 message says how precise it is by how many digits it carries, and leaves the place out unless the sender adds an offset. This layer reads and writes those values without guessing the place.', + guideTitle: "Healthcare: Clinical Timestamps", + solves: [ + { + problem: "A message time with no offset is stored as UTC.", + answer: + "{{parseHL7}} returns it as a local time with no instant, so the sending facility's zone has to be named before it becomes one.", + see: [ + { + label: "guide", + href: "/guides/industries/healthcare-clinical-timestamps/", + }, + { + label: "scenario", + href: "/scenarios/an-hl7-time-read-as-utc/", + }, + { + label: "HL7 Timestamp Reader", + href: "/tools/hl7-timestamp-reader/", + }, + ], + }, + { + problem: "A birth year is padded to midnight on the first of January.", + answer: + "{{parseHL7}} keeps a year, month, day or hour as a partial value with its precision and no instant.", + see: [ + { + label: "HL7 Timestamp Reader", + href: "/tools/hl7-timestamp-reader/", + }, + { + label: "guide", + href: "/guides/industries/healthcare-clinical-timestamps/", + }, + ], + }, + { + problem: + "An older time stamp whose precision code says it is a date is read as a time.", + answer: + "{{parseHL7}} reads the precision code and cuts the value to it, never past the digits sent.", + see: [ + { + label: "scenario", + href: "/scenarios/a-ts-date-read-as-a-time/", + }, + ], + }, + { + problem: + "A message clears a stored time by sending the null value, and the reader drops it as empty.", + answer: + "{{isValidHL7}} accepts the null value and {{parseHL7}} returns it as its own kind, so it is never mistaken for a missing field.", + see: [ + { + label: "guide", + href: "/guides/industries/healthcare-clinical-timestamps/", + }, + ], + }, + { + problem: "An instant is written back with its offset lost or rounded.", + answer: + "{{formatHL7}} writes the offset the value has, cuts to the precision asked for and never rounds.", + see: [ + { + label: "guide", + href: "/guides/industries/healthcare-clinical-timestamps/", + }, + ], + }, + ], + }, }; /** The `{{name}}` tokens in a pain point's text, in order. */ diff --git a/apps/dox/src/lib/industry-tags.ts b/apps/dox/src/lib/industry-tags.ts index 597b32d4e..48ec3f440 100644 --- a/apps/dox/src/lib/industry-tags.ts +++ b/apps/dox/src/lib/industry-tags.ts @@ -178,6 +178,7 @@ export const INDUSTRY_ICON_PATHS: Readonly> = { "industry-gnss": ``, "industry-maritime": ``, "industry-finance": ``, + "industry-healthcare": ``, }; /** diff --git a/apps/dox/src/lib/mdx-jsx.ts b/apps/dox/src/lib/mdx-jsx.ts index 9bc23cf27..0ed7631e2 100644 --- a/apps/dox/src/lib/mdx-jsx.ts +++ b/apps/dox/src/lib/mdx-jsx.ts @@ -601,6 +601,7 @@ export function renderMdxComponents(body: string): string { "EpcisEventReader", "EtaDrift", "FreeTimeLedger", + "Hl7TimestampReader", "JourneySplit", "PunctualityBoard", "TimetableReader", diff --git a/apps/dox/src/lib/namespace-summary.ts b/apps/dox/src/lib/namespace-summary.ts index 7b75d9bcb..9a3798d2b 100644 --- a/apps/dox/src/lib/namespace-summary.ts +++ b/apps/dox/src/lib/namespace-summary.ts @@ -47,6 +47,8 @@ export const NAMESPACE_SUMMARIES: Readonly> = { gnss: "Functions that convert between UTC and the satellite navigation system times, GNSS week numbers and RINEX weeks.", finance: "Functions that read, write and check the timestamps of financial messages, starting with the FIX UTCTimestamp.", + healthcare: + "Functions that read, write and check HL7 version 2 date-times, keeping the precision sent and a missing offset as local time.", }; /** diff --git a/apps/dox/src/lib/widget-load-error.test.tsx b/apps/dox/src/lib/widget-load-error.test.tsx index ead6269da..bc3b36cbd 100644 --- a/apps/dox/src/lib/widget-load-error.test.tsx +++ b/apps/dox/src/lib/widget-load-error.test.tsx @@ -58,6 +58,10 @@ import { renderDepartureBoardTemplate, } from "./departure-board-mount"; import { mountDtmDecoder, renderDtmDecoderTemplate } from "./dtm-decoder-mount"; +import { + mountHl7TimestampReader, + renderHl7TimestampReaderTemplate, +} from "./hl7-timestamp-reader-mount"; import { mountBlDateStamp, renderBlDateStampTemplate, @@ -264,6 +268,11 @@ const MOUNTS: [string, () => SafeHtml, MountFn][] = [ () => renderDtmDecoderTemplate("dtm-decoder"), mountDtmDecoder as MountFn, ], + [ + "hl7 timestamp reader", + () => renderHl7TimestampReaderTemplate("hl7-timestamp-reader"), + mountHl7TimestampReader as MountFn, + ], [ "x12 time reader", () => renderX12TimeReaderTemplate("x12-time-reader"), diff --git a/apps/dox/src/lib/widget-permalink.ts b/apps/dox/src/lib/widget-permalink.ts index 3e1b8e08f..338839bf4 100644 --- a/apps/dox/src/lib/widget-permalink.ts +++ b/apps/dox/src/lib/widget-permalink.ts @@ -54,6 +54,7 @@ export type WidgetKind = | "departure" | "planner" | "dtm" + | "hl7" | "xtime" | "demclock" | "bldate" @@ -115,6 +116,7 @@ export const WIDGET_PAGE_PATHS: Record = { departure: "/tools/departure-board/", planner: "/tools/zone-planner/", dtm: "/tools/dtm-decoder/", + hl7: "/tools/hl7-timestamp-reader/", xtime: "/tools/x12-time-reader/", demclock: "/tools/demurrage-clock/", bldate: "/tools/bl-date-stamp/", diff --git a/apps/dox/src/test/hl7-lib.ts b/apps/dox/src/test/hl7-lib.ts new file mode 100644 index 000000000..e49fc3e38 --- /dev/null +++ b/apps/dox/src/test/hl7-lib.ts @@ -0,0 +1,32 @@ +/** + * The real gmt functions the HL7 Timestamp Reader's unit tests inject as an `Hl7Lib`, loaded by + * module path so a test never needs the loader's dynamic imports. Cast as `Hl7Lib` through `unknown`, as `test/edi-lib.ts` does, because `resolveLocal`'s options + * are a narrower type than the widgets' `Hl7Lib` states; `hl7-lib.test.ts` checks the two against + * each other. + */ +import { formatHL7 } from "@northguild/gmt/healthcare/format"; +import { parseHL7 } from "@northguild/gmt/healthcare/parse"; +import { + classifyLocal, + fromOffsetInstant, + resolveLocal, + toOffsetInstant, +} from "@northguild/gmt/instant/convert"; +import { + diffUtcAsDuration, + maxUtc, + minUtc, +} from "@northguild/gmt/utc/calculate"; +import type { Hl7Lib } from "~/lib/hl7-lib"; + +export const hl7Lib = { + parseHL7, + formatHL7, + resolveLocal, + classifyLocal, + toOffsetInstant, + fromOffsetInstant, + minUtc, + maxUtc, + diffUtcAsDuration, +} as unknown as Hl7Lib; diff --git a/apps/dox/src/widgets/families/edi/edi-timeline.module.css b/apps/dox/src/widgets/families/edi/edi-timeline.module.css index 9fed3151b..6d0a1d3a5 100644 --- a/apps/dox/src/widgets/families/edi/edi-timeline.module.css +++ b/apps/dox/src/widgets/families/edi/edi-timeline.module.css @@ -142,6 +142,60 @@ line-height: 1; } +/* The reference: a hollow pin on a dashed stem, labelled on the side with room. Nothing here is + a stripe on a card's left edge. */ +.reference { + position: absolute; + inset-block: 0; + inset-inline-start: var(--x); + inline-size: 0; + + &::after { + content: ""; + position: absolute; + inset-block: calc(var(--lane) * 30px + 28px) 0; + inline-size: 2px; + translate: -1px 0; + background: repeating-linear-gradient( + to bottom, + var(--gmt-ice-dim) 0 4px, + transparent 4px 8px + ); + } +} + +.referencePin { + position: absolute; + inset-block-start: calc(var(--lane) * 30px); + translate: -50% 0; + box-sizing: border-box; + inline-size: 28px; + block-size: 28px; + border: 2px solid var(--gmt-ice-dim); + border-radius: var(--gmt-radius-sm); + corner-shape: bevel; + background: transparent; +} + +.referenceLabel { + position: absolute; + inset-block-start: calc(var(--lane) * 30px + 4px); + padding-inline: var(--gmt-space-1); + white-space: nowrap; + background: var(--gmt-surface); + color: var(--gmt-ice-dim); + font-size: var(--gmt-text-xs); + line-height: 20px; + + .reference[data-side="end"] > & { + inset-inline-start: 18px; + } + + .reference[data-side="start"] > & { + inset-inline-end: 18px; + } +} + .bracket { position: absolute; inset-block-end: 26px; @@ -198,6 +252,23 @@ background: CanvasText; } + .reference::after { + background: repeating-linear-gradient( + to bottom, + CanvasText 0 4px, + transparent 4px 8px + ); + } + + .referencePin { + border-color: CanvasText; + } + + .referenceLabel { + background: Canvas; + color: CanvasText; + } + .pin { border-color: CanvasText; background: Canvas; @@ -222,6 +293,7 @@ .label, .day, .caption, + .referenceLabel, .empty { color: var(--gmt-ice); } diff --git a/apps/dox/src/widgets/families/edi/edi-timeline.test.ts b/apps/dox/src/widgets/families/edi/edi-timeline.test.ts index 0ace682b9..8521e670e 100644 --- a/apps/dox/src/widgets/families/edi/edi-timeline.test.ts +++ b/apps/dox/src/widgets/families/edi/edi-timeline.test.ts @@ -60,4 +60,31 @@ describe("ediTimeline", () => { ); expect(host).toHaveTextContent("empty words"); }); + + it("draws the value read as UTC beside the zones, and names it", async () => { + const { host } = renderHtml( + timelineContent({ + kind: "marks", + rows: [{ n: 1, zone: "Asia/Kolkata", instant: "2024-06-15T05:00:00Z" }], + gap: null, + reference: { instant: "2024-06-15T10:30:00Z", label: "Read as UTC" }, + }), + ); + expect(host).toHaveTextContent("Read as UTC"); + expect(screen.getByRole("img")).toHaveAccessibleName( + /Read as UTC: 2024-06-15T10:30:00Z/, + ); + await expectNoAxeViolations(host); + }); + + it("draws no reference without one", () => { + const { host } = renderHtml( + timelineContent({ + kind: "marks", + rows: [{ n: 1, zone: "Asia/Kolkata", instant: "2024-06-15T05:00:00Z" }], + gap: null, + }), + ); + expect(host).not.toHaveTextContent("Read as UTC"); + }); }); diff --git a/apps/dox/src/widgets/families/edi/edi-timeline.ts b/apps/dox/src/widgets/families/edi/edi-timeline.ts index e6ad31704..c5de5d2ae 100644 --- a/apps/dox/src/widgets/families/edi/edi-timeline.ts +++ b/apps/dox/src/widgets/families/edi/edi-timeline.ts @@ -26,6 +26,8 @@ type TimelineSpec = kind: "marks"; rows: readonly TimelineInput[]; gap: WidestGap | null; + /** A comparison instant drawn as a hollow pin: the value read as UTC. Absent draws none. */ + reference?: { instant: string; label: string } | null; }; function plot( @@ -33,6 +35,7 @@ function plot( stated: boolean, gap: string, aria: string, + reference: { label: string } | null = null, ): SafeHtml { const ticks = layout.ticks.map( (t) => @@ -50,6 +53,13 @@ function plot( >${stated ? "" : m.n}`, ); + const ref = + reference === null || layout.reference === null + ? "" + : html`${reference.label}`; const bracket = layout.span === null ? "" @@ -59,7 +69,7 @@ function plot( return html`${marks}${ref}${bracket}
`; } @@ -88,10 +98,14 @@ export function timelineContent(spec: TimelineSpec): SafeHtml { : "No chosen zone gives an instant.", }); } - const layout = timelineLayout(placed)!; + const reference = spec.reference ?? null; + const layout = timelineLayout( + placed, + reference === null ? null : reference.instant, + )!; const gap = spec.gap === null ? "" : durationText(spec.gap.duration); return html`
${plot(layout, false, gap, timelineAria(placed, spec.gap === null ? "" : spec.gap.text, ""))}

${plot(layout, false, gap, timelineAria(placed, spec.gap === null ? "" : spec.gap.text, "", reference), reference)}

All times in UTC.

`; diff --git a/apps/dox/src/widgets/tools/hl7-timestamp-reader.module.css b/apps/dox/src/widgets/tools/hl7-timestamp-reader.module.css new file mode 100644 index 000000000..80bcd0c5d --- /dev/null +++ b/apps/dox/src/widgets/tools/hl7-timestamp-reader.module.css @@ -0,0 +1,118 @@ +/* + * HL7 Timestamp Reader: what only this tool needs. The sections, tables, code frames, verdict and + * asides are the kit's and the EDI family's; this sheet places them and styles the writer ladder's + * cells. The two bands (the value and what it states; the zones and where they land) sit side by + * side where the widget is wide and one under the other where it is not. The widget root is the + * container. + * + * Nothing here is a verdict colour. Amber is the sentinel's alone. + */ + +/* The stack of controls keeps a gap. */ +.controls { + display: grid; + gap: var(--gmt-space-3); + min-inline-size: 0; +} + +/* The value field takes the whole row. */ +.main { + grid-column: 1 / -1; + min-inline-size: 0; +} + +/* A band: two panes, a column each when there is room for both. */ +.split, +.pane { + display: flex; + flex-direction: column; + gap: var(--gmt-space-3); + min-inline-size: 0; +} + +@container (inline-size >= 67.75rem) { + .split { + display: grid; + grid-template-columns: minmax(28rem, 1fr) minmax(38.75rem, 1fr); + column-gap: var(--gmt-space-4); + align-items: stretch; + } +} + +/* The box a picture sits in; it takes the pane's spare height so the two bottoms line up. */ +.panel { + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: var(--gmt-space-3); + flex: 1 1 auto; + min-inline-size: 0; + padding: var(--gmt-space-3) var(--gmt-space-4); + border: 1px solid var(--gmt-border); + border-radius: var(--gmt-radius-md); + corner-shape: bevel; + background: var(--gmt-fill-subtle); +} + +/* The ladder and its note stack, a column wide. */ +.written { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: var(--gmt-space-3); + min-inline-size: 0; +} + +/* A ladder cell reserves the width of the longest value it can hold, so a coarser or finer + answer never moves a column edge; a value never wraps. */ +.ladderCell { + display: inline-block; + min-inline-size: var(--w); + font-family: var(--gmt-font-mono); + font-variant-numeric: tabular-nums; + white-space: nowrap; + + /* No result, or a hint to choose a zone, is quieter than a value. */ + &[data-state="none"], + &[data-state="hint"] { + color: var(--gmt-ice-dim); + } +} + +/* Two columns of 24 characters do not fit a phone. Below this width a value breaks inside its + cell, and the cell holds two lines whatever it shows, so nothing moves as the value changes. */ +@media (width <= 36rem) { + .ladderCell { + display: block; + min-inline-size: 0; + min-block-size: 2lh; + white-space: normal; + overflow-wrap: anywhere; + } +} + +.precision { + font-family: var(--gmt-font-mono); +} + +@media (forced-colors: active) { + .panel { + border-color: CanvasText; + background: Canvas; + } + + .ladderCell[data-state="none"], + .ladderCell[data-state="hint"] { + color: CanvasText; + } +} + +@media (prefers-contrast: more) { + .panel { + border-color: var(--gmt-ice); + } + + .ladderCell[data-state="none"], + .ladderCell[data-state="hint"] { + color: var(--gmt-ice); + } +} diff --git a/apps/dox/worker/select-vocabulary.test.ts b/apps/dox/worker/select-vocabulary.test.ts index e88a42ae0..6e2610ba6 100644 --- a/apps/dox/worker/select-vocabulary.test.ts +++ b/apps/dox/worker/select-vocabulary.test.ts @@ -21,6 +21,7 @@ const SKILL_NAMES = [ "gmt-transport", "gmt-intermodal", "gmt-workforce", + "gmt-healthcare", ]; const SKILLS = SKILL_NAMES.map((name) => parseSkill( diff --git a/apps/dox/worker/tools.ts b/apps/dox/worker/tools.ts index 5da676fda..98af2b3a3 100644 --- a/apps/dox/worker/tools.ts +++ b/apps/dox/worker/tools.ts @@ -59,6 +59,7 @@ import { showDemurrageClockInput, showDepartureBoardInput, showDtmDecoderInput, + showHl7TimestampReaderInput, showEpcisEventReaderInput, showElapsedVsClockInput, showGnssRolloverCheckerInput, @@ -378,6 +379,23 @@ export function buildWorkerTools( }, }), + // The zones are the ones the reader named, to read a value with no offset in. + showHl7TimestampReader: tool({ + description: docFor("showHl7TimestampReader"), + inputSchema: showHl7TimestampReaderInput, + execute: ({ zone1, zone2, zone3, zone4 }) => { + const unknown = unknownZones( + [zone1, zone2, zone3, zone4].filter((z): z is string => Boolean(z)), + ); + return unknown.length > 0 + ? reject( + "hl7-timestamp-reader", + `not IANA time zones this runtime knows: ${unknown.join(", ")}.`, + ) + : accept("hl7-timestamp-reader"); + }, + }), + // The zones are the ones the reader named, to read a local time in. showX12TimeReader: tool({ description: docFor("showX12TimeReader"), diff --git a/apps/dox/worker/vocabulary.ts b/apps/dox/worker/vocabulary.ts index 8816ebf03..236fa3551 100644 --- a/apps/dox/worker/vocabulary.ts +++ b/apps/dox/worker/vocabulary.ts @@ -29,6 +29,7 @@ import gmtArithmetic from "../../../packages/gmt/skills/gmt-arithmetic/SKILL.md" import gmtBasics from "../../../packages/gmt/skills/gmt-basics/SKILL.md"; import gmtFinance from "../../../packages/gmt/skills/gmt-finance/SKILL.md"; import gmtGnss from "../../../packages/gmt/skills/gmt-gnss/SKILL.md"; +import gmtHealthcare from "../../../packages/gmt/skills/gmt-healthcare/SKILL.md"; import gmtIntegration from "../../../packages/gmt/skills/gmt-integration/SKILL.md"; import gmtIntermodal from "../../../packages/gmt/skills/gmt-intermodal/SKILL.md"; import gmtTimezone from "../../../packages/gmt/skills/gmt-timezone/SKILL.md"; @@ -45,4 +46,5 @@ export const VOCABULARY_SKILLS: readonly VocabularySkill[] = [ gmtTransport, gmtIntermodal, gmtWorkforce, + gmtHealthcare, ].map((s) => parseSkill(s as unknown as string)); diff --git a/context/coding-standards.md b/context/coding-standards.md index baefc188a..7b2421261 100644 --- a/context/coding-standards.md +++ b/context/coding-standards.md @@ -178,6 +178,16 @@ An RFC 5545 §3.3.10 RECUR value (`FREQ=MONTHLY;BYDAY=-1FR`) and a five-field cr This prohibition stands for every other function in the library. +### Scoped exception: HL7 v2 date/time grammar in `parseHL7` and `formatHL7` (HLTH-93) + +HL7 v2 `DTM` (`YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`, ch. 2A 2.A.22) and the `TS` that wraps it (2.A.77) are not ISO 8601, and no `Temporal.*.from` reads either. The grammar is fixed and published: + +1. The grammar is one regex in `internal/hl7DateTime.ts`, built from fragments named in the picture's own notation, with the split of a `TS` at `^` and `&` and Table 0529 beside it. Fields come out as named groups, never by per-call slicing in a public function. It is not a public pattern: a `DTM` is valid only as a whole, so the public check is `isValidHL7`. A second regex in the same file, `isoHl7Form`, reads the form of `formatHL7`'s ISO 8601 input and never its values: which groups are present (so the written precision, through `isoHl7Precision`), how many fraction digits there are, and whether there is an offset. +2. Extracted fields are **always** checked by Temporal before they are used. `parseHL7` hands them to `Temporal.PlainDate.from(fields, { overflow: "reject" })` and `Temporal.PlainDateTime.from(fields, { overflow: "reject" })`. A value at minute precision or finer that carries an offset is rebuilt as an extended ISO string and read by `toOffsetInstant`; the offset of a partial value (year, month, day or hour precision) is checked with the `utcOffset` regex and normalised with `formatUtcOffset`. `formatHL7` reads its input by the precision it is written at: a year's group goes to `Temporal.PlainDate.from({ year, month: 1, day: 1 }, { overflow: "reject" })`; a month is read from the string by `Temporal.PlainYearMonth.from`; a day is checked with `isValidDate` and then read from the string by `Temporal.PlainDate.from`; an hour's groups go to `Temporal.PlainDateTime.from(fields, { overflow: "reject" })`. A local minute or finer is checked with `isValidDateTime` and read from the string by `Temporal.PlainDateTime.from`, and a form with an offset is read by `toOffsetInstant`. It writes digits from Temporal's fields. +3. The try-catch and sentinel-return rules above are unchanged. + +This prohibition stands for every other function in the library. + ### Calendar-annotated strings are RFC 9557 (E1, E7) A calendar string is the RFC 9557 form Temporal writes: the ISO 8601 date (or zoned datetime), diff --git a/context/domination/issues/HLTH-93.md b/context/domination/issues/HLTH-93.md index 0a9f6266e..a6aa00546 100644 --- a/context/domination/issues/HLTH-93.md +++ b/context/domination/issues/HLTH-93.md @@ -172,3 +172,7 @@ HL7 Europe's published copy. - `isValidHL7('20240615103000-0500')`, `'2024'` and `'""'` are `true`; `'20240615^S'`, `'20240230'` and `''` are `false` - `isValidHL7` agrees with `parseHL7` on every `parseHL7` row above; `isValidHL7(20240615)` and `isValidHL7(null)` are `false` - `pnpm run validate` stays green + +## Decisions + +[Decisions](HLTH-93/decisions.md): the four result kinds, the offset and `TS` degree rules, what `formatHL7` writes and refuses, the clause numbering, and the docs and Dox choices. diff --git a/context/domination/issues/HLTH-93/decisions.md b/context/domination/issues/HLTH-93/decisions.md new file mode 100644 index 000000000..60945fca2 --- /dev/null +++ b/context/domination/issues/HLTH-93/decisions.md @@ -0,0 +1,25 @@ +# HLTH-93 — Decisions + +Part of [HLTH-93](../HLTH-93.md). + +Settled by the owner. They are the current rules for this code. + +- The three functions are `parseHL7`, `formatHL7` and `isValidHL7`, in `healthcare/{parse,format,validate}/`, with the types `Hl7DateTime`, `Hl7Precision` and `Hl7FormatOptions` in `types/hl7.ts`. `Hl7Precision` is the union of `Hl7PartialPrecision` (year to hour, the `"partial"` kind) and `Hl7MomentPrecision` (minute to fraction, the `"instant"` and `"local"` kinds), so each kind's `precision` names only the precisions it can carry; narrowed in review of #494 on 2026-11-10. The subpaths are `@northguild/gmt/healthcare`, `/healthcare/parse`, `/healthcare/format` and `/healthcare/validate`. Sentinels are `null`, `""` and `false`; none throws, for a value of any type. Every call is constant work, so there are no bench rows. +- Section numbers are cited as "2.A.22 (headed 2.A.1.22 in the hl7.eu v2.5.1 copy)", once per JSDoc. hl7.eu numbers `DTM`, `TS` and the degree of precision 2.A.1.22, 2.A.1.77 and 2.A.1.77.2; HL7's own cross-references and the v2.6 copy say 2.A.22 and 2.A.77. The quote "Retained only for purposes of backward compatibility as of v 2.3" is in 2.A.77.2, not 2.A.77 as the issue text says. +- `parseHL7` returns one of four kinds. `"instant"` has an offset and a minute or finer. `"local"` has no offset and a minute or finer, and has no `instant` member. `"partial"` is a year, month, day or hour: it names a span, keeps the offset it was sent with (`""` when none), and has no instant. `"null"` is the string `""` (two double quotes), alone or with only empty components after it (`""^`), which differs from the empty string, which returns `null`. `local` is the wall clock as sent, at the precision sent (`2024-06-15T10`, no minute added), with seconds always written from the minute on and the fraction kept as sent (`.1000`). `instant` is `toOffsetInstant`'s output (`.1Z`). +- No offset is the sender's local time, never UTC (2.A.22). The caller supplies the sender's zone to `resolveLocal`. `+0000` and `-0000` both read `+00:00`. `0000` is the start of the stated day, so `198807050000` is `1988-07-05T00:00:00`. Any `±HHMM` with hours `00`–`23` is read; HL7's "legally-defined time zones" names no list to check against. +- A `TS` degree of precision (`Y L D H M S`, upper case) only lowers the precision, by cutting and never rounding. A degree finer than the digits sent and a lower-case degree return `null`. `^S` on a fractional value cuts the fraction, because Table 0529 has no value for a fraction. +- A lone `TS` carries no MSH-2, so `^` separates its components and `&` their subcomponents, the separators Figure 2-1 recommends (ch. 2 §2.5.4); any other separator returns `null`, and the caller re-joins a `TS` whose MSH-2 names others with `^` and `&` first. A recipient ignores "components, subcomponents, and extra repetitions of a field that are present but were not expected" (ch. 2 §2.6.2), and a later version adds components at the end of a data type (§2.8.1, §2.8.2). So each component is read up to its first `&`, and everything after the second component is ignored: `20240615^D^X` reads as `20240615^D`, `2024&X` as `2024`, and `20240615&X^D` as `20240615^D`. A component left empty is not present (§2.6.2): `20240615^` reads as `20240615`, `20240615^^D` as `20240615`, `20240615^D^` as `20240615^D` and `'""^'` as the null value, while `^D`, `&X` and `'""^D'` return `null`. Settled in review of #494 on 2026-11-10. +- Hour `24`, second `60` and a day the month lacks return `null`; a fraction is one to four digits and follows seconds only. +- `formatHL7` writes a `DTM` and never a `TS`, which HL7 withdrew in v2.6. It reads the precision from the form the input is written in, and `precision` only lowers it; a fraction is cut to four digits, never rounded. A finer `precision` than the value carries, a year outside 0000–9999, an offset with seconds, a reduced ISO form with an offset (`2024-06-15-05:00`) and a local form with a zone annotation and no offset (`2024-06-15T10:30:00[Europe/Helsinki]`) return `""`. It writes the offset the value has (`Z` writes `+0000`) and never drops or rounds one. +- A minute-precision `local` comes back from `parseHL7` with `:00` seconds, so writing it with the digits sent takes `{ precision: result.precision }`. A `"partial"` value with an offset is written from the instant with `{ precision }`, for example `formatHL7("2024-06-15T10:30:00-05:00", { precision: "day" })` is `20240615-0500`. +- The round trip `parseHL7(formatHL7(iso))` holds for instants of four fraction digits or fewer. A longer fraction is cut, so the round trip returns the cut instant. +- `isValidHL7(value)` is `parseHL7(value) !== null`, so the two cannot disagree. `'""'` is valid. +- The grammar lives in `internal/hl7DateTime.ts`, pure (regexes and tables, no Temporal), not in `regex/`: HL7 publishes a format picture, not a pattern, and the public check is `isValidHL7`. `coding-standards.md` carries the scoped exception, as it does for the EDI grammars. The parse and format files import `toOffsetInstant` themselves, and neither imports `fromOffsetInstant`. `formatHL7` reads its input's form with a second regex in the same file, `isoHl7Form`, and hands its fields to Temporal. +- The guide and the mistakes page are named for the industry (`healthcare-clinical-timestamps`, `mistakes/healthcare`), with HL7 under its own `##` heading so HLTH-94 adds a FHIR section beside it. Its type links follow the reference generator: a type one function reaches is an anchor on that function's page (`/reference/healthcare/parse/parseHL7/#hl7datetime`, `/reference/healthcare/format/formatHL7/#hl7formatoptions`, `/reference/healthcare/format/formatHL7/#hl7precision`), and one two functions reach has its own page (`/reference/types/Hl7PartialPrecision/`, `/reference/types/Hl7MomentPrecision/`). +- A skipped or repeated wall time is resolved by `resolveLocal`'s default disambiguation, `"compatible"`: a skipped hour takes the later reading and a repeated hour the earlier. GMT does not refuse it unless the caller passes `"reject"`. The guide says so. +- The hub text on the Healthcare industry (`INDUSTRY_OVERVIEWS.healthcare`) names only `healthcare` functions, since Healthcare declares no `drawsOn`. `HL7` joins `X12` as an exemption from the digit rule in `industry-overview.test.ts`. The glyph is a plain cross. `namespace-summary.ts` carries a healthcare line, which the spec did not name. +- The Dox tool is the HL7 Timestamp Reader at `/tools/hl7-timestamp-reader/`; its rules are in `context/dox/built.md`. The timeline kit gained an optional `reference` mark (the DTM Decoder and X12 Time Reader pass `null`), and `resolveInZone`, `resolveReason` and `widestGap` take `Pick`, which is type-only. +- The realm exports no pattern. HLTH-94 adds the FHIR functions to it without reshaping what is here. +- The root bundle budget in `scripts/bundle-size.budgets.json` is 584000 B. FIN-95 (#493) changed the same line and merged first, so #494 merged `main` in and measured again, as agreed in review of #494 on 2026-11-10. With both the finance and healthcare namespaces in, and the review changes of #494, the root measures 578210 B; plus 1%, rounded up to the next 100 as `bundle-size.mjs --update` does, that is 584000. Before: 570400 on `main` after SPA-47, 578900 after FIN-95, and 581300 approved for #494 alone. +- The hub text (`INDUSTRY_OVERVIEWS.healthcare.about`) and the guide intro give HL7 International's own claim for version 2, "one of the most widely implemented standards for healthcare information in the world" ([HL7 TSC product list](https://tscwiki.hl7.org/TSC_Product_List_V2)), in place of the unsourced "most of their records". Settled in review of #494 on 2026-11-10. The hub says "version two" and carries no link, because `industry-overview.test.ts` refuses a digit there and the text is plain; the guide carries the link. diff --git a/context/domination/tracker.md b/context/domination/tracker.md index 87cdad2a2..49dd62f69 100644 --- a/context/domination/tracker.md +++ b/context/domination/tracker.md @@ -117,8 +117,8 @@ ending with lengths of time counted from now, ahead of the remaining realms. | 42 | SPA-47 | Space | `toTT` + `toTCG` | — | #228 | — | Done | | 43 | SPA-49 | Space | Two-part Julian Date + MJD + J2000 | — | #230 | — | Not started | | 44 | SPA-52 | Space | CCSDS ASCII time codes A and B | — | #233 | Cut | Not started | -| 45 | HLTH-93 | Healthcare | HL7 v2 timestamps: `parseHL7`,
`formatHL7`, `isValidHL7` | — | #401 | — | Not started | -| 46 | HLTH-94 | Healthcare | FHIR datetimes: `parseFHIR`, `formatFHIR`,
`isValidFHIR`, three FHIR regexes | HLTH-93 | #402 | — | Not started | +| 45 | HLTH-93 | Healthcare | HL7 v2 timestamps: `parseHL7`,
`formatHL7`, `isValidHL7` | — | #401 | — | Done | +| 46 | HLTH-94 | Healthcare | FHIR datetimes: `parseFHIR`, `formatFHIR`,
`isValidFHIR`, three FHIR regexes | — | #402 | — | Not started | | 47 | FIN-95 | Finance | FIX UTC timestamps: parse, format and
`isValidFixUtcTimestamp` | — | #403 | — | Done | | 48 | FIN-96 | Finance | SWIFT dates: `parseSwiftDate`,
`formatSwiftDate`, `isValidSwiftDate` | — | #404 | — | Not started | | 49 | AV-97 | Aviation | SSIM dates: `parseSsimDate`,
`formatSsimDate`, `isValidSsimDate` | — | #405 | — | Not started | diff --git a/context/dox/built.md b/context/dox/built.md index efc29910d..b55760d8a 100644 --- a/context/dox/built.md +++ b/context/dox/built.md @@ -1627,6 +1627,41 @@ Shared hooks come first, then the globe, then the clock-change pages. - **Every zone is read with `disambiguation: "reject"`**, stated beside the result and in the printed call, because any other policy picks an instant for a repeated or skipped time. `classifyLocal` supplies the reason for a refused one. + The HL7 Timestamp Reader (HLTH-93, `/tools/hl7-timestamp-reader/`) is a third member of the + family, for the healthcare layer. It reads one HL7 v2 `DTM` or `TS` field with `parseHL7` + (`lib/hl7-timestamp-reader.ts` is the pure module, `hl7-timestamp-reader-mount.ts` the template + and mount, `hl7-lib.ts` the loader) and states which of four kinds it is: an instant, a local + time with no offset (the sender's time, not UTC), a partial value that names a span and no + instant, or the null value. A local value goes through the same four-zone strip, with a third + column that sets each instant against the same digits read as UTC ("5 h 30 min later"), and a + fourth section writes the value back with `formatHL7` at seven precisions. Its rules: + - **The timeline takes an optional `reference` mark.** A spec with a `reference` draws a pin + and a label for a value that is not an instant of its own (the digits read as UTC). The + DTM Decoder and X12 Time Reader pass none, and their snapshots are unchanged. + - **`edi-widgets.ts` narrows with `Pick`.** `resolveReason`, `resolveInZone` and + `widestGap` ask for the functions they call and no more, so the Reader's `Hl7Lib` satisfies + them without carrying the EDI functions. The duration reader keeps a fraction of an hour. + - **A preset-only permalink.** While the state matches a preset the link is `{ preset }` + alone, and the zod `value` of the chat tool stays required (the Leap Day precedent). + Otherwise the link carries the untrimmed value and the trimmed zones. + - **The ladder never rounds.** `formatHL7` only lowers the precision; a finer one is `no result` + in the cell, which is a correct answer and not the sentinel. + - **Picture widths are read off `formatHL7`.** The width of the group for precision p is the + characters `formatHL7(local, { precision: p })` adds to the rung before it. Digits sent past the + precision are one dashed box, "cut by the degree, not read". The offset and the `^degree` are + their own boxes. What `parseHL7` ignores (ch. 2 §2.6.2), the subcomponents after a component's + first `&` and every component after the second, is a dashed box of its own, "ignored, not + read", after the part it follows. + - **The UTC reading is a library call.** `resolveLocal(local, "UTC", reject)` gives the reading, + and `diffUtcAsDuration` gives "5 h 30 min later". Both are printed in the calls. + - **The ladder's columns.** Seven rows, year to fraction, with "As sent" and a third column, + "With offset" or "In UTC (+0000)". Each cell reserves 24ch in tabular figures, and a value + never wraps above 36rem. The note prints the calls once. + - **The writer's second column** uses zone 1's offset for a value with no offset and `+0000` + for one with an offset. A partial value with an offset makes no `formatHL7` call, and one + sentence says why. The call is printed once, in the caption, with `{ precision }` as the row. + - **The NO SIGNAL reason** comes from probing `parseHL7` on the first component, cut at its + first `&`: when that reads, the degree's reason; when it does not, the picture's. The starter zone is `Asia/Kolkata`, and the permalink never trims the value. - **The site holds no table of codes.** Whether the library reads a code, and its kind, come from the classifier, and a code's layout comes from what its kind's formatter writes, so the widgets cannot drift from the library's code table. The one list of codes is `TWO_DIGIT_YEAR_CODES` @@ -2790,7 +2825,7 @@ Shared hooks come first, then the globe, then the clock-change pages. `/tools/timetable-reader/`, `/tools/crossing-clock/`, `/tools/cutoff-stack/`, `/tools/cutoff-ruler/`, `/tools/cutoff-countdown/`, `/tools/punctuality-board/`, `/tools/eta-drift/`, `/tools/departure-board/`, `/tools/dtm-decoder/`, - `/tools/x12-time-reader/`, `/tools/bl-date-stamp/`, `/tools/demurrage-clock/`, + `/tools/x12-time-reader/`, `/tools/hl7-timestamp-reader/`, `/tools/bl-date-stamp/`, `/tools/demurrage-clock/`, `/tools/epcis-event-reader/`, `/tools/journey-split/`, `/tools/gnss-week-decoder/`, `/tools/satellite-clock-converter/`, `/tools/gnss-rollover-checker/`, `/tools/leap-second-timeline/`, `/tools/elapsed-vs-clock-difference/`, `/tools/stored-time-audit/`, @@ -4204,6 +4239,9 @@ Shared hooks come first, then the globe, then the clock-change pages. pair. A zone is passed only when the reader named it, never chosen from the time code. Both schemas check a code's shape only (`ediCodeSchema`): a code the library does not read is the widget's sentinel to show, not a failed tool call. + - `showHl7TimestampReader({ value, zone1?, zone2?, zone3?, zone4? })` (HLTH-93): `value` is + one HL7 v2 `DTM` or `TS` field as typed, up to 64 characters, never trimmed. A zone is passed + only when the reader named it, never chosen from a facility or a sending system. - `showBlDateStamp({ value, event, timeZone, zone2?, zone3?, zone4?, latest? })` (INT-14): `value` is a moment, never a bare local time, and `timeZone` is the place where the event happened. A zone is passed only when the reader named it, never chosen from a port or a place. @@ -4294,7 +4332,7 @@ Shared hooks come first, then the globe, then the clock-change pages. - **Example cards open their widget on the click.** The `CHAT_STARTERS` live in the widget rail, not the empty chat, as a scrolling panel of bevelled cards (`ExamplesPanel.tsx`) grouped by area. The areas are industries: `EXAMPLE_AREAS` is Core, Transport, Intermodal, - GNSS and Finance, each heading carries its industry's icon (`INDUSTRY_ICON_PATHS` through `industryTag`), + GNSS, Finance and Healthcare, each heading carries its industry's icon (`INDUSTRY_ICON_PATHS` through `industryTag`), and a card's `area` is its tool page's tag. An industry with no tool has no area (Workforce and Maritime gain one with their first tool). `startersByArea()` returns the groups in that order. `chat-starters.test.ts` asserts each area is an industry with that industry's label and icon, diff --git a/packages/gmt/README.md b/packages/gmt/README.md index c0225bd95..f0e10e6fd 100644 --- a/packages/gmt/README.md +++ b/packages/gmt/README.md @@ -53,7 +53,7 @@ addZoned("2024-03-30T12:00:00+01:00[Europe/Berlin]", { hours: 24 }); // "2024-03 resolveLocal("2024-03-31T02:30:00", "Europe/Berlin", { disambiguation: "reject" }); // "" ``` -- **745 functions, to the nanosecond**, tested in 17 locales. +- **748 functions, to the nanosecond**, tested in 17 locales. - **Never throws.** ISO 8601 strings in. Invalid input returns `""`, `null`, `false` or `[]`. The latest test counts, CI volume and the comparison with Luxon, date-fns, Moment.js, Day.js, Spacetime and `@internationalized/date` are on the [Why GMT](https://northguild.dev/gmt/why-gmt/) page. The full comparison and the method are on the [compare](https://northguild.dev/gmt/compare/) page. @@ -79,9 +79,9 @@ convertUtcToZoned("2024-06-15T12:00:00Z", "Asia/Tokyo"); // "2024-06-15T21:00:00 ``` Every function has a reference page with a live playground: -[plain](https://northguild.dev/gmt/reference/plain/) · [zoned](https://northguild.dev/gmt/reference/zoned/) · [utc](https://northguild.dev/gmt/reference/utc/) · [unix](https://northguild.dev/gmt/reference/unix/) · [instant](https://northguild.dev/gmt/reference/instant/) · [calendar](https://northguild.dev/gmt/reference/calendar/) · [duration](https://northguild.dev/gmt/reference/duration/) · [interval](https://northguild.dev/gmt/reference/interval/) · [workforce](https://northguild.dev/gmt/reference/workforce/) · [span](https://northguild.dev/gmt/reference/span/) · [precision](https://northguild.dev/gmt/reference/precision/) · [recurrence](https://northguild.dev/gmt/reference/recurrence/) · [timescale](https://northguild.dev/gmt/reference/timescale/) · [gnss](https://northguild.dev/gmt/reference/gnss/) · [transport](https://northguild.dev/gmt/reference/transport/) · [intermodal](https://northguild.dev/gmt/reference/intermodal/) · [finance](https://northguild.dev/gmt/reference/finance/) +[plain](https://northguild.dev/gmt/reference/plain/) · [zoned](https://northguild.dev/gmt/reference/zoned/) · [utc](https://northguild.dev/gmt/reference/utc/) · [unix](https://northguild.dev/gmt/reference/unix/) · [instant](https://northguild.dev/gmt/reference/instant/) · [calendar](https://northguild.dev/gmt/reference/calendar/) · [duration](https://northguild.dev/gmt/reference/duration/) · [interval](https://northguild.dev/gmt/reference/interval/) · [workforce](https://northguild.dev/gmt/reference/workforce/) · [span](https://northguild.dev/gmt/reference/span/) · [precision](https://northguild.dev/gmt/reference/precision/) · [recurrence](https://northguild.dev/gmt/reference/recurrence/) · [timescale](https://northguild.dev/gmt/reference/timescale/) · [gnss](https://northguild.dev/gmt/reference/gnss/) · [transport](https://northguild.dev/gmt/reference/transport/) · [intermodal](https://northguild.dev/gmt/reference/intermodal/) · [finance](https://northguild.dev/gmt/reference/finance/) · [healthcare](https://northguild.dev/gmt/reference/healthcare/) -By industry: [Workforce](https://northguild.dev/gmt/industries/workforce/) · [Transport](https://northguild.dev/gmt/industries/transport/) · [Intermodal](https://northguild.dev/gmt/industries/intermodal/) · [GNSS](https://northguild.dev/gmt/industries/gnss/) · [Maritime](https://northguild.dev/gmt/industries/maritime/) · [Finance](https://northguild.dev/gmt/industries/finance/) +By industry: [Workforce](https://northguild.dev/gmt/industries/workforce/) · [Transport](https://northguild.dev/gmt/industries/transport/) · [Intermodal](https://northguild.dev/gmt/industries/intermodal/) · [GNSS](https://northguild.dev/gmt/industries/gnss/) · [Maritime](https://northguild.dev/gmt/industries/maritime/) · [Finance](https://northguild.dev/gmt/industries/finance/) · [Healthcare](https://northguild.dev/gmt/industries/healthcare/) Then the [guides](https://northguild.dev/gmt/guides/) show how to do each job, and the [tools](https://northguild.dev/gmt/tools/) let you try it on your own values. diff --git a/packages/gmt/package.json b/packages/gmt/package.json index aba696176..c7012ac77 100644 --- a/packages/gmt/package.json +++ b/packages/gmt/package.json @@ -117,6 +117,18 @@ "gnss/convert": [ "./dist/gnss/convert/index.d.ts" ], + "healthcare": [ + "./dist/healthcare/index.d.ts" + ], + "healthcare/format": [ + "./dist/healthcare/format/index.d.ts" + ], + "healthcare/parse": [ + "./dist/healthcare/parse/index.d.ts" + ], + "healthcare/validate": [ + "./dist/healthcare/validate/index.d.ts" + ], "instant": [ "./dist/instant/index.d.ts" ], @@ -446,6 +458,22 @@ "types": "./dist/gnss/convert/index.d.ts", "default": "./dist/gnss/convert/index.js" }, + "./healthcare": { + "types": "./dist/healthcare/index.d.ts", + "default": "./dist/healthcare/index.js" + }, + "./healthcare/format": { + "types": "./dist/healthcare/format/index.d.ts", + "default": "./dist/healthcare/format/index.js" + }, + "./healthcare/parse": { + "types": "./dist/healthcare/parse/index.d.ts", + "default": "./dist/healthcare/parse/index.js" + }, + "./healthcare/validate": { + "types": "./dist/healthcare/validate/index.d.ts", + "default": "./dist/healthcare/validate/index.js" + }, "./instant": { "types": "./dist/instant/index.d.ts", "default": "./dist/instant/index.js" diff --git a/packages/gmt/skills/_artifacts/domain_map.yaml b/packages/gmt/skills/_artifacts/domain_map.yaml index 777624ce5..dab52721c 100644 --- a/packages/gmt/skills/_artifacts/domain_map.yaml +++ b/packages/gmt/skills/_artifacts/domain_map.yaml @@ -27,7 +27,7 @@ domains: description: Integrating gmt with application frameworks and linting tools - name: Industry Layers slug: industry-layers - description: One skill per industry layer (gnss/, finance/, transport/, intermodal/, workforce/) drawing on the core skills; core namespaces such as timescale/ stay in the core skills + description: One skill per industry layer (gnss/, finance/, transport/, intermodal/, workforce/, healthcare/) drawing on the core skills; core namespaces such as timescale/ stay in the core skills - name: Contributor slug: contributor description: Library maintainer workflows — issues, PRs, implementation, testing @@ -595,6 +595,23 @@ skills: - Find the operator-designated day an instant falls in, from a start time in a reference zone - Total time in a set of statuses, the longest unbroken stretch, and the rests or paired rests that qualify + - name: GMT Healthcare + slug: gmt-healthcare + domain: industry-layers + description: HL7 v2 date-times, @northguild/gmt/healthcare (parseHL7/formatHL7/isValidHL7); an HL7 time with no offset is the sender's local time, never UTC + type: core + packages: + - '@northguild/gmt' + covers: + - parseHL7 + - formatHL7 + - isValidHL7 + tasks: + - Read an HL7 v2 DTM or TS as an instant, a local time with no offset, a partial value or the null value + - Take the instant of an HL7 time that carries no offset, once the sender's zone is known + - Write an ISO 8601 value as an HL7 DTM at the precision the caller names + - Check an HL7 v2 date-time before storing it + - name: Issue Creation slug: issue-creation domain: contributor @@ -701,6 +718,9 @@ cross_references: - from: gmt-arithmetic to: gmt-workforce reason: Hours-of-work rules are built on interval and duration arithmetic + - from: gmt-timezone + to: gmt-healthcare + reason: An HL7 time with no offset becomes an instant through resolveLocal and the sender's zone - from: issue-creation to: new-method-implementation reason: Issue is first step; implementation skill guides actual code diff --git a/packages/gmt/skills/_artifacts/skill_spec.md b/packages/gmt/skills/_artifacts/skill_spec.md index 9fc19b8a4..bb33102af 100644 --- a/packages/gmt/skills/_artifacts/skill_spec.md +++ b/packages/gmt/skills/_artifacts/skill_spec.md @@ -10,7 +10,7 @@ Temporal-based date and time utilities with timezone support and polyfill integr | Arithmetic | Add/subtract, durations, interval range math | gmt-arithmetic | | Zoned Date Operations | IANA timezone-aware date operations, DST disambiguation | gmt-timezone | | Integration | Application framework integration, cache keys, lint package selection | gmt-integration | -| Industry Layers | One skill per industry layer, drawing on the core skills | gmt-gnss, gmt-finance, gmt-transport, gmt-intermodal, gmt-workforce | +| Industry Layers | One skill per industry layer, drawing on the core skills | gmt-gnss, gmt-finance, gmt-transport, gmt-intermodal, gmt-workforce, gmt-healthcare | | Contributor | Library maintainer workflows — issues, PRs, implementation, testing | issue-creation, pr-contribution, new-method-implementation, unit-test-generation, api-expansion-workflow | ## Skill Inventory @@ -26,6 +26,7 @@ Temporal-based date and time utilities with timezone support and polyfill integr | gmt-transport | core | Industry Layers | transitTime, etaAtZone, dwellTime, scheduleDelivery, cutoffAt, classifyPunctuality, nextDeparture (transport/) | | | gmt-intermodal | core | Industry Layers | freeTimeExpiry, chargeableDays, demurrageClock, billingTimeline, bolTimestamp, EDI and EPCIS timestamps (intermodal/) | | | gmt-workforce | core | Industry Layers | evaluateDutyLog, dutyViolations, dutyDayFor, dutyTotals (workforce/) | | +| gmt-healthcare | core | Industry Layers | parseHL7, formatHL7, isValidHL7 (healthcare/) | | | issue-creation | lifecycle | Contributor | Feature requests, missing methods, issue templates | | | pr-contribution | lifecycle | Contributor | PR workflow, tests, contribution guidelines | | | new-method-implementation | maintainer | Contributor | Adding methods to gmt source | | @@ -55,7 +56,7 @@ consumers. Core namespaces hold general time primitives and stay in the topic skills (`timescale/` leap seconds and TAI are in `gmt-integration`). Each industry -layer (`gnss/`, `transport/`, `intermodal/`, `workforce/`) has its own consumer +layer (`gnss/`, `transport/`, `intermodal/`, `workforce/`, `healthcare/`) has its own consumer skill, and its functions are in no topic skill. A topic skill may keep a one-line cross-reference to an industry skill, and no function lists or examples of industry functions. @@ -65,7 +66,7 @@ examples of industry functions. - **Consumer skills** (shipped in the npm tarball): `skills/gmt-basics/`, `skills/gmt-arithmetic/`, `skills/gmt-timezone/`, `skills/gmt-integration/`, `skills/gmt-gnss/`, `skills/gmt-finance/`, `skills/gmt-transport/`, `skills/gmt-intermodal/`, - `skills/gmt-workforce/` + `skills/gmt-workforce/`, `skills/gmt-healthcare/` — lightweight routing pointers (~30-60 lines each) that point agents to the docs site and the JSDoc in the installed package for full API details. - **Contributor skills** (excluded from the npm tarball via `.npmignore`): @@ -73,7 +74,7 @@ examples of industry functions. ## Recommended Skill File Structure -- **Consumer skills:** gmt-basics, gmt-arithmetic, gmt-timezone, gmt-integration, gmt-gnss, gmt-finance, gmt-transport, gmt-intermodal, gmt-workforce +- **Consumer skills:** gmt-basics, gmt-arithmetic, gmt-timezone, gmt-integration, gmt-gnss, gmt-finance, gmt-transport, gmt-intermodal, gmt-workforce, gmt-healthcare - **Contributor skills:** issue-creation, pr-contribution, new-method-implementation, unit-test-generation, api-expansion-workflow ## Notes diff --git a/packages/gmt/skills/_artifacts/skill_tree.yaml b/packages/gmt/skills/_artifacts/skill_tree.yaml index 7abf4f351..bc06521e4 100644 --- a/packages/gmt/skills/_artifacts/skill_tree.yaml +++ b/packages/gmt/skills/_artifacts/skill_tree.yaml @@ -227,6 +227,20 @@ skills: - 'northguild/gmt:packages/gmt/src/workforce/index.ts' - 'northguild/gmt:packages/gmt/src/types/duty.ts' + - name: GMT Healthcare + slug: gmt-healthcare + type: core + domain: industry-layers + path: 'skills/gmt-healthcare/SKILL.md' + package: 'packages/gmt' + description: HL7 v2 date-times, @northguild/gmt/healthcare (parseHL7/formatHL7/isValidHL7); an HL7 time with no offset is the sender's local time, never UTC + requires: + - gmt-timezone + sources: + - 'northguild/gmt:apps/dox/src/content/docs/guides/industries/healthcare-clinical-timestamps.mdx' + - 'northguild/gmt:packages/gmt/src/healthcare/index.ts' + - 'northguild/gmt:packages/gmt/src/types/hl7.ts' + # Lifecycle skills (contributors only — excluded from consumer intent install) - name: Issue Creation slug: issue-creation diff --git a/packages/gmt/skills/gmt-healthcare/SKILL.md b/packages/gmt/skills/gmt-healthcare/SKILL.md new file mode 100644 index 000000000..036fb3953 --- /dev/null +++ b/packages/gmt/skills/gmt-healthcare/SKILL.md @@ -0,0 +1,87 @@ +--- +name: gmt-healthcare +description: > + HL7 v2 date-times in @northguild/gmt/healthcare — parseHL7 reads a DTM, or a + TS with its degree of precision, as an instant, a local time with no offset, + a partial value or the null value; formatHL7 writes an ISO 8601 value as a + DTM; isValidHL7 checks one. An HL7 time with no offset is the sender's local + time, never UTC. Reads the docs site (llms.txt) and the installed package's + JSDoc; a routing pointer. +sources: + - 'northguild/gmt:apps/dox/src/content/docs/guides/industries/healthcare-clinical-timestamps.mdx' + - 'northguild/gmt:packages/gmt/src/healthcare/index.ts' + - 'northguild/gmt:packages/gmt/src/types/hl7.ts' +metadata: + type: core + library: '@northguild/gmt' + library_version: '1.21.0' +--- + +# GMT Healthcare + +Use this skill when the task is reading or writing the date-time of an HL7 v2 +message: an `MSH-7`, an `OBX-14`, a `PID-7`. Resolving a local time once the +sender's zone is known is in the `gmt-timezone` skill. + +## When to load + +- The user reads an HL7 v2 `DTM` or `TS` field, or a value such as + `20240615103000-0500` or `199904011200^L`. +- The user asks why HL7 times are hours off, or whether an HL7 time is UTC. +- The user writes an ISO 8601 value into an HL7 field. +- The user checks that an HL7 time is well formed before storing it. + +## Core rules + +1. **No offset means the sender's local time, not UTC.** HL7 2.A.22: "if the + time zone is not included, the time zone defaults to that of the local time + zone of the sender". `parseHL7` returns `kind: "local"` for it, with no + `instant`. Take the instant by supplying the sender's zone to + `resolveLocal(result.local, zone)`; reading the digits as UTC moves every + event by the sender's offset. + + ```typescript + parseHL7("20240615103000-0500"); // { kind: "instant", instant: "2024-06-15T15:30:00Z", offset: "-05:00", local: "2024-06-15T10:30:00", precision: "second" } + parseHL7("20240615103000"); // { kind: "local", local: "2024-06-15T10:30:00", precision: "second" } + resolveLocal("2024-06-15T10:30:00", "Europe/Helsinki"); // "2024-06-15T07:30:00Z" + ``` + +2. **Four kinds, and the digits sent are the precision.** `"instant"` (an offset + and a minute or finer), `"local"` (no offset, a minute or finer), `"partial"` + (a year, month, day or hour: a span, with no instant even when it carries an + offset) and `"null"` (the HL7 null value `""`, two double quotes, which is not + the empty string). `precision` says which digits were sent. +3. **A `TS` degree of precision only lowers the precision.** `199904011200^L` is + April 1999, not 12:00. A degree finer than the digits sent, or not one of + `Y L D H M S`, returns `null`. `^` separates the components and `&` the + subcomponents (ch. 2 §2.5.4); a feed whose MSH-2 names others re-joins the + field first. What is present but not expected is ignored (§2.6.2), so + `20240615^D^X` reads as `20240615^D` and `2024&X` as `2024`. An empty + component is not present: `20240615^D^` is `20240615^D`, `'""^'` the null + value, and `^D` and `&X` return `null`. +4. **`formatHL7` writes a `DTM`, never a `TS`, and never rounds.** It reads the + precision from the form of the input and `{ precision }` only lowers it; a + fraction is cut to four digits. An instant with `Z` writes `+0000`. A local + value writes no offset. +5. **Sentinels, never throws.** `parseHL7` returns `null`, `formatHL7` returns + `""`, `isValidHL7` returns `false`, for any input of any type. `isValidHL7` is + `parseHL7(value) !== null`; `'""'` is valid. +6. **Read the docs site.** This skill is a routing pointer. The map of the docs + is `https://northguild.dev/gmt/llms.txt`, and each page has a `.md` twin that + holds its text. The JSDoc ships in the installed package: + `node_modules/@northguild/gmt/dist/**/*.d.ts`. + +## Key functions + +- **Read and write**: `parseHL7`, `formatHL7` +- **Check**: `isValidHL7` +- **Types**: `Hl7DateTime`, `Hl7Precision`, `Hl7PartialPrecision`, + `Hl7MomentPrecision`, `Hl7FormatOptions` + +## References + +- [healthcare reference](https://northguild.dev/gmt/reference/healthcare/) +- [Healthcare: Clinical Timestamps guide](https://northguild.dev/gmt/guides/industries/healthcare-clinical-timestamps/) +- [HL7 Timestamp Reader](https://northguild.dev/gmt/tools/hl7-timestamp-reader/) +- [Docs map for agents (llms.txt)](https://northguild.dev/gmt/llms.txt) +- [GMT Timezone skill](../gmt-timezone/SKILL.md) diff --git a/packages/gmt/src/healthcare/README.md b/packages/gmt/src/healthcare/README.md new file mode 100644 index 000000000..226fba4c1 --- /dev/null +++ b/packages/gmt/src/healthcare/README.md @@ -0,0 +1,3 @@ +# Healthcare API + +See the full reference at [/reference/healthcare](/reference/healthcare). diff --git a/packages/gmt/src/healthcare/format/formatHL7.test.ts b/packages/gmt/src/healthcare/format/formatHL7.test.ts new file mode 100644 index 000000000..dfac0008c --- /dev/null +++ b/packages/gmt/src/healthcare/format/formatHL7.test.ts @@ -0,0 +1,340 @@ +import { fromOffsetInstant, toOffsetInstant } from "../../instant/convert"; +import { revokedProxy } from "../../test/hostileValues"; +import { NON_STRINGS } from "../../test/nonStrings"; +import type { Hl7FormatOptions } from "../../types"; +import { parseHL7 } from "../parse/parseHL7"; +import { formatHL7 } from "./formatHL7"; + +// Every expected value is decided from HL7 v2.5.1 2.A.22 (digit count is the precision; the +// offset is `±ZZZZ`) and the GMT rules "cut, never round" and "precision only lowers". +const WRITTEN = [ + { + input: "2024-06-15T10:30:00-05:00", + expected: "20240615103000-0500", + }, + { input: "2024-06-15T15:30:00Z", expected: "20240615153000+0000" }, + { input: "2024-06-15T10:30:00", expected: "20240615103000" }, + { input: "2024-06-15T10:30", expected: "202406151030" }, + { + input: "2024-06-15T10:30:45.98765-05:00", + expected: "20240615103045.9876-0500", + }, + { input: "2024-06-15T10:30:00.1000", expected: "20240615103000.1000" }, + { input: "2024-06-15T10:30:00,5", expected: "20240615103000.5" }, + { input: "2024", expected: "2024" }, + { input: "2024-06", expected: "202406" }, + { input: "2024-06-15", expected: "20240615" }, + { input: "2024-06-15T10", expected: "2024061510" }, + { input: "0000-01-01", expected: "00000101" }, + { + input: "2024-06-15T10:30:00+05:30[Asia/Kolkata]", + expected: "20240615103000+0530", + }, + { + input: "2024-06-15T10:30:00+23:00", + expected: "20240615103000+2300", + }, + { + // UTC year 10000, wall clock 9999 + input: "9999-12-31T23:59:59-14:00", + expected: "99991231235959-1400", + }, + // 2.A.22 `±ZZZZ`: the value's own offset, whole minutes, never `-0000` + { input: "2024-06-15T10:30:00+00:00", expected: "20240615103000+0000" }, + { input: "2024-06-15T10:30:00-00:00", expected: "20240615103000+0000" }, + { input: "2024-06-15T10:30:00+05:45", expected: "20240615103000+0545" }, + { input: "2024-06-15T10:30:00-14:00", expected: "20240615103000-1400" }, + { input: "2024-06-15T10:30:00+14:00", expected: "20240615103000+1400" }, + // Z names an exact instant; a zone annotation shows it on that zone's clock (EEST, +03:00) + { + input: "2024-06-15T10:30:00Z[Europe/Helsinki]", + expected: "20240615133000+0300", + }, + { input: "2024-06-15T10:30:00Z[UTC]", expected: "20240615103000+0000" }, + { input: "2024-06-15T10:30:00+00:00:00", expected: "20240615103000+0000" }, + // 2.A.22 `YYYY`: years 0000 and 9999 are the ends + { input: "0000-01-01T00:00:00Z", expected: "00000101000000+0000" }, + { input: "0000-01-01T00:00:00+01:00", expected: "00000101000000+0100" }, + { input: "9999", expected: "9999" }, + { input: "9999-12-31T23:59:59.9999", expected: "99991231235959.9999" }, + // 2.A.22 `[.S[S[S[S]]]]`: as many digits as written, at most four + { input: "2024-06-15T10:30:00.0", expected: "20240615103000.0" }, + { input: "2024-06-15T10:30:00.123Z", expected: "20240615103000.123+0000" }, + { + input: "2024-06-15T10:30:00.000000000Z", + expected: "20240615103000.0000+0000", + }, + { + input: "2024-06-15T10:30:00.123456789+05:45", + expected: "20240615103000.1234+0545", + }, + { + input: fromOffsetInstant({ + instant: "2024-06-15T15:30:00Z", + offset: "-05:00", + timeZone: "America/Chicago", + }), + expected: "20240615103000-0500", + }, +] as const; + +const LOWERED: { + input: string; + precision: Hl7FormatOptions["precision"]; + expected: string; +}[] = [ + { + input: "2024-06-15T10:30:45.98765-05:00", + precision: "minute", + expected: "202406151030-0500", + }, + { + input: "2024-06-15T10:30:45.98765-05:00", + precision: "day", + expected: "20240615-0500", + }, + { + input: "2024-06-15T10:30:45.98765-05:00", + precision: "year", + expected: "2024-0500", + }, + { + input: "2024-06-15T10:30:59.999999999", + precision: "minute", + expected: "202406151030", + }, + { + input: "2024-06-15T23:59:59.9Z", + precision: "second", + expected: "20240615235959+0000", + }, + { + input: "2024-06-15T10:30:00-05:00", + precision: "hour", + expected: "2024061510-0500", + }, + { + input: "2024-06-15T10:30:00", + precision: "minute", + expected: "202406151030", + }, + { + input: "2024-06-15T10:30:45.123456789Z", + precision: "fraction", + expected: "20240615103045.1234+0000", + }, + { input: "2024-06-15", precision: "day", expected: "20240615" }, + { input: "2024-06-15", precision: "month", expected: "202406" }, + { input: "2024-06-15T10", precision: "hour", expected: "2024061510" }, + // a cut that rounding would carry across a boundary + { + input: "2024-12-31T23:59:59.999999999Z", + precision: "day", + expected: "20241231+0000", + }, + { + input: "2024-12-31T23:59:59.999999999", + precision: "year", + expected: "2024", + }, + { + input: "2024-12-31T23:59:59.999999999", + precision: "hour", + expected: "2024123123", + }, + { + input: "2024-12-31T23:59:59.999999999+05:45", + precision: "second", + expected: "20241231235959+0545", + }, + { + input: "2024-06-15T10:30:00.5", + precision: "fraction", + expected: "20240615103000.5", + }, + { + input: "2024-06-15T10:30:45.98765", + precision: "second", + expected: "20240615103045", + }, + { + input: "2024-06-15T10:30:00-05:00", + precision: "minute", + expected: "202406151030-0500", + }, + { + input: "2024-06-15T10:30:00+05:45", + precision: "month", + expected: "202406+0545", + }, +]; + +const REFUSED: { + input: string; + precision?: Hl7FormatOptions["precision"]; + why: string; +}[] = [ + { input: "2024-06", precision: "day", why: "finer than the value carries" }, + { + input: "2024-06-15T15:30:00Z", + precision: "fraction", + why: "no fraction to write", + }, + { + input: "2024-06-15T10:30", + precision: "second", + why: "minute value has no seconds", + }, + { input: "1900-01-01T11:34:39-00:25:21", why: "offset with seconds" }, + { + input: "1900-01-01T11:34:39-00:25:21[Europe/Dublin]", + why: "Dublin Mean Time offset", + }, + { input: "+010000-01-01", why: "expanded year" }, + { input: "-000001-01-01T00:00:00Z", why: "negative year" }, + { input: "2024-06-15-05:00", why: "day with an offset" }, + { input: "2024-06-15T10-05:00", why: "hour with an offset" }, + { input: "2024-06Z", why: "month with an offset" }, + { input: "2024-06-15T10:30:00[Europe/Helsinki]", why: "zone with no offset" }, + { input: "2024-06-15[u-ca=iso8601]", why: "annotated date" }, + { input: "2024-06-15T10:30:60", why: "second 60" }, + { input: "2024-06-15T24:00:00", why: "hour 24" }, + { input: "2024-02-30", why: "no such day" }, + { input: "2024-13", why: "no such month" }, + { + input: "2024-06-15T10:30:00+05:30[Europe/Helsinki]", + why: "zone disagrees with offset", + }, + { input: "2023-02-29T10", why: "no such day, hour form" }, + { input: "20240615103000", why: "already basic form" }, + { input: "2024-06-15t10:30:00", why: "lower-case t" }, + { input: "2024-06-15T10:30:00z", why: "lower-case z" }, + { input: "2024-06-15 10:30", why: "space separator" }, + { input: "", why: "empty string" }, + { input: "2024", precision: "minute", why: "year value, finer precision" }, + { input: "2024-06-15", precision: "hour", why: "day value, finer precision" }, + { input: "2024-06-15T10", precision: "minute", why: "hour value, minute" }, + { + input: "2024-06-15T10:30:00", + precision: "fraction", + why: "local second, no fraction", + }, + { input: "2024-06-15T10:30:00+05:30:30", why: "offset with seconds" }, + { input: "2024-06-15T10:30:00[u-ca=iso8601]", why: "local, annotated" }, + { input: "2024-06-15T10:30:00+24:00", why: "offset hours 24" }, + { input: "10000-01-01", why: "five-digit year" }, +]; + +const BAD_OPTIONS: { label: string; options: unknown }[] = [ + { label: "null", options: null }, + { label: "5", options: 5 }, + { label: "'minute'", options: "minute" }, + { label: "{ precision: 'Minute' }", options: { precision: "Minute" } }, + { label: "{ precision: 'week' }", options: { precision: "week" } }, + { label: "{ precision: null }", options: { precision: null } }, + { label: "{ precision: '' }", options: { precision: "" } }, + { + label: "a throwing getter", + options: { + get precision(): never { + throw new TypeError("hostile getter"); + }, + }, + }, + { label: "a revoked proxy", options: revokedProxy() }, +]; + +describe("formatHL7", () => { + it.each(WRITTEN)("writes '$input' as '$expected'", ({ input, expected }) => { + expect(formatHL7(input)).toBe(expected); + }); + + it.each(LOWERED)( + "writes '$input' lowered to $precision as '$expected', cut and never rounded", + ({ input, precision, expected }) => { + expect(formatHL7(input, { precision })).toBe(expected); + }, + ); + + it.each(REFUSED)("returns '' for '$input' ($why)", ({ input, precision }) => { + expect( + formatHL7(input, precision === undefined ? undefined : { precision }), + ).toBe(""); + }); + + it("accepts an empty options object", () => { + expect(formatHL7("2024-06-15", {})).toBe("20240615"); + }); + + it("reads an array, a function and an unknown key as options with no precision", () => { + expect(formatHL7("2024-06-15T10:30:00Z", [] as Hl7FormatOptions)).toBe( + "20240615103000+0000", + ); + expect( + formatHL7("2024-06-15T10:30:00Z", (() => 0) as Hl7FormatOptions), + ).toBe("20240615103000+0000"); + expect( + formatHL7("2024-06-15T10:30:00Z", { other: 1 } as Hl7FormatOptions), + ).toBe("20240615103000+0000"); + }); + + it("accepts options with precision undefined", () => { + expect(formatHL7("2024-06-15", { precision: undefined })).toBe("20240615"); + }); + + it.each(BAD_OPTIONS)("returns '' for the options $label", ({ options }) => { + expect(formatHL7("2024-06-15T10:30:00Z", options as Hl7FormatOptions)).toBe( + "", + ); + }); + + it.each(NON_STRINGS.map(([label, make]) => ({ label, make })))( + "returns '' without throwing for $label", + ({ make }) => { + expect(formatHL7(make() as string)).toBe(""); + }, + ); + + describe("round trip through parseHL7 (index correction 2)", () => { + it.each( + [ + "2024-06-15T10:30:00-05:00", + "2024-06-15T15:30:00Z", + "2024-06-15T10:30:45.1234-05:00", + "2024-06-15T10:30:45.1-05:00", + "2024-06-15T10:30:00+05:30[Asia/Kolkata]", + "9999-12-31T23:59:59-14:00", + "2024-06-15T10:30:00+05:45", + "2024-06-15T10:30:00+14:00", + "2024-06-15T10:30:00.1234Z", + "2024-06-15T10:30:00-00:00", + ].map((iso) => ({ iso })), + )("reads '$iso' back as the same instant and offset", ({ iso }) => { + const pair = toOffsetInstant(iso); + const back = parseHL7(formatHL7(iso)); + expect(back).toMatchObject({ + kind: "instant", + instant: pair?.instant, + offset: pair?.offset, + }); + }); + + it("returns the cut instant for a five-digit fraction", () => { + expect( + parseHL7(formatHL7("2024-06-15T10:30:45.98765-05:00")), + ).toMatchObject({ + instant: "2024-06-15T15:30:45.9876Z", + offset: "-05:00", + }); + }); + + it("writes a minute-precision local back only with its parsed precision", () => { + const parsed = parseHL7("202406151030"); + expect(parsed).not.toBeNull(); + const local = (parsed as { local: string }).local; + const precision = (parsed as { precision: "minute" }).precision; + expect(formatHL7(local, { precision })).toBe("202406151030"); + expect(formatHL7(local)).toBe("20240615103000"); + }); + }); +}); diff --git a/packages/gmt/src/healthcare/format/formatHL7.ts b/packages/gmt/src/healthcare/format/formatHL7.ts new file mode 100644 index 000000000..19d81e6d0 --- /dev/null +++ b/packages/gmt/src/healthcare/format/formatHL7.ts @@ -0,0 +1,272 @@ +import { + hl7PrecisionRank, + isoHl7Form, + isoHl7Precision, + isoStringBody, + isOptionsArgument, + parseUtcOffsetNanoseconds, +} from "../../internal"; +import { Temporal } from "../../internal/temporal"; +import { toOffsetInstant } from "../../instant/convert/toOffsetInstant"; +import { isValidDate } from "../../plain/validate/isValidDate"; +import { isValidDateTime } from "../../plain/validate/isValidDateTime"; +import type { Hl7FormatOptions, Hl7Precision } from "../../types"; + +const NANOSECONDS_PER_MINUTE = 60_000_000_000n; +const NANOSECONDS_PER_HOUR = 3_600_000_000_000n; + +// 2.A.22 picture `YYYY…`: four digits and no sign. +const MIN_FOUR_DIGIT_YEAR = 0; +const MAX_FOUR_DIGIT_YEAR = 9999; + +// 2.A.22 picture `[.S[S[S[S]]]]`: a fraction of one to four digits. +const MAX_FRACTION_DIGITS = 4; + +const RANK_MINUTE = hl7PrecisionRank("minute"); + +/** + * Write an ISO 8601 string as an HL7 v2 date-time (`DTM`): the inverse of `parseHL7`. + * + * HL7 v2.5.1 2.A.22 (headed 2.A.1.22 in the hl7.eu v2.5.1 copy) defines the `DTM` + * `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]` and says "the number of characters populated + * (excluding the time zone specification) specifies the precision". + * + * | Input form | Written precision | Example result | + * | --- | --- | --- | + * | `2024` | year | `2024` | + * | `2024-06` | month | `202406` | + * | `2024-06-15` | day | `20240615` | + * | `2024-06-15T10` | hour | `2024061510` | + * | `2024-06-15T10:30` / `…:00` / `…:00.f` | minute / second / fraction | `202406151030` / `20240615103000` / `20240615103000.f` | + * | the same with `Z` or `±HH:MM`, with or without a bracketed zone | as written, then `±HHMM` | `20240615103000-0500` | + * + * - The precision is read from the form the input is written in; `options.precision` only lowers + * it, and a finer one returns `""`. A value is cut to its precision and never rounded, so the + * result never names a later minute, hour or day than the input. A fraction is cut to four + * digits, the most 2.A.22 allows. + * - It never writes `TS`: v2.6 2.A.77 says it was "withdrawn and removed from the standard as of + * v 2.6", so the result never holds `^`. + * - A value with no offset writes none, and the HL7 value then means the sender's local time + * (2.A.22: "if the time zone is not included, the time zone defaults to that of the local time + * zone of the sender"). To send a facility's wall clock with its offset, pass the string + * `fromOffsetInstant` writes for that zone. + * - The offset written is `toOffsetInstant`'s: the one written, or the zone's when a zone + * annotation follows `Z` (`…Z[Europe/Helsinki]` writes `+0300`); `Z` alone writes `+0000`. It is + * never dropped and never rounded: an offset that is not a whole number of minutes returns `""`. + * - `Z` and `-00:00` (RFC 9557 §2.2: UTC known, local offset unknown) write `+0000`; HL7 has no + * spelling for an unknown offset (2.A.22: "+0000 or -0000 both represent UTC"). + * - A date with an offset is not ISO 8601, and an hour with one is refused, as `isValidInstant` + * refuses it; both return `""`. To write a partial value with its offset, pass the instant with + * `precision`: + * `formatHL7("2024-06-15T10:30:00-05:00", { precision: "day" })` is `20240615-0500`. + * - Disambiguation: none. The function never converts a wall time without an offset to an + * instant, and a zone annotation with no offset (`2024-06-15T10:30:00[Europe/Helsinki]`) + * returns `""`: resolve it first with `resolveLocal` or `toOffsetInstant(value, zone)`. + * - Annotations: on a form with no offset, any bracketed annotation returns `""` + * (`2024-06-15[u-ca=iso8601]`, `…T10:30:00[foo=bar]`). On a form with an offset, `[u-ca=…]`, + * `[!u-ca=…]` and an unknown non-critical key are ignored and the ISO digits are written, while + * a critical unknown key (`[!foo=bar]`) returns `""`. + * - A minute-precision `local` from `parseHL7` reads back with `:00` seconds; to write the same + * digits, pass `{ precision: result.precision }`. + * - A year outside 0000–9999 returns `""`. + * - Never throws: any failure, for input of any type, is `""`. + * + * @param value ISO 8601 date, date-time, or date-time with an offset + * @param options How much of the value is written + * @returns the `DTM`, or `""` when the value cannot be written + * + * @example formatHL7("2024-06-15T10:30:00-05:00") // "20240615103000-0500" + * @example formatHL7("2024-06-15T15:30:00Z") // "20240615153000+0000" + * @example formatHL7("2024-06-15T10:30:00") // "20240615103000" (the sender's local time) + * @example formatHL7("2024-06-15T10:30:45.98765-05:00") // "20240615103045.9876-0500" (cut, not rounded) + * @example formatHL7("2024-06-15T10:30:45.98765-05:00", { precision: "day" }) // "20240615-0500" + * @example formatHL7("2024-06", { precision: "day" }) // "" (finer than the value carries) + * @example formatHL7("2024-06-15-05:00") // "" (not ISO 8601) + * @example formatHL7("2024-06-15T10:30:00[Europe/Helsinki]") // "" (a zone with no offset) + * @example formatHL7("2024-02-30") // "" (no such day) + */ +export function formatHL7(value: string, options?: Hl7FormatOptions): string { + try { + if (typeof value !== "string" || !isOptionsArgument(options)) { + return ""; + } + const match = isoHl7Form.exec(isoStringBody(value)); + const form = match === null ? null : planForm(value, match, options); + if (match === null || form === null) { + return ""; + } + const { target, written, fractionDigits, hasOffset } = form; + const read = hasOffset + ? readOffsetForm(value) + : readLocalForm(value, match, written); + if (read === null) { + return ""; + } + const { wallClock, offset } = read; + if ( + wallClock.year < MIN_FOUR_DIGIT_YEAR || + wallClock.year > MAX_FOUR_DIGIT_YEAR + ) { + return ""; + } + const offsetText = offset === null ? "" : writeOffset(offset); + if (offsetText === null) { + return ""; + } + return writeDigits(wallClock, target, fractionDigits) + offsetText; + } catch { + // Never throws (Core Rule 3) + return ""; + } +} + +interface FormPlan { + readonly target: Hl7Precision; + readonly written: Hl7Precision; + readonly fractionDigits: number; + readonly hasOffset: boolean; +} + +/** The precisions of a form and the checks that need no Temporal; null when the form is refused. */ +function planForm( + value: string, + match: RegExpExecArray, + options: Hl7FormatOptions | undefined, +): FormPlan | null { + const requested = options?.precision; + if (requested !== undefined && hl7PrecisionRank(requested) < 0) { + return null; + } + const { precision: written, fractionDigits } = isoHl7Precision(match); + const hasOffset = match.groups?.["offset"] !== undefined; + if (!isWritableForm(value, hasOffset, written)) { + return null; + } + const target = requested ?? written; + if (hl7PrecisionRank(target) > hl7PrecisionRank(written)) { + return null; + } + return { target, written, fractionDigits, hasOffset }; +} + +/** + * A zone with no offset needs a disambiguation choice this function does not make; a date with an + * offset is not ISO 8601, and an hour with one is refused, as `isValidInstant` refuses it. + */ +function isWritableForm( + value: string, + hasOffset: boolean, + written: Hl7Precision, +): boolean { + return hasOffset + ? hl7PrecisionRank(written) >= RANK_MINUTE + : !value.includes("["); +} + +interface WallClockRead { + readonly wallClock: Temporal.PlainDateTime; + /** The offset string of the value, or null for a local form. */ + readonly offset: string | null; +} + +/** A form with no offset: Temporal reads the fields, with `overflow: "reject"`. */ +function readLocalForm( + value: string, + match: RegExpExecArray, + written: Hl7Precision, +): WallClockRead | null { + const groups = match.groups as Record; + const reject = { overflow: "reject" } as const; + const own = isoStringBody(value); + let wallClock: Temporal.PlainDateTime; + switch (written) { + case "year": + wallClock = Temporal.PlainDate.from( + { year: Number(groups["year"]), month: 1, day: 1 }, + reject, + ).toPlainDateTime(); + break; + case "month": { + const month = Temporal.PlainYearMonth.from(own); + wallClock = month.toPlainDate({ day: 1 }).toPlainDateTime(); + break; + } + case "day": + if (!isValidDate(own)) { + return null; + } + wallClock = Temporal.PlainDate.from(own).toPlainDateTime(); + break; + case "hour": + wallClock = Temporal.PlainDateTime.from( + { + year: Number(groups["year"]), + month: Number(groups["month"]), + day: Number(groups["day"]), + hour: Number(groups["hour"]), + }, + reject, + ); + break; + default: + if (!isValidDateTime(own)) { + return null; + } + wallClock = Temporal.PlainDateTime.from(own); + } + return { wallClock, offset: null }; +} + +/** A form with an offset: `toOffsetInstant` reads it, and the wall clock is the instant seen at that offset. */ +function readOffsetForm(value: string): WallClockRead | null { + const pair = toOffsetInstant(value); + if (pair === null) { + return null; + } + const wallClock = Temporal.Instant.from(pair.instant) + .toZonedDateTimeISO(pair.offset) + .toPlainDateTime(); + return { wallClock, offset: pair.offset }; +} + +/** `±HHMM` from whole minutes, or null for an offset that is not a whole number of minutes. */ +function writeOffset(offset: string): string | null { + const nanoseconds = parseUtcOffsetNanoseconds(offset); + if (nanoseconds === null || nanoseconds % NANOSECONDS_PER_MINUTE !== 0n) { + return null; + } + const magnitude = nanoseconds < 0n ? -nanoseconds : nanoseconds; + const hours = magnitude / NANOSECONDS_PER_HOUR; + const minutes = (magnitude % NANOSECONDS_PER_HOUR) / NANOSECONDS_PER_MINUTE; + return `${nanoseconds < 0n ? "-" : "+"}${hours.toString().padStart(2, "0")}${minutes + .toString() + .padStart(2, "0")}`; +} + +/** The digits `YYYY` … `SS[.S…]` of the wall clock up to the target precision: a cut, never a rounding. */ +function writeDigits( + wallClock: Temporal.PlainDateTime, + target: Hl7Precision, + fractionDigits: number, +): string { + const pad = (n: number, width: number): string => + String(n).padStart(width, "0"); + const rank = hl7PrecisionRank(target); + const parts = [ + pad(wallClock.year, 4), + pad(wallClock.month, 2), + pad(wallClock.day, 2), + pad(wallClock.hour, 2), + pad(wallClock.minute, 2), + pad(wallClock.second, 2), + ]; + let text = parts.slice(0, Math.min(rank + 1, parts.length)).join(""); + if (target === "fraction") { + const subSecond = + pad(wallClock.millisecond, 3) + + pad(wallClock.microsecond, 3) + + pad(wallClock.nanosecond, 3); + text += `.${subSecond.slice(0, Math.min(MAX_FRACTION_DIGITS, fractionDigits))}`; + } + return text; +} diff --git a/packages/gmt/src/healthcare/format/index.ts b/packages/gmt/src/healthcare/format/index.ts new file mode 100644 index 000000000..51804ac57 --- /dev/null +++ b/packages/gmt/src/healthcare/format/index.ts @@ -0,0 +1 @@ +export * from "./formatHL7"; diff --git a/packages/gmt/src/healthcare/index.ts b/packages/gmt/src/healthcare/index.ts new file mode 100644 index 000000000..663347f97 --- /dev/null +++ b/packages/gmt/src/healthcare/index.ts @@ -0,0 +1,5 @@ +// Re-export `Temporal`, `Intl` and `toTemporalInstant` from the internal seam so every namespace subpath offers them +export { Intl, Temporal, toTemporalInstant } from "../internal/temporal"; +export * from "./format"; +export * from "./parse"; +export * from "./validate"; diff --git a/packages/gmt/src/healthcare/parse/index.ts b/packages/gmt/src/healthcare/parse/index.ts new file mode 100644 index 000000000..3ab83a324 --- /dev/null +++ b/packages/gmt/src/healthcare/parse/index.ts @@ -0,0 +1 @@ +export * from "./parseHL7"; diff --git a/packages/gmt/src/healthcare/parse/parseHL7.test.ts b/packages/gmt/src/healthcare/parse/parseHL7.test.ts new file mode 100644 index 000000000..34e0b7fc3 --- /dev/null +++ b/packages/gmt/src/healthcare/parse/parseHL7.test.ts @@ -0,0 +1,66 @@ +import { resolveLocal } from "../../instant/convert"; +import { + hl7DtmRows, + hl7NullRows, + hl7NullValueInputs, + hl7TsRows, +} from "../../test/hl7ParseRows"; +import { NON_STRINGS } from "../../test/nonStrings"; +import { parseHL7 } from "./parseHL7"; + +describe("parseHL7", () => { + it.each(hl7DtmRows)( + "reads the DTM '$input' as what 2.A.22 says it states", + ({ input, expected }) => { + expect(parseHL7(input)).toStrictEqual(expected); + }, + ); + + it.each(hl7TsRows)( + "reads the TS '$input' with its degree of precision lowering only (2.A.77.2)", + ({ input, expected }) => { + expect(parseHL7(input)).toStrictEqual(expected); + }, + ); + + it.each(hl7NullValueInputs.map((input) => ({ input })))( + "reads '$input' as the null value (ch. 2 §2.5.3, an empty trailing component §2.6.2)", + ({ input }) => { + expect(parseHL7(input)).toStrictEqual({ kind: "null" }); + }, + ); + + it("gives a local value no instant member", () => { + const result = parseHL7("20240615103000"); + expect(result).not.toBeNull(); + expect(result !== null && "instant" in result).toBe(false); + }); + + it.each(hl7NullRows.map((input) => ({ input })))( + "returns null for the string '$input'", + ({ input }) => { + expect(parseHL7(input)).toBeNull(); + }, + ); + + it.each(NON_STRINGS.map(([label, make]) => ({ label, make })))( + "returns null without throwing for $label", + ({ make }) => { + expect(parseHL7(make() as string)).toBeNull(); + }, + ); + + it("returns a fresh object each call", () => { + expect(parseHL7("202406")).not.toBe(parseHL7("202406")); + }); + + it("makes the caller supply the sender's zone: Helsinki 10:30 is 07:30Z, not 10:30Z", () => { + const result = parseHL7("20240615103000"); + if (result?.kind !== "local") { + throw new Error("expected a local value"); + } + const resolved = resolveLocal(result.local, "Europe/Helsinki"); + expect(resolved).toBe("2024-06-15T07:30:00Z"); + expect(resolved).not.toBe("2024-06-15T10:30:00Z"); + }); +}); diff --git a/packages/gmt/src/healthcare/parse/parseHL7.ts b/packages/gmt/src/healthcare/parse/parseHL7.ts new file mode 100644 index 000000000..aeb588236 --- /dev/null +++ b/packages/gmt/src/healthcare/parse/parseHL7.ts @@ -0,0 +1,213 @@ +import { + formatUtcOffset, + HL7_NULL_VALUE, + hl7DegreePrecision, + hl7PrecisionRank, + parseUtcOffsetNanoseconds, + readHl7Dtm, + splitHl7Ts, +} from "../../internal"; +import type { Hl7DtmFields } from "../../internal/hl7DateTime"; +import { Temporal } from "../../internal/temporal"; +import { toOffsetInstant } from "../../instant/convert/toOffsetInstant"; +import { utcOffset } from "../../regex/utc-offset"; +import type { + Hl7DateTime, + Hl7MomentPrecision, + Hl7Precision, +} from "../../types"; + +/** + * Read an HL7 v2 date-time (`DTM`, or the older `TS`) as what it states: a moment, the sender's + * local time, or a span. + * + * HL7 v2.5.1 2.A.22 (headed 2.A.1.22 in the hl7.eu v2.5.1 copy) defines the `DTM` + * `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`; 2.A.77 the `TS`, a `DTM` then `^` and a + * degree of precision. + * + * | `kind` | when | members | + * | --- | --- | --- | + * | `"instant"` | an offset and a minute or finer | `instant`, `offset`, `local`, `precision` | + * | `"local"` | no offset and a minute or finer | `local`, `precision` | + * | `"partial"` | year, month, day or hour | `local`, `offset` (`""` when none), `precision` | + * | `"null"` | the string `""` | none | + * + * - No offset is the sender's local time: 2.A.22, "if the time zone is not included, the time + * zone defaults to that of the local time zone of the sender". It is never read as UTC; supply + * the sender's zone to `resolveLocal`. + * - A partial value has no instant: padding a year or a day to a moment states a fact the sender + * did not send. + * - The degree of precision only lowers (2.A.77.2: it "may not indicate greater precision"), by + * cutting, never rounding. `S` on a fractional value cuts the fraction. + * - `0000` is the start of the stated day (2.A.22, `198807050000`: "Midnight of the night + * extending from July 4 to July 5, 1988"), not the end of the day before. + * - `+0000` and `-0000` are both UTC (2.A.22), read as `+00:00`. + * - `""` (two double quote marks) is the null value and differs from `''` (ch. 2 §2.5.3: "is + * different from omitting an optional data field"); `''` returns `null`. + * - A lone `TS` carries no MSH-2, so `^` separates its components and `&` their subcomponents, + * the separators Figure 2-1 recommends (ch. 2 §2.5.4). When a feed's MSH-2 names others, the + * caller re-joins that `TS` with `^` and `&` first. + * - Components and subcomponents that are present but not expected are ignored (ch. 2 §2.6.2; + * a later version adds them at the end, §2.8.1 and §2.8.2), so `20240615^D^X` reads as + * `20240615^D` and `2024&X` as `2024`. An empty component is not present (§2.6.2), so + * `20240615^D^` reads as `20240615^D` and `""^` as the null value, while `^D` and `&X` return + * `null`. + * - Second `60` and hour `24` are rejected, as is any day the month lacks. + * - Returns `null` on invalid input and for any value that is not a string. Never throws. + * + * @param value HL7 v2 `DTM` or `TS` string + * @returns the reading, or `null` on invalid input + * + * @example parseHL7("20240615103000-0500") // { kind: "instant", instant: "2024-06-15T15:30:00Z", offset: "-05:00", local: "2024-06-15T10:30:00", precision: "second" } + * @example parseHL7("20240615103000") // { kind: "local", local: "2024-06-15T10:30:00", precision: "second" } + * @example parseHL7("20240615") // { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } + * @example parseHL7("199904011200^L") // { kind: "partial", local: "1999-04", offset: "", precision: "month" } + * @example parseHL7("20240615^D^X") // { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } + * @example parseHL7('""') // { kind: "null" } + * @example parseHL7("") // null + * @example parseHL7("20240615240000") // null (hour 24) + */ +export function parseHL7(value: string): Hl7DateTime | null { + try { + if (typeof value !== "string") { + return null; + } + const ts = splitHl7Ts(value); + if (ts === null || ts.dtm === "") { + return null; + } + if (ts.dtm === HL7_NULL_VALUE) { + return ts.degree === "" ? { kind: "null" } : null; + } + const fields = readHl7Dtm(ts.dtm); + if (fields === null) { + return null; + } + const precision = lowerPrecision(fields.precision, ts.degree); + if (precision === null) { + return null; + } + const local = writeLocal(fields, precision); + const offset = readOffset(fields); + if (offset === null) { + return null; + } + if (isMoment(precision)) { + if (offset === "") { + return { kind: "local", local, precision }; + } + const pair = toOffsetInstant(local + offset); + if (pair === null) { + return null; + } + return { + kind: "instant", + instant: pair.instant, + offset: pair.offset, + local, + precision, + }; + } + return { kind: "partial", local, offset, precision }; + } catch { + // Never throws (Core Rule 3) + return null; + } +} + +/** A minute or finer names a moment; a coarser precision names a span. */ +function isMoment(precision: Hl7Precision): precision is Hl7MomentPrecision { + return ( + precision === "minute" || precision === "second" || precision === "fraction" + ); +} + +/** The precision after a `TS` degree (2.A.77.2 lowers only); `null` for a bad or finer degree. */ +function lowerPrecision( + written: Hl7Precision, + degree: string, +): Hl7Precision | null { + if (degree === "") { + return written; + } + const lowered = hl7DegreePrecision(degree); + return lowered === null || + hl7PrecisionRank(lowered) > hl7PrecisionRank(written) + ? null + : lowered; +} + +/** The sent offset as `±HH:MM` (`-0000` reads `+00:00`), `""` when none, `null` when out of range. */ +function readOffset(fields: Hl7DtmFields): string | null { + if (fields.sign === undefined) { + return ""; + } + const sent = `${fields.sign}${fields.offsetHour}:${fields.offsetMinute}`; + const nanoseconds = utcOffset.test(sent) + ? parseUtcOffsetNanoseconds(sent) + : null; + return nanoseconds === null ? null : formatUtcOffset(nanoseconds); +} + +/** + * Validates the calendar of `fields` with Temporal (`overflow: "reject"`), then writes `local` at + * `precision`, cutting and never rounding. A field out of range throws a `RangeError`, which + * `parseHL7` catches. + */ +function writeLocal(fields: Hl7DtmFields, precision: Hl7Precision): string { + const reject = { overflow: "reject" } as const; + const date = Temporal.PlainDate.from( + { + year: Number(fields.year), + month: num(fields.month, 1), + day: num(fields.day, 1), + }, + reject, + ); + const hour = num(fields.hour, 0); + const minute = num(fields.minute, 0); + const second = num(fields.second, 0); + // The field bag rejects second 60 and hour 24, which a string would clamp or refuse. + Temporal.PlainDateTime.from( + { year: date.year, month: date.month, day: date.day, hour, minute, second }, + reject, + ); + if (precision === "year" || precision === "month" || precision === "day") { + return date.toString().slice(0, { year: 4, month: 7, day: 10 }[precision]); + } + if (precision === "hour") { + return `${date.toString()}T${pad(hour)}`; + } + const clock = `${pad(hour)}:${pad(minute)}:${pad(second)}`; + return writeClock( + Temporal.PlainDateTime.from( + `${date.toString()}T${clock}${fields.fraction === undefined ? "" : `.${fields.fraction}`}`, + ), + precision, + fields.fractionDigits, + ); +} + +/** A minute or finer: cut to `precision`, seconds always written. */ +function writeClock( + dateTime: Temporal.PlainDateTime, + precision: Hl7MomentPrecision, + fractionDigits: number, +): string { + return precision === "fraction" + ? dateTime.toString({ + fractionalSecondDigits: fractionDigits as 1 | 2 | 3 | 4, + }) + : dateTime + .round({ smallestUnit: precision, roundingMode: "trunc" }) + .toString({ smallestUnit: "second" }); +} + +/** An absent group reads as its first value (month 1, day 1, time 0). */ +function num(group: string | undefined, absent: number): number { + return group === undefined ? absent : Number(group); +} + +function pad(n: number): string { + return String(n).padStart(2, "0"); +} diff --git a/packages/gmt/src/healthcare/validate/index.ts b/packages/gmt/src/healthcare/validate/index.ts new file mode 100644 index 000000000..60732c0dc --- /dev/null +++ b/packages/gmt/src/healthcare/validate/index.ts @@ -0,0 +1 @@ +export * from "./isValidHL7"; diff --git a/packages/gmt/src/healthcare/validate/isValidHL7.test.ts b/packages/gmt/src/healthcare/validate/isValidHL7.test.ts new file mode 100644 index 000000000..e295d394f --- /dev/null +++ b/packages/gmt/src/healthcare/validate/isValidHL7.test.ts @@ -0,0 +1,41 @@ +import { hl7AllStringInputs } from "../../test/hl7ParseRows"; +import { NON_STRINGS } from "../../test/nonStrings"; +import { parseHL7 } from "../parse/parseHL7"; +import { isValidHL7 } from "./isValidHL7"; + +/** Each verdict is worked out from HL7 v2.5.1 2.A.22 (DTM), 2.A.77 (TS) and ch. 2 §2.5.3 (null). */ +describe("isValidHL7", () => { + it.each` + value | expected | reads + ${"20240615103000-0500"} | ${true} | ${"a DTM to the second with an offset"} + ${"2024"} | ${true} | ${"a year alone"} + ${'""'} | ${true} | ${"the null value clears the stored one (ch. 2 §2.5.3)"} + ${"199904011200^L"} | ${true} | ${"a TS whose degree lowers the precision to the month"} + ${"20240615^"} | ${true} | ${"a TS with an empty degree of precision"} + ${"20240615^D^"} | ${true} | ${"an empty trailing component is not present (ch. 2 §2.6.2)"} + ${'""^'} | ${true} | ${"the null value with an empty degree of precision"} + ${"20240615^D^X"} | ${true} | ${"a third component is not expected and is ignored (ch. 2 §2.6.2)"} + ${"2024&X"} | ${true} | ${"a subcomponent is not expected and is ignored (ch. 2 §2.6.2)"} + ${"&X"} | ${false} | ${"an empty DTM before the subcomponent is not present"} + ${"20240615^S"} | ${false} | ${"a degree finer than the digits (2.A.77.2)"} + ${"20240230"} | ${false} | ${"30 February"} + ${""} | ${false} | ${"an empty string is not the null value"} + ${"20240615103000.12345"} | ${false} | ${"five fraction digits; the picture allows four"} + `("returns $expected for '$value' ($reads)", ({ value, expected }) => { + expect(isValidHL7(value)).toBe(expected); + }); + + it.each(NON_STRINGS.map(([label, make]) => ({ label, make })))( + "returns false without throwing for $label", + ({ make }) => { + expect(isValidHL7(make() as never)).toBe(false); + }, + ); + + it("agrees with parseHL7 on every input of the parser's table", () => { + expect(hl7AllStringInputs.length).toBeGreaterThan(0); + for (const input of hl7AllStringInputs) { + expect(isValidHL7(input), input).toBe(parseHL7(input) !== null); + } + }); +}); diff --git a/packages/gmt/src/healthcare/validate/isValidHL7.ts b/packages/gmt/src/healthcare/validate/isValidHL7.ts new file mode 100644 index 000000000..912a9b456 --- /dev/null +++ b/packages/gmt/src/healthcare/validate/isValidHL7.ts @@ -0,0 +1,37 @@ +import { parseHL7 } from "../parse/parseHL7"; + +/** + * Return true when `value` is an HL7 v2 `DTM`, or a `TS` with a degree of precision the digits + * carry, that `parseHL7` reads. + * + * HL7 v2.5.1 2.A.22 (headed 2.A.1.22 in the hl7.eu v2.5.1 copy) defines the `DTM` + * `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`; 2.A.77 the `TS`. + * + * - True exactly when `parseHL7` returns a reading: the validator calls the parser, so the two + * cannot disagree. + * - The null value `'""'` (two double quote marks) is valid, because ch. 2 §2.5.3 makes it a + * value that clears the stored one; `''` is not. + * - A valid value is not necessarily an instant: `parseHL7` reads a value at a minute or finer + * with no offset as `"local"`, one at year to hour precision as `"partial"` (with or without + * an offset), and `'""'` as `"null"`. + * - Components are read as `parseHL7` reads them: `^` and `&` are the separators (ch. 2 + * §2.5.4), and components and subcomponents that are present but not expected are ignored + * (§2.6.2), so `20240615^D^X` and `2024&X` are valid, while `&X` is not. + * - No public regex exists: a `DTM` is valid only as a whole (calendar, clock, offset and + * degree of precision together), which a pattern alone cannot check. + * - False for a value that is not a string. Never throws. + * + * @param value HL7 v2 `DTM` or `TS` string + * @returns boolean indicating validity + * + * @example isValidHL7("20240615103000-0500") // true + * @example isValidHL7("2024") // true + * @example isValidHL7('""') // true (the null value) + * @example isValidHL7("20240615^D^X") // true (the third component is ignored) + * @example isValidHL7("20240615^S") // false (a degree finer than the digits) + * @example isValidHL7("20240230") // false (30 February) + * @example isValidHL7("") // false (not the null value) + */ +export function isValidHL7(value: string): boolean { + return parseHL7(value) !== null; +} diff --git a/packages/gmt/src/index.ts b/packages/gmt/src/index.ts index 9e51e2b7e..8bc96e34c 100644 --- a/packages/gmt/src/index.ts +++ b/packages/gmt/src/index.ts @@ -3,6 +3,7 @@ export * from "./calendar"; export * from "./duration"; export * from "./finance"; export * from "./gnss"; +export * from "./healthcare"; export * from "./instant"; export * from "./intermodal"; export * from "./interval"; diff --git a/packages/gmt/src/internal/hl7DateTime.test.ts b/packages/gmt/src/internal/hl7DateTime.test.ts new file mode 100644 index 000000000..249a993da --- /dev/null +++ b/packages/gmt/src/internal/hl7DateTime.test.ts @@ -0,0 +1,296 @@ +import { + HL7_DEGREE_OF_PRECISION, + HL7_NULL_VALUE, + HL7_PRECISIONS, + hl7DegreePrecision, + hl7PrecisionRank, + isoHl7Form, + isoHl7Precision, + readHl7Dtm, + splitHl7Ts, +} from "./hl7DateTime"; +import * as internal from "./index"; + +// HL7 v2.5.1 ch. 2A 2.A.22 (DTM), 2.A.77 and 2.A.77.2 (TS), Table 0529. The grammar proves shape +// only: month 01-12 and the calendar are Temporal's job in parseHL7. + +describe("HL7_PRECISIONS and hl7PrecisionRank", () => { + it("lists the seven precisions coarsest first", () => { + expect(HL7_PRECISIONS).toEqual([ + "year", + "month", + "day", + "hour", + "minute", + "second", + "fraction", + ]); + }); + + it.each` + precision | rank + ${"year"} | ${0} + ${"month"} | ${1} + ${"day"} | ${2} + ${"hour"} | ${3} + ${"minute"} | ${4} + ${"second"} | ${5} + ${"fraction"} | ${6} + ${"Second"} | ${-1} + ${""} | ${-1} + `("rank of '$precision' is $rank", ({ precision, rank }) => { + expect(hl7PrecisionRank(precision)).toBe(rank); + }); + + it("ranks an input that is not a string as -1", () => { + expect(hl7PrecisionRank(undefined)).toBe(-1); + }); +}); + +describe("HL7_DEGREE_OF_PRECISION", () => { + it("is Table 0529, upper case, exactly six keys", () => { + expect(HL7_DEGREE_OF_PRECISION).toEqual({ + Y: "year", + L: "month", + D: "day", + H: "hour", + M: "minute", + S: "second", + }); + }); + + it("is frozen", () => { + expect(Object.isFrozen(HL7_DEGREE_OF_PRECISION)).toBe(true); + }); +}); + +describe("hl7DegreePrecision", () => { + it.each` + degree | precision + ${"Y"} | ${"year"} + ${"L"} | ${"month"} + ${"D"} | ${"day"} + ${"H"} | ${"hour"} + ${"M"} | ${"minute"} + ${"S"} | ${"second"} + ${"l"} | ${null} + ${"F"} | ${null} + ${""} | ${null} + ${"toString"} | ${null} + ${"constructor"} | ${null} + ${"__proto__"} | ${null} + ${"hasOwnProperty"} | ${null} + `("degree '$degree' names $precision", ({ degree, precision }) => { + expect(hl7DegreePrecision(degree)).toBe(precision); + }); +}); + +describe("HL7_NULL_VALUE", () => { + it("is two double quote marks, nothing else", () => { + expect(HL7_NULL_VALUE).toBe('""'); + expect(HL7_NULL_VALUE).toHaveLength(2); + }); +}); + +describe("internal barrel", () => { + it("re-exports the pure HL7 grammar", () => { + expect(internal.HL7_PRECISIONS).toBe(HL7_PRECISIONS); + expect(internal.hl7PrecisionRank).toBe(hl7PrecisionRank); + }); +}); + +describe("readHl7Dtm", () => { + it.each` + dtm | precision | fractionDigits + ${"2024"} | ${"year"} | ${0} + ${"202406"} | ${"month"} | ${0} + ${"20240615"} | ${"day"} | ${0} + ${"2024061510"} | ${"hour"} | ${0} + ${"202406151030"} | ${"minute"} | ${0} + ${"20240615103000"} | ${"second"} | ${0} + ${"20240615103000.1"} | ${"fraction"} | ${1} + ${"20240615103000.1234"} | ${"fraction"} | ${4} + `( + "reads '$dtm' as $precision with $fractionDigits fraction digits", + ({ dtm, precision, fractionDigits }) => { + expect(readHl7Dtm(dtm)).toMatchObject({ precision, fractionDigits }); + }, + ); + + it("returns every group as a string, absent ones undefined", () => { + expect(readHl7Dtm("20240615103045.1234-0530")).toEqual({ + year: "2024", + month: "06", + day: "15", + hour: "10", + minute: "30", + second: "45", + fraction: "1234", + sign: "-", + offsetHour: "05", + offsetMinute: "30", + precision: "fraction", + fractionDigits: 4, + }); + expect(readHl7Dtm("2024")).toEqual({ + year: "2024", + month: undefined, + day: undefined, + hour: undefined, + minute: undefined, + second: undefined, + fraction: undefined, + sign: undefined, + offsetHour: undefined, + offsetMinute: undefined, + precision: "year", + fractionDigits: 0, + }); + }); + + it.each` + dtm | sign | offsetHour | offsetMinute + ${"20240615103000-0500"} | ${"-"} | ${"05"} | ${"00"} + ${"2024-0500"} | ${"-"} | ${"05"} | ${"00"} + ${"20240615103000+0000"} | ${"+"} | ${"00"} | ${"00"} + ${"20240615103000-0000"} | ${"-"} | ${"00"} | ${"00"} + ${"2024061510+0100"} | ${"+"} | ${"01"} | ${"00"} + ${"20240615103000.1234+0530"} | ${"+"} | ${"05"} | ${"30"} + `( + "reads the offset of '$dtm' as $sign$offsetHour$offsetMinute", + ({ dtm, sign, offsetHour, offsetMinute }) => { + expect(readHl7Dtm(dtm)).toMatchObject({ sign, offsetHour, offsetMinute }); + }, + ); + + it.each` + dtm | reason + ${"20240615103000.12345"} | ${"five fraction digits"} + ${"20240615103000."} | ${"a point and no digit"} + ${"202406151030.5"} | ${"a fraction after minutes"} + ${"19981004010159+010"} | ${"HL7's own example, a three-digit offset"} + ${"20240615+05"} | ${"an hour-only offset"} + ${"20240615+05:00"} | ${"an extended offset"} + ${"202"} | ${"three digits"} + ${"2024061"} | ${"seven digits"} + ${"202406151"} | ${"nine digits"} + ${" 2024"} | ${"leading space"} + ${"2024 "} | ${"trailing space"} + ${"2024"} | ${"full-width digits"} + ${""} | ${"empty"} + ${"2024Z"} | ${"a Z designator"} + ${"20240615T103000"} | ${"an ISO T separator"} + ${"2024\n"} | ${"a trailing newline"} + ${"2024-06-15"} | ${"ISO extended dashes"} + ${"20240615103000.1234+05"} | ${"a fraction and an hour-only offset"} + `("rejects '$dtm' ($reason)", ({ dtm }) => { + expect(readHl7Dtm(dtm)).toBeNull(); + }); +}); + +describe("input that is not a string", () => { + it("is not read by readHl7Dtm or splitHl7Ts", () => { + expect(readHl7Dtm(undefined as unknown as string)).toBeNull(); + expect(splitHl7Ts(undefined as unknown as string)).toBeNull(); + }); +}); + +describe("splitHl7Ts", () => { + it.each` + value | dtm | degree + ${"20240615"} | ${"20240615"} | ${""} + ${"199904011200^L"} | ${"199904011200"} | ${"L"} + ${"20240615^"} | ${"20240615"} | ${""} + ${"^D"} | ${""} | ${"D"} + ${""} | ${""} | ${""} + ${"20240615^D^"} | ${"20240615"} | ${"D"} + ${"20240615^D^^"} | ${"20240615"} | ${"D"} + ${"20240615^^"} | ${"20240615"} | ${""} + ${'""^'} | ${'""'} | ${""} + ${"^^"} | ${""} | ${""} + `( + "splits '$value' into '$dtm' and degree '$degree'", + ({ value, dtm, degree }) => { + expect(splitHl7Ts(value)).toEqual({ dtm, degree }); + }, + ); + + // ch. 2 §2.6.2: components and subcomponents not expected are ignored + it.each` + value | dtm | degree + ${"20240615^D^X"} | ${"20240615"} | ${"D"} + ${"20240615^^D"} | ${"20240615"} | ${""} + ${"20240615^D^X^"} | ${"20240615"} | ${"D"} + ${"^^D"} | ${""} | ${""} + ${"2024&X"} | ${"2024"} | ${""} + ${"2024^D&X"} | ${"2024"} | ${"D"} + ${"2024&X^D"} | ${"2024"} | ${"D"} + ${"2024&X&Y^D&Z"} | ${"2024"} | ${"D"} + ${"&X"} | ${""} | ${""} + ${"&X^D"} | ${""} | ${"D"} + ${'""&X'} | ${'""'} | ${""} + `( + "ignores what is not expected in '$value': '$dtm' and degree '$degree'", + ({ value, dtm, degree }) => { + expect(splitHl7Ts(value)).toEqual({ dtm, degree }); + }, + ); + + it.each` + value | separator + ${"20240615~D"} | ${"~"} + ${"20240615|D"} | ${"|"} + ${"20240615\\D"} | ${"\\"} + `("reads no other separator: '$separator' stays in the DTM", ({ value }) => { + expect(splitHl7Ts(value)).toEqual({ dtm: value, degree: "" }); + }); +}); + +describe("isoHl7Form and isoHl7Precision", () => { + it.each` + iso | precision | fractionDigits | offset + ${"2024"} | ${"year"} | ${0} | ${undefined} + ${"2024-06"} | ${"month"} | ${0} | ${undefined} + ${"2024-06-15"} | ${"day"} | ${0} | ${undefined} + ${"2024-06-15T10"} | ${"hour"} | ${0} | ${undefined} + ${"2024-06-15T10:30"} | ${"minute"} | ${0} | ${undefined} + ${"2024-06-15T10:30:00"} | ${"second"} | ${0} | ${undefined} + ${"2024-06-15T10:30:00,5"} | ${"fraction"} | ${1} | ${undefined} + ${"2024-06-15T10:30:00.5"} | ${"fraction"} | ${1} | ${undefined} + ${"2024-06-15T10:30:00.123456789Z"} | ${"fraction"} | ${9} | ${"Z"} + ${"2024-06-15T10:30Z"} | ${"minute"} | ${0} | ${"Z"} + ${"2024-06-15T10:30:00-05:00"} | ${"second"} | ${0} | ${"-05:00"} + ${"2024-06-15T10-05:00"} | ${"hour"} | ${0} | ${"-05:00"} + ${"2024-06-15T10:30:00-00:44:30"} | ${"second"} | ${0} | ${"-00:44:30"} + ${"2024-06-15T10:30:00+05:30:15.5"} | ${"second"} | ${0} | ${"+05:30:15.5"} + `( + "reads '$iso' as $precision, $fractionDigits fraction digits, offset $offset", + ({ iso, precision, fractionDigits, offset }) => { + const match = isoHl7Form.exec(iso); + expect(match).not.toBeNull(); + expect(match?.groups?.["offset"]).toBe(offset); + expect(isoHl7Precision(match as RegExpExecArray)).toEqual({ + precision, + fractionDigits, + }); + }, + ); + + it.each` + iso | reason + ${"+010000-01-01"} | ${"an expanded year"} + ${"-000001"} | ${"a negative year"} + ${"2024-06-15t10:30:00"} | ${"lower-case t"} + ${"2024-06-15T10:30:00z"} | ${"lower-case z"} + ${"20240615"} | ${"basic format"} + ${"2024-06-15Z"} | ${"an offset on a date"} + ${"2024-06-15T10:30:00-0500"} | ${"a basic-format offset"} + ${"2024-06-15T10:30:00-05"} | ${"an hour-only offset"} + ${"2024-06-15T10:30:00Z\n"} | ${"a trailing newline"} + ${"2024-06-15T10:30:00."} | ${"a point and no digit"} + ${"2024-06-15T10:30:00.1234567890"} | ${"ten fraction digits"} + ${""} | ${"empty"} + `("does not match '$iso' ($reason)", ({ iso }) => { + expect(isoHl7Form.exec(iso)).toBeNull(); + }); +}); diff --git a/packages/gmt/src/internal/hl7DateTime.ts b/packages/gmt/src/internal/hl7DateTime.ts new file mode 100644 index 000000000..49ed6e0f2 --- /dev/null +++ b/packages/gmt/src/internal/hl7DateTime.ts @@ -0,0 +1,256 @@ +/* + * The HL7 v2 date-time grammar: `DTM` (2.A.22) and the older `TS` (2.A.77) that wraps it with a + * degree of precision (2.A.77.2, Table 0529). Private: a `DTM` is valid only as a whole, so its + * public form is the validator `isValidHL7`, never a pattern. + * + * Pure: this module imports only `types/hl7` and nothing from `instant/` or Temporal, so, like + * `ediGrammar.ts`, it is re-exported from `internal/index.ts`. The parse and format files import + * `toOffsetInstant` themselves. If a later change moves that import, or any other from + * `instant/`, into this module, it leaves the barrel, for the cycle the comment above the + * `ediGrammar` block in `internal/index.ts` describes. + * + * Sources (HL7 Europe's published copies of the standard; the v2.5.1 copy heads these sections + * 2.A.1.22 and 2.A.1.77, HL7's own cross-references and the v2.6 copy say 2.A.22 and 2.A.77): + * - 2.A.22 DTM, picture `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`: + * https://www.hl7.eu/HL7v2x/v251/std251/ch02a.html + * https://www.hl7.eu/HL7v2x/v26/std26/ch02a.html + * - 2.A.77 TS, 2.A.77.2 degree of precision, Table 0529 (`Y L D H M S`), same pages. + * - Ch. 2 §2.5.3 (the null value `""`), §2.5.4 and Figure 2-1 (the recommended separators `^` + * and `&`), §2.6.1.1 (a sender writes `^` only before another populated component), §2.6.2 (a + * component not sent is not present, and one not expected is ignored) and §2.8.1, §2.8.2 (a + * later version adds components at the end): + * https://www.hl7.eu/HL7v2x/v251/std251/ch02.html + */ + +import type { Hl7Precision } from "../types/hl7"; + +/** + * The seven precisions of an HL7 v2 date-time, coarsest first. Every "lower or raise" test in + * the parser and the formatter compares ranks (`hl7PrecisionRank`); nothing compares strings. + */ +export const HL7_PRECISIONS: readonly Hl7Precision[] = [ + "year", + "month", + "day", + "hour", + "minute", + "second", + "fraction", +]; + +/** + * The index of a precision in `HL7_PRECISIONS`, coarsest first. + * + * @param precision candidate precision + * @returns its rank, or `-1` for anything that is not one of the seven + * + * @example hl7PrecisionRank("year") // 0 + * @example hl7PrecisionRank("fraction") // 6 + * @example hl7PrecisionRank("Second") // -1 + */ +export function hl7PrecisionRank(precision: unknown): number { + return HL7_PRECISIONS.indexOf(precision as Hl7Precision); +} + +/** + * Table 0529, degree of precision (2.A.77.2): "(Y = year, L = month, D = day, H = hour, + * M = minute, S = second)". Upper case only; `"fraction"` has no letter. + */ +export const HL7_DEGREE_OF_PRECISION: Readonly< + Record<"Y" | "L" | "D" | "H" | "M" | "S", Hl7Precision> +> = Object.freeze({ + Y: "year", + L: "month", + D: "day", + H: "hour", + M: "minute", + S: "second", +}); + +/** + * The precision a Table 0529 degree letter names. + * + * @param degree candidate degree of precision + * @returns the precision, or `null` for anything but an own upper-case key (`"toString"` and + * `"__proto__"` included) + * + * @example hl7DegreePrecision("L") // "month" + * @example hl7DegreePrecision("l") // null + * @example hl7DegreePrecision("toString") // null + */ +export function hl7DegreePrecision(degree: unknown): Hl7Precision | null { + return typeof degree === "string" && + Object.hasOwn(HL7_DEGREE_OF_PRECISION, degree) + ? HL7_DEGREE_OF_PRECISION[degree as keyof typeof HL7_DEGREE_OF_PRECISION] + : null; +} + +/** + * The HL7 null value: two U+0022 characters (ch. 2 §2.5.3, "transmitted as two double quote + * marks (\"\"), is different from omitting an optional data field"). + */ +export const HL7_NULL_VALUE = '""'; + +// The 2.A.22 picture `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`, one fragment per element. +// ASCII digits only: `[0-9]`, never `\d` with the `u` flag. +const YYYY = "(?[0-9]{4})"; +const MM = "(?[0-9]{2})"; +const DD = "(?[0-9]{2})"; +const HH = "(?[0-9]{2})"; +const MI = "(?[0-9]{2})"; +const SS = "(?[0-9]{2})"; +const FRACTION = "\\.(?[0-9]{1,4})"; +const ZZZZ = "(?[+-])(?[0-9]{2})(?[0-9]{2})"; + +/** + * The `DTM` grammar of 2.A.22, anchored. Named groups: `year month day hour minute second + * fraction sign offsetHour offsetMinute`. The longest match is 24 characters, the `DTM` maximum + * length (2.A.22), so there is no separate length check. Shape only: the ranges and the calendar + * of the date and time fields are Temporal's to check; a partial value's offset is checked with the + * `utcOffset` regex and normalised with `formatUtcOffset` (parseHL7). + */ +export const hl7Dtm: RegExp = new RegExp( + `^${YYYY}(?:${MM}(?:${DD}(?:${HH}(?:${MI}(?:${SS}(?:${FRACTION})?)?)?)?)?)?(?:${ZZZZ})?$`, +); + +/** The fields of a `DTM` that matched `hl7Dtm`, as the strings sent. */ +export interface Hl7DtmFields { + readonly year: string; + readonly month: string | undefined; + readonly day: string | undefined; + readonly hour: string | undefined; + readonly minute: string | undefined; + readonly second: string | undefined; + readonly fraction: string | undefined; + readonly sign: string | undefined; + readonly offsetHour: string | undefined; + readonly offsetMinute: string | undefined; + /** The finest group present: `"fraction"` when a fraction matched. */ + readonly precision: Hl7Precision; + /** The number of fraction digits sent, `0` when none. */ + readonly fractionDigits: number; +} + +/** + * Reads a `DTM` against `hl7Dtm`. No range check here. + * + * @param dtm candidate `DTM` text + * @returns the matched groups and the precision written, or `null` when it does not match + * + * @example readHl7Dtm("20240615103000.1234") // { year: "2024", …, precision: "fraction", fractionDigits: 4 } + * @example readHl7Dtm("2024-0500") // { year: "2024", sign: "-", offsetHour: "05", offsetMinute: "00", precision: "year", … } + * @example readHl7Dtm("20240615103000.12345") // null + */ +export function readHl7Dtm(dtm: string): Hl7DtmFields | null { + if (typeof dtm !== "string") { + return null; + } + const groups = hl7Dtm.exec(dtm)?.groups; + if (groups === undefined) { + return null; + } + const fraction = groups["fraction"]; + return { + year: groups["year"] as string, + month: groups["month"], + day: groups["day"], + hour: groups["hour"], + minute: groups["minute"], + second: groups["second"], + fraction, + sign: groups["sign"], + offsetHour: groups["offsetHour"], + offsetMinute: groups["offsetMinute"], + precision: finestPrecision(groups, fraction), + fractionDigits: fraction === undefined ? 0 : fraction.length, + }; +} + +/** The finest of `year … second` whose group is present, or `"fraction"` when a fraction is. */ +function finestPrecision( + groups: Readonly>, + fraction: string | undefined, +): Hl7Precision { + if (fraction !== undefined) { + return "fraction"; + } + let finest: Hl7Precision = "year"; + for (const precision of HL7_PRECISIONS) { + if (precision !== "fraction" && groups[precision] !== undefined) { + finest = precision; + } + } + return finest; +} + +/** + * Splits a `TS` (2.A.77: `DTM ^ degree of precision`) into its two components, each read up to + * its first subcomponent. A lone field carries no MSH-2, so the separators are the ones Figure + * 2-1 recommends, `^` between components and `&` between subcomponents (ch. 2 §2.5.4). A + * recipient ignores components and subcomponents "that are present but were not expected" + * (ch. 2 §2.6.2), and a later version adds components at the end of a data type (§2.8.1, + * §2.8.2), so everything after the second component and after each first `&` is ignored: + * `20240615^D^X` is `20240615^D`, and `2024&X^D` is `2024^D`. A component left empty is not + * present (§2.6.2), so `20240615^` and `20240615^^D` are `20240615`. + * + * @param value candidate `TS` text + * @returns the two components, each `""` when not present; `null` for a value that is not a string + * + * @example splitHl7Ts("199904011200^L") // { dtm: "199904011200", degree: "L" } + * @example splitHl7Ts("20240615^D^X") // { dtm: "20240615", degree: "D" } + * @example splitHl7Ts("2024&X^D") // { dtm: "2024", degree: "D" } + */ +export function splitHl7Ts( + value: string, +): { dtm: string; degree: string } | null { + if (typeof value !== "string") { + return null; + } + // The limit stops the split at the second component, so the rest is never read. + const [dtm = "", degree = ""] = value.split("^", 2); + return { dtm: firstSubcomponent(dtm), degree: firstSubcomponent(degree) }; +} + +/** A component up to its first `&`; the subcomponents after it are not expected (ch. 2 §2.6.2). */ +function firstSubcomponent(component: string): string { + const amp = component.indexOf("&"); + return amp < 0 ? component : component.slice(0, amp); +} + +const ISO_OFFSET = + "(?Z|[+-][0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:[.,][0-9]{1,9})?)?)"; + +/** + * Which form an ISO 8601 extended string is written in, for `formatHL7`; apply it to + * `isoStringBody(value)`. It reads the form, never the values (Temporal checks those). Groups + * `year month day hour minute second fraction offset`: + * - `year` is exactly four digits, so `+010000` and `-000001` do not match. + * - `fraction` is one to nine digits after `.` or `,` (the decimal signs `plainDateTime` accepts). + * - `offset` follows a time only: `Z` or `±HH:MM` with the optional `:SS` and fraction Temporal + * writes for a sub-minute zone, so the formatter can refuse it rather than fail to match. + * - Upper-case `T` and `Z` only. + */ +export const isoHl7Form: RegExp = new RegExp( + `^(?[0-9]{4})(?:-(?[0-9]{2})(?:-(?[0-9]{2})(?:T(?[0-9]{2})(?::(?[0-9]{2})(?::(?[0-9]{2})(?:[.,](?[0-9]{1,9}))?)?)?${ISO_OFFSET}?)?)?)?$`, +); + +/** + * The precision an `isoHl7Form` match is written at, as `readHl7Dtm` gives it for a `DTM`. + * + * @param match a successful `isoHl7Form.exec` result + * @returns the finest group present and the number of fraction digits written + * + * @example isoHl7Precision(isoHl7Form.exec("2024-06-15T10:30") as RegExpExecArray) // { precision: "minute", fractionDigits: 0 } + * @example isoHl7Precision(isoHl7Form.exec("2024-06-15T10:30:00,5") as RegExpExecArray) // { precision: "fraction", fractionDigits: 1 } + */ +export function isoHl7Precision(match: RegExpExecArray): { + precision: Hl7Precision; + fractionDigits: number; +} { + const groups = match.groups ?? {}; + const fraction = groups["fraction"]; + return { + precision: finestPrecision(groups, fraction), + fractionDigits: fraction === undefined ? 0 : fraction.length, + }; +} diff --git a/packages/gmt/src/internal/index.ts b/packages/gmt/src/internal/index.ts index 6a9e49f22..49a476d99 100644 --- a/packages/gmt/src/internal/index.ts +++ b/packages/gmt/src/internal/index.ts @@ -96,6 +96,17 @@ export { X12_DATE_TIME_PERIOD_FORMATS, X12_TIME_CODES, } from "./ediGrammar"; +export { + HL7_DEGREE_OF_PRECISION, + HL7_NULL_VALUE, + HL7_PRECISIONS, + hl7DegreePrecision, + hl7PrecisionRank, + isoHl7Form, + isoHl7Precision, + readHl7Dtm, + splitHl7Ts, +} from "./hl7DateTime"; export { exactDurationNanoseconds, nonNegativeExactDurationNanoseconds, diff --git a/packages/gmt/src/test/hl7ParseRows.ts b/packages/gmt/src/test/hl7ParseRows.ts new file mode 100644 index 000000000..dac745940 --- /dev/null +++ b/packages/gmt/src/test/hl7ParseRows.ts @@ -0,0 +1,349 @@ +/* + * The inputs of `parseHL7.test.ts`, written once so `isValidHL7.test.ts` can assert, for every + * row, `isValidHL7(input) === (parseHL7(input) !== null)`. Test-only: the build leaves it out. + * Every expected value was decided from HL7 v2.5.1 2.A.22 / 2.A.77.2 (see the spec's Authority + * table) before the parser existed. + */ + +import type { Hl7DateTime } from "../types"; + +/** A string that parses, and what it reads as. */ +export interface Hl7ParseRow { + input: string; + expected: Hl7DateTime; +} + +const instant = ( + input: string, + instant: string, + offset: string, + local: string, + precision: Extract["precision"], +): Hl7ParseRow => ({ + input, + expected: { kind: "instant", instant, offset, local, precision }, +}); + +const local = ( + input: string, + localValue: string, + precision: Extract["precision"], +): Hl7ParseRow => ({ + input, + expected: { kind: "local", local: localValue, precision }, +}); + +const partial = ( + input: string, + localValue: string, + offset: string, + precision: Extract["precision"], +): Hl7ParseRow => ({ + input, + expected: { kind: "partial", local: localValue, offset, precision }, +}); + +/** `DTM` strings (2.A.22) that parse. */ +export const hl7DtmRows: readonly Hl7ParseRow[] = [ + instant( + "20240615103000-0500", + "2024-06-15T15:30:00Z", + "-05:00", + "2024-06-15T10:30:00", + "second", + ), + local("20240615103000", "2024-06-15T10:30:00", "second"), + instant( + "202406151030+0200", + "2024-06-15T08:30:00Z", + "+02:00", + "2024-06-15T10:30:00", + "minute", + ), + local("202406151030", "2024-06-15T10:30:00", "minute"), + instant( + "20240615103000.1234+0000", + "2024-06-15T10:30:00.1234Z", + "+00:00", + "2024-06-15T10:30:00.1234", + "fraction", + ), + instant( + "20240615103000.1000+0000", + "2024-06-15T10:30:00.1Z", + "+00:00", + "2024-06-15T10:30:00.1000", + "fraction", + ), + local("20240615103000.5", "2024-06-15T10:30:00.5", "fraction"), + instant( + "20240615103000-0000", + "2024-06-15T10:30:00Z", + "+00:00", + "2024-06-15T10:30:00", + "second", + ), + instant( + "20240615103000+2300", + "2024-06-14T11:30:00Z", + "+23:00", + "2024-06-15T10:30:00", + "second", + ), + partial("2024", "2024", "", "year"), + partial("202406", "2024-06", "", "month"), + partial("20240615", "2024-06-15", "", "day"), + partial("2024061510", "2024-06-15T10", "", "hour"), + partial("20240615-0500", "2024-06-15", "-05:00", "day"), + partial("2024-0000", "2024", "+00:00", "year"), + partial("0000", "0000", "", "year"), + // the range limits of Temporal's instant, polyfill-checked + instant( + "00000101000000+2359", + "-000001-12-31T00:01:00Z", + "+23:59", + "0000-01-01T00:00:00", + "second", + ), + instant( + "99991231235959.9999-2359", + "+010000-01-01T23:58:59.9999Z", + "-23:59", + "9999-12-31T23:59:59.9999", + "fraction", + ), + local("198807050000", "1988-07-05T00:00:00", "minute"), + partial("20240229", "2024-02-29", "", "day"), + // leap days: every fourth year, and the 400-year century + partial("20000229", "2000-02-29", "", "day"), + local("20240229235959", "2024-02-29T23:59:59", "second"), + instant( + "20240229235959-0500", + "2024-03-01T04:59:59Z", + "-05:00", + "2024-02-29T23:59:59", + "second", + ), + // year 0000 at finer precisions + partial("0000-0500", "0000", "-05:00", "year"), + local("000001010000", "0000-01-01T00:00:00", "minute"), + instant( + "000001010000+0000", + "0000-01-01T00:00:00Z", + "+00:00", + "0000-01-01T00:00:00", + "minute", + ), + // a fraction of 1 to 4 digits, without and with an offset + local("20240615103000.12", "2024-06-15T10:30:00.12", "fraction"), + local("20240615103000.123", "2024-06-15T10:30:00.123", "fraction"), + local("20240615103000.1234", "2024-06-15T10:30:00.1234", "fraction"), + local("20240615103000.0000", "2024-06-15T10:30:00.0000", "fraction"), + instant( + "20240615103000.5+0200", + "2024-06-15T08:30:00.5Z", + "+02:00", + "2024-06-15T10:30:00.5", + "fraction", + ), + instant( + "20240615103000.12+0000", + "2024-06-15T10:30:00.12Z", + "+00:00", + "2024-06-15T10:30:00.12", + "fraction", + ), + instant( + "20240615103000.123-0500", + "2024-06-15T15:30:00.123Z", + "-05:00", + "2024-06-15T10:30:00.123", + "fraction", + ), + instant( + "20240615103000.0000+0000", + "2024-06-15T10:30:00Z", + "+00:00", + "2024-06-15T10:30:00.0000", + "fraction", + ), + // offset range edges + instant( + "202406151030-2359", + "2024-06-16T10:29:00Z", + "-23:59", + "2024-06-15T10:30:00", + "minute", + ), + instant( + "202406151030+0059", + "2024-06-15T09:31:00Z", + "+00:59", + "2024-06-15T10:30:00", + "minute", + ), + partial("202406-0000", "2024-06", "+00:00", "month"), + partial("2024061510+0200", "2024-06-15T10", "+02:00", "hour"), +]; + +/** `TS` strings (2.A.77) that parse. */ +export const hl7TsRows: readonly Hl7ParseRow[] = [ + local("20240615103000^S", "2024-06-15T10:30:00", "second"), + partial("20240615103000^D", "2024-06-15", "", "day"), + partial("199904011200^L", "1999-04", "", "month"), + instant( + "20240615103045-0500^M", + "2024-06-15T15:30:00Z", + "-05:00", + "2024-06-15T10:30:00", + "minute", + ), + partial("20240615103045^H", "2024-06-15T10", "", "hour"), + partial("20240615103045+0100^Y", "2024", "+01:00", "year"), + local("20240615103045.9876^S", "2024-06-15T10:30:45", "second"), + partial("20240615^", "2024-06-15", "", "day"), + // an empty trailing component is not present (ch. 2 §2.6.1.1, §2.6.2) + partial("20240615^D^", "2024-06-15", "", "day"), + partial("20240615^^", "2024-06-15", "", "day"), + partial("20240615^Y^", "2024", "", "year"), + instant( + "20240615103000+0000^S^", + "2024-06-15T10:30:00Z", + "+00:00", + "2024-06-15T10:30:00", + "second", + ), + partial("20240615103000+0000^D", "2024-06-15", "+00:00", "day"), + local("20240615103000.5^M", "2024-06-15T10:30:00", "minute"), + local("20240615103000.5^S", "2024-06-15T10:30:00", "second"), + instant( + "20240615103000.5+0100^S", + "2024-06-15T09:30:00Z", + "+01:00", + "2024-06-15T10:30:00", + "second", + ), + // components and subcomponents not expected are ignored (ch. 2 §2.6.2, §2.8.1, §2.8.2) + partial("20240615^D^X", "2024-06-15", "", "day"), + partial("20240615^^D", "2024-06-15", "", "day"), + partial("20240615^D^X^", "2024-06-15", "", "day"), + partial("2024&X", "2024", "", "year"), + partial("2024^Y&X", "2024", "", "year"), + partial("20240615^D&X", "2024-06-15", "", "day"), + partial("20240615&X^D", "2024-06-15", "", "day"), + local("20240615103000&X&Y^S&Z^Q", "2024-06-15T10:30:00", "second"), + instant( + "202406151030-0500&X^M", + "2024-06-15T15:30:00Z", + "-05:00", + "2024-06-15T10:30:00", + "minute", + ), +]; + +/** Strings that return `null`. */ +export const hl7NullRows: readonly string[] = [ + // a degree finer than the digits (2.A.77.2 "may not indicate greater precision") + // the whole DTM is checked even when the degree lowers the precision (2.A.77.2) + "20240615106000^D", + "20240615103060^Y", + "20240230^Y", + "20240615240000^D", + "20240615^S", + "2024^L", + "202406151030^S", + "202406^D", + "2024061510^M", + "20240615^H", + "20240615^S^", + // the subcomponent is cut, then D is finer than the year sent + "2024^D&X", + "2024&X^D", + // unknown, lower-case and padded degrees, an empty DTM + "20240615^X", + "20240615^d", + "20240615^ D", + "^D", + "^^", + "^^D", + "&X", + "&X^D", + "^D&X", + "20240615^toString", + "20240615^__proto__", + "20240615^constructor", + // the null value is the two quotes alone, with nothing but empty components after them + "", + '"', + '"""', + '""^D', + '""^D^', + ' ""', + '"" ', + // out-of-range fields and days the month lacks + "20240615240000", + "20240615106000", + "20240615103060", + "20240230", + "20231301", + "20230229", + "20240600", + "2024061524", + "202406152400", + "20240615240000.5", + "20240615103060.5", + "20240615103061", + "20240615106000.5", + "202400", + "202413", + "20240000", + "20230229103000", + "19000229", + "20240431", + // fractions + "20240615103000.12345", + "20240615103000.", + "202406151030.5", + // offsets + "20240615103000+010", + "20240615103000+05", + "20240615103000+2400", + "20240615103000+0560", + "20240615103000Z", + "2024+2400", + "20240615-2400", + "2024061510+0060", + "202406151030-0060", + "20240615103000.5+2400", + "20240615103000 +0000", + "20240615103000+00:00", + // ISO, not HL7 + "2024-06-15", + "2024-06-15T10:30:00Z", + // padding and wrong lengths + " 20240615", + "20240615 ", + "202", + "2024061", +]; + +/** + * Strings that read as the HL7 null value (ch. 2 §2.5.3): `""` alone, with empty components, + * which are not present, or with components and subcomponents not expected, which are ignored + * (ch. 2 §2.6.2). + */ +export const hl7NullValueInputs: readonly string[] = [ + '""', + '""^', + '""^^', + '""^^X', + '""&X', +]; + +/** Every string input above, for the `isValidHL7` agreement test. */ +export const hl7AllStringInputs: readonly string[] = [ + ...hl7DtmRows.map((row) => row.input), + ...hl7TsRows.map((row) => row.input), + ...hl7NullRows, + ...hl7NullValueInputs, +]; diff --git a/packages/gmt/src/test/noThrow.test.ts b/packages/gmt/src/test/noThrow.test.ts index 3599c9fab..af1f545fc 100644 --- a/packages/gmt/src/test/noThrow.test.ts +++ b/packages/gmt/src/test/noThrow.test.ts @@ -23,6 +23,7 @@ describe("no-throw harness coverage", () => { "duration", "finance", "gnss", + "healthcare", "instant", "intermodal", "interval", diff --git a/packages/gmt/src/types/hl7.ts b/packages/gmt/src/types/hl7.ts new file mode 100644 index 000000000..23e590c9a --- /dev/null +++ b/packages/gmt/src/types/hl7.ts @@ -0,0 +1,118 @@ +/** + * The precision of an HL7 v2 date-time, coarsest first. HL7 v2.5.1 ch. 2A 2.A.22 (headed + * 2.A.1.22 in the [hl7.eu v2.5.1 copy](https://www.hl7.eu/HL7v2x/v251/std251/ch02a.html)): + * "The number of characters populated (excluding the time zone specification) specifies the + * precision". The characters before the offset, per member: + * + * - `"year"`: 4 (`YYYY`) + * - `"month"`: 6 (`YYYYMM`) + * - `"day"`: 8 (`YYYYMMDD`) + * - `"hour"`: 10 (`YYYYMMDDHH`) + * - `"minute"`: 12 (`YYYYMMDDHHMM`) + * - `"second"`: 14 (`YYYYMMDDHHMMSS`) + * - `"fraction"`: 16 to 19, a decimal point and one to four digits after the seconds + * + * The six coarser members are the degrees of precision of Table 0529 (`Y`, `L`, `D`, `H`, `M`, + * `S`). `"fraction"` has no Table 0529 letter. + * + * The union of `Hl7PartialPrecision` and `Hl7MomentPrecision`. Taken by `formatHL7` through + * `Hl7FormatOptions`; `parseHL7` returns the narrower one for each `kind` of `Hl7DateTime`. + */ +export type Hl7Precision = Hl7PartialPrecision | Hl7MomentPrecision; + +/** + * The precision of a span: a year, month, day or hour, which names no single moment + * (`Hl7Precision` lists the characters each one takes). + * + * Returned in the `"partial"` kind of `Hl7DateTime` by `parseHL7`. + */ +export type Hl7PartialPrecision = "year" | "month" | "day" | "hour"; + +/** + * The precision of a moment: a minute or finer (`Hl7Precision` lists the characters each one + * takes). + * + * Returned in the `"instant"` and `"local"` kinds of `Hl7DateTime` by `parseHL7`. + */ +export type Hl7MomentPrecision = "minute" | "second" | "fraction"; + +/** + * An HL7 v2 date-time (`DTM`, 2.A.22; or `TS`, 2.A.77) read as what it states. What the sender + * did not send is not invented: a value with no offset has no instant, and a year or a day has + * no moment. + * + * Returned by `parseHL7`. + */ +export type Hl7DateTime = + | { + /** An offset and a precision of a minute or finer: a moment in time. */ + kind: "instant"; + /** + * UTC, ISO 8601 ending in `Z`, as `toOffsetInstant` writes it (a sent fraction of `.1000` + * is `.1Z`; `local` keeps `.1000`). + */ + instant: string; + /** `±HH:MM`, as sent; `+0000` and `-0000` both read `+00:00`. */ + offset: string; + /** + * The wall clock as sent, ISO 8601 extended, at the precision sent; seconds always written + * (`2024-06-15T10:30:00`, `2024-06-15T10:30:00.1234`). + */ + local: string; + /** The digits sent, or the `TS` degree of precision when it lowers them. */ + precision: Hl7MomentPrecision; + } + | { + /** No offset and a precision of a minute or finer: the sender's local time. */ + kind: "local"; + /** + * The wall clock as sent, ISO 8601 extended, at the precision sent; seconds always written + * (`2024-06-15T10:30:00`, `2024-06-15T10:30:00.1234`). Ready for `resolveLocal` once you + * supply the sender's zone; HL7 2.A.22: "if the time zone is not included, the time zone + * defaults to that of the local time zone of the sender". + */ + local: string; + /** The digits sent, or the `TS` degree of precision when it lowers them. */ + precision: Hl7MomentPrecision; + } + | { + /** + * Year, month, day or hour precision, with or without an offset: no single moment, so no + * instant. + */ + kind: "partial"; + /** + * The wall clock as sent, ISO 8601 extended, at the precision sent: `2024`, `2024-06`, + * `2024-06-15`, `2024-06-15T10`. + */ + local: string; + /** + * `±HH:MM`, as sent; `+0000` and `-0000` both read `+00:00`; or `""` when the value + * carried none. + */ + offset: string; + /** The digits sent, or the `TS` degree of precision when it lowers them. */ + precision: Hl7PartialPrecision; + } + | { + /** + * The HL7 null value `""` (two double quote marks), ch. 2 §2.5.3: "is different from + * omitting an optional data field". The old value "should be changed to null". + */ + kind: "null"; + }; + +/** + * Options for `formatHL7`. + * + * Taken by `formatHL7`. + */ +export interface Hl7FormatOptions { + /** + * Lowers the precision written; never raises it. The precision is read from the form the input + * is written in, and a value lower than that cuts the digits (never rounds). + * + * @defaultValue the precision of the input + */ + precision?: Hl7Precision; +} diff --git a/packages/gmt/src/types/index.ts b/packages/gmt/src/types/index.ts index cb72850db..6dff7276c 100644 --- a/packages/gmt/src/types/index.ts +++ b/packages/gmt/src/types/index.ts @@ -21,6 +21,7 @@ export * from "./fix"; export * from "./fractional-digit"; export * from "./free-time-options"; export * from "./gnss"; +export * from "./hl7"; export * from "./holiday-rule"; export * from "./interval"; export * from "./now-unit"; diff --git a/scripts/bundle-size.budgets.json b/scripts/bundle-size.budgets.json index 03a526fe8..db6af6d76 100644 --- a/scripts/bundle-size.budgets.json +++ b/scripts/bundle-size.budgets.json @@ -1,7 +1,7 @@ { "entries": { "root": { - "minified": 578900 + "minified": 584000 }, "isValidDate": { "minified": 154900