ezmedicationinput 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +216 -18
  2. package/dist/adapters/canonical-course.d.ts +131 -0
  3. package/dist/adapters/r5-course.d.ts +27 -0
  4. package/dist/advice-locale-adapter.d.ts +24 -0
  5. package/dist/advice.d.ts +73 -6
  6. package/dist/body-site-grammar.d.ts +21 -2
  7. package/dist/body-site-lookup.d.ts +8 -0
  8. package/dist/body-site-spatial.d.ts +12 -2
  9. package/dist/body-site-target.d.ts +38 -3
  10. package/dist/canonical/compile.d.ts +98 -0
  11. package/dist/canonical/course.d.ts +388 -0
  12. package/dist/canonical/format-course.d.ts +38 -0
  13. package/dist/clause-tail-grammar.d.ts +2 -0
  14. package/dist/date-interpretation.d.ts +36 -2
  15. package/dist/dosage-course.d.ts +304 -30
  16. package/dist/event-timing-expression.d.ts +26 -1
  17. package/dist/execution/calendar.d.ts +107 -0
  18. package/dist/execution/engine.d.ts +11 -0
  19. package/dist/fhir-quantity-operator.d.ts +89 -0
  20. package/dist/fhir-translations.d.ts +5 -6
  21. package/dist/fhir.d.ts +119 -14
  22. package/dist/format.d.ts +106 -5
  23. package/dist/hpsg/constructions.d.ts +35 -8
  24. package/dist/hpsg/defaults.d.ts +2 -0
  25. package/dist/hpsg/lexical-classes.d.ts +196 -24
  26. package/dist/hpsg/method-lexicon.d.ts +3 -0
  27. package/dist/hpsg/procedural-context.d.ts +48 -5
  28. package/dist/hpsg/projection.d.ts +32 -1
  29. package/dist/hpsg/quantity-lexicon.d.ts +51 -0
  30. package/dist/hpsg/rule-context.d.ts +172 -7
  31. package/dist/hpsg/rules/clinical-quantity-rules.d.ts +16 -7
  32. package/dist/hpsg/rules/condition-rules.d.ts +13 -3
  33. package/dist/hpsg/rules/core-rules.d.ts +8 -2
  34. package/dist/hpsg/rules/instruction-rules.d.ts +2 -0
  35. package/dist/hpsg/rules/prn-rules.d.ts +12 -1
  36. package/dist/hpsg/rules/site-rules.d.ts +10 -1
  37. package/dist/hpsg/rules/timing-rules.d.ts +116 -22
  38. package/dist/hpsg/segmenter.d.ts +2 -2
  39. package/dist/hpsg/signature.d.ts +54 -7
  40. package/dist/hpsg/timing-lexicon.d.ts +18 -2
  41. package/dist/hpsg/unification.d.ts +3 -1
  42. package/dist/i18n.d.ts +37 -1
  43. package/dist/index.cjs +83231 -52284
  44. package/dist/index.d.ts +26 -9
  45. package/dist/index.js +83222 -52284
  46. package/dist/instruction-action-locale-adapter.d.ts +92 -5
  47. package/dist/instruction-action-parser.d.ts +43 -0
  48. package/dist/instruction-action-terminology.d.ts +44 -3
  49. package/dist/instruction-concept-terminology.d.ts +20 -1
  50. package/dist/instruction-graph-fhir.d.ts +10 -2
  51. package/dist/instruction-graph-ownership.d.ts +96 -0
  52. package/dist/instruction-graph.d.ts +68 -49
  53. package/dist/ir.d.ts +1 -1
  54. package/dist/lexer/lex.d.ts +5 -1
  55. package/dist/lexer/locale.d.ts +14 -0
  56. package/dist/lexer/locales/en.d.ts +11 -0
  57. package/dist/lexer/surface-segmenter.d.ts +1 -1
  58. package/dist/lexer/surface.d.ts +4 -1
  59. package/dist/lexer/token-types.d.ts +6 -0
  60. package/dist/locale-detection.d.ts +5 -0
  61. package/dist/locales/clause/en.d.ts +14 -0
  62. package/dist/locales/course/en.d.ts +20 -0
  63. package/dist/locales/course/th.d.ts +12 -0
  64. package/dist/localization.d.ts +76 -0
  65. package/dist/localized-timing.d.ts +1 -1
  66. package/dist/maps.d.ts +44 -10
  67. package/dist/medication-condition.d.ts +72 -11
  68. package/dist/parser-state.d.ts +12 -2
  69. package/dist/parser.d.ts +5 -3
  70. package/dist/prn.d.ts +13 -2
  71. package/dist/regimen/coordination-scope.d.ts +13 -1
  72. package/dist/regimen/grammar.d.ts +18 -1
  73. package/dist/regimen/parallel-course.d.ts +13 -42
  74. package/dist/regimen/planner.d.ts +2 -3
  75. package/dist/regimen/regimen.d.ts +8 -2
  76. package/dist/relation-terminology.d.ts +1 -0
  77. package/dist/schedule.d.ts +14 -10
  78. package/dist/snomed.d.ts +3 -0
  79. package/dist/suggest-locale-adapter.d.ts +15 -0
  80. package/dist/symptom-terminology.d.ts +5 -1
  81. package/dist/timing-summary.d.ts +114 -1
  82. package/dist/types.d.ts +627 -61
  83. package/dist/unit-lexicon.d.ts +4 -1
  84. package/dist/utils/text.d.ts +3 -0
  85. package/dist/utils/units.d.ts +22 -0
  86. package/package.json +1 -1
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # ezmedicationinput
2
2
 
3
- `ezmedicationinput` parses concise clinician shorthand medication instructions and produces [FHIR R5 Dosage](https://hl7.org/fhir/dosage.html) JSON. It is designed for use in lightweight medication-entry experiences and ships with batteries-included normalization for common Thai/English sig abbreviations.
3
+ `ezmedicationinput` parses concise clinician shorthand medication instructions into editable dosage rows, with [FHIR R5 Dosage](https://hl7.org/fhir/dosage.html) and current R6 export. It is designed for use in lightweight medication-entry experiences and ships with batteries-included normalization for common Thai/English sig abbreviations.
4
4
 
5
5
  ## Features
6
6
 
7
- - Converts shorthand strings (e.g. `1x3 po pc`, `500 mg po q6h prn pain`) into FHIR-compliant dosage JSON.
7
+ - Converts shorthand strings (e.g. `1x3 po pc`, `500 mg po q6h prn pain`) into extended editable dosage rows, with separate R5 and R6 projections.
8
8
  - Parses multi-clause sigs into multiple dosage items (e.g. `OD ... , OS ...`), with all dosage rows available in the complete `batch.fhir` array.
9
9
  - Emits timing abbreviations (`timing.code`) and repeat structures simultaneously where possible.
10
10
  - Maps meal/time blocks to the correct `Timing.repeat.when` **EventTiming** codes and can auto-expand AC/PC/C into specific meals.
@@ -33,17 +33,20 @@ npm install ezmedicationinput
33
33
  ## Usage
34
34
 
35
35
  ```ts
36
- import { parseSig } from "ezmedicationinput";
36
+ import { parseSig, toFhirR5Dosages } from "ezmedicationinput";
37
37
 
38
38
  const batch = parseSig("1x3 po pc", { context: { dosageForm: "tab" } });
39
39
 
40
- // Individual clause and one FHIR Dosage
40
+ // Individual clause and its editable dosage row
41
41
  console.log(batch.count); // 1
42
- console.log(batch.items[0].fhir); // Single FHIR dosage
42
+ console.log(batch.items[0].fhir); // Single EzDosage
43
43
 
44
44
  // Complete batch for multi-dose or phased instructions
45
- console.log(batch.fhir); // EzDosage[]: flat R5-compatible rows
46
- console.log(batch.fhirNext); // R6-like course and phases
45
+ console.log(batch.fhir); // EzDosage[]: extended R5-shaped editable rows
46
+ console.log(batch.fhirNext); // Current FHIR R6 DosageInstruction
47
+
48
+ // Strict R5 wire export, including the batch course metadata
49
+ const r5Dosages = toFhirR5Dosages(batch.fhir, batch.course);
47
50
  ```
48
51
 
49
52
  Example output:
@@ -78,9 +81,9 @@ Example output:
78
81
  `parseSig` and `parseSigAsync` return one batch result containing:
79
82
 
80
83
  - `count`: number of parsed dosage clauses.
81
- - `items[n].fhir`: the dosage for an individual clause.
82
- - `fhir`: `EzDosage[]` containing all flat R5-compatible dosage rows.
83
- - `fhirNext`: R6-like course details, including phases and independent dosing schedules.
84
+ - `items[n].fhir`: the editable `EzDosage` for an individual clause.
85
+ - `fhir`: `EzDosage[]` containing all extended R5-shaped editable rows; these are not strict FHIR R5 JSON.
86
+ - `fhirNext`: native FHIR R6 `DosageInstruction`, with sequential steps and concurrent dosing components.
84
87
  - `meta.segments`: source ranges for each clause.
85
88
  - `shortText`, `longText`, `warnings`, and `meta`: batch-level display and diagnostics.
86
89
 
@@ -89,6 +92,112 @@ Use `items[0].fhir` when displaying or editing a single dosage, and
89
92
  `formatSig` and `fromFhirDosage` accept one dosage; `formatSigBatch`
90
93
  accepts an array of dosages.
91
94
 
95
+ The extended rows under `fhir` remain the compatibility/editing surface.
96
+ Use `toFhirR5Dosages(batch.fhir, batch.course)` for strict R5 wire export.
97
+ This projects the extended clinical fields into supported R5 fields and extensions,
98
+ while retaining the supplied course metadata.
99
+ The `fhirNext` object follows the **pinned HL7 R6 CI build dated November 13, 2026**,
100
+ whose profiles use the version label `6.0.0-snapshot1`. The
101
+ [checked-in contract](fhir/r6/official-snapshot1-20261113-contract.json) records
102
+ the supported schema: `DosageInstruction.step[].component[]` contains R6
103
+ `Dosage` values. Use `fromFhir(fhirNext)` to import that structure.
104
+ The [published September 2026 snapshot](https://www.hl7.org/fhir/6.0.0-snapshot1/dosage.html)
105
+ uses the same version label but defines `DosageDetails`; that schema is not a
106
+ supported interchange target. The importer checks the current structural
107
+ contract, not a datatype name or release tag absent from the JSON. Objects in
108
+ the structural overlap are accepted, including text-only `renderedInstruction`
109
+ objects and structured dosages using shared fields. Acceptance does not identify
110
+ which release produced the object or add support for the September schema.
111
+ TypeScript callers of the earlier R6 draft should replace `FhirR6DosageDetails`
112
+ with `FhirR6DosageInstruction`. Its `step` property is optional, matching the
113
+ current wire contract:
114
+
115
+ ```ts
116
+ import type { FhirR6DosageInstruction } from "ezmedicationinput";
117
+
118
+ function firstStepComponents(instruction: FhirR6DosageInstruction) {
119
+ return instruction.step?.[0]?.component ?? [];
120
+ }
121
+ ```
122
+
123
+ Empty R6 step lists are omitted on output. For a header containing only shared
124
+ Element metadata (such as an ID and unknown extensions), use the explicit
125
+ `fromFhir` boundary; mixed R5/R6 dispatch cannot infer a version from those fields.
126
+ The R5 editing/export APIs are unchanged; the current reader accepts previously
127
+ saved R5 rows without a downstream storage migration. New exports encode an
128
+ approximation on `SimpleQuantity` using the EMA quantity-operator coding. The
129
+ current reader accepts both that encoding and the older package comparator
130
+ child. Older package readers may not recover `~` from a new export; this is not
131
+ a guarantee that an older reader can interpret every newer extension encoding.
132
+
133
+ A phase beginning on the day after the preceding phase uses an application-owned
134
+ `step.start.contextCode`: system
135
+ `urn:ezmedicationinput:CodeSystem:course-phase-event`, code
136
+ `previous-phase-next-day`. It names local midnight following the predecessor's
137
+ last occupied treatment day. The scheduler derives that date from the completed
138
+ phase, including admitted doses and administration durations, so delayed starts,
139
+ count limits, and daylight-saving changes retain their meaning. Any supplied
140
+ `offsetDuration` or exact `offsetRange` is applied from that midnight. The
141
+ relation binds to the current preceding step in the ordered course. Reordering or
142
+ removing a step changes that predecessor; a first step has no predecessor and
143
+ leaves the relation unresolved.
144
+ The existing R5 course metadata preserves this boundary and its annotations
145
+ through saves. Patient-facing wording comes from the course language facet.
146
+
147
+ ### R5 clocks alongside event-based timing
148
+
149
+ For mixed schedules such as `1 tab with meals and @ 10:00`, the R5
150
+ `Timing.repeat.when` retains the meal event. Additional clocks are stored in
151
+ `Timing.repeat.extension` under
152
+ `urn:ezmedicationinput:StructureDefinition:medication-timing-additional-clock`.
153
+ Read each matching extension's `valueTime`; `_valueTime` holds its optional
154
+ primitive metadata. Do not rely only on `repeat.timeOfDay` to recover clocks
155
+ from a mixed R5 schedule.
156
+
157
+ ```json
158
+ {
159
+ "repeat": {
160
+ "when": ["C"],
161
+ "extension": [{
162
+ "url": "urn:ezmedicationinput:StructureDefinition:medication-timing-additional-clock",
163
+ "valueTime": "10:00:00"
164
+ }]
165
+ }
166
+ }
167
+ ```
168
+
169
+ ### Internal native clinical model (unstable)
170
+
171
+ **INTERNAL USE ONLY — NOT A BACKWARD-COMPATIBLE API OR PERSISTENCE FORMAT.**
172
+ `CanonicalCourse`, `CanonicalStage`, `CanonicalAdministration`, their
173
+ nested clinical types, `meta.canonical`, and the native
174
+ import/project/format helpers are implementation surfaces for EZMED
175
+ development. **Their structures, identities, field names, invariants, and
176
+ function signatures may be changed or removed at any time without
177
+ deprecation, migration, compatibility adapters, or support for earlier
178
+ internal shapes.** This remains true even where TypeScript types or helper
179
+ functions are currently exported from the package. Do not persist these
180
+ objects, build downstream integrations against them, or assume one version
181
+ can load another version's internal model.
182
+
183
+ **Only the documented external interchange contracts are compatibility
184
+ boundaries:** `.fhir` and the established R5 editing/persistence APIs
185
+ remain R5-shaped; `toFhirR5Dosages` produces strict R5 wire output.
186
+ `.fhirNext` and `fromFhir` use the *current supported* R6
187
+ structure, not obsolete R6 drafts. The internal model is deliberately free
188
+ to evolve for maximum clinical expressiveness, performance, and
189
+ maintainability; no old internal representation must be retained.
190
+
191
+ Native courses are parser implementation data. EZMED does not expose a native
192
+ editing workflow. Parser and projection outputs, including borrowed provider
193
+ listings, are immutable by caller contract; ordinary imports do not deep-clone
194
+ or freeze them defensively. Instruction action and concept vocabulary lookups
195
+ and listings also return borrowed immutable definitions.
196
+ Applications that modify external R5 or current R6 data pass those values back
197
+ through the corresponding import boundary. Native scheduling, formatting, and
198
+ supply consume clinical facts directly; the R5 reconciliation bridge is confined
199
+ to R5 persistence and interchange.
200
+
92
201
  ### PRN reasons & additional instructions
93
202
 
94
203
  `parseSig` identifies PRN (as-needed) clauses and trailing instructions, then
@@ -238,6 +347,79 @@ Highlights:
238
347
  without imposing timing-sensitive test thresholds.
239
348
 
240
349
 
350
+ ## Extending course realization to another language
351
+
352
+ **Internal extension example:** the native course-realization facet and its
353
+ clinical-model inputs are not a versioned third-party plugin contract.
354
+ They may be restructured along with the internal model, without preserving
355
+ previous facet shapes. Future language packs should depend on language
356
+ boundaries and shared clinical semantics rather than pinning a historic
357
+ `CanonicalCourse` layout.
358
+
359
+ Whole-course wording is a typed optional `course` facet on the existing
360
+ `SigLocalization` registration. It complements the same `formatShort` and
361
+ `formatLong` clause hooks—there is no separate registry or second parser.
362
+
363
+ The `formatLong` callback receives the complete clause, `defaultText`, and
364
+ `formatDefault(style)`. Its returned string is the final clause wording: custom
365
+ formatters may wrap or replace the whole clause and are responsible for that
366
+ wording. Defaults use the resolved locale and include the clause's native timing
367
+ qualifiers, authored directions, and independent advice. Built-in defaults compose
368
+ medication conditions and independent advice from typed facts.
369
+
370
+ ```ts
371
+ import {
372
+ importCanonicalCourse,
373
+ FhirPeriodUnit,
374
+ registerSigLocalization,
375
+ resolveSigLocalization,
376
+ formatCanonicalCourse,
377
+ } from "ezmedicationinput";
378
+
379
+ const english = resolveSigLocalization("en")!;
380
+ registerSigLocalization({
381
+ locale: "example",
382
+ formatShort: ({ defaultText }) => defaultText,
383
+ formatLong: ({ defaultText }) => defaultText,
384
+ course: {
385
+ ...english.course!,
386
+ dayRange: (first, last) => `Jours ${first}–${last}`,
387
+ noDoseDays: (first, last) => `Pause ${first}–${last}.`,
388
+ rateLabel: "Débit: ",
389
+ unspecified: "non spécifié",
390
+ },
391
+ });
392
+
393
+ // An explicit treatment-day window uses both clause and course wording.
394
+ const treatmentDayStart = { coding: [{
395
+ system: "urn:ezmedicationinput:CodeSystem:course-phase-event", code: "treatment-day-start",
396
+ }] };
397
+ const nativeCourse = importCanonicalCourse({ step: [{
398
+ start: { contextCode: treatmentDayStart, offsetDuration: { value: 0, unit: "d" } },
399
+ end: { contextCode: treatmentDayStart, offsetDuration: { value: 3, unit: "d" } },
400
+ component: [{
401
+ doseAndRate: [{ doseQuantity: { value: 1, unit: "tab" } }],
402
+ timing: { repeat: { frequency: 1, period: 1, periodUnit: FhirPeriodUnit.Day } },
403
+ }],
404
+ }] });
405
+ const text = formatCanonicalCourse(nativeCourse, "long", {
406
+ locale: "example", realizationMode: "normalized",
407
+ });
408
+ // text includes "Jours 1–3" from the registered course.dayRange callback.
409
+ ```
410
+
411
+ A full language implementation supplies its own clause hooks and course facet;
412
+ the example deliberately inherits the other English strings. Course templates
413
+ receive resolved counts, intervals, unit codes, predicates and stage windows.
414
+ They do not change clinical scope, calculate dates, choose a treatment branch,
415
+ or reinterpret dose numbers. `i18n.inherit`/`i18n.course` can inherit or override
416
+ the facet using the existing per-call configuration.
417
+
418
+ Adding course wording alone does **not** add parsing or autocomplete in that
419
+ language. Lexer, relation/action terminology and suggestion registrations keep
420
+ their existing roles. This boundary lets a future language-pack installer group
421
+ those registrations without changing the shared clinical engine.
422
+
241
423
  ## Formal HPSG substrate
242
424
 
243
425
  The HPSG core now uses an actual typed-feature-structure runtime on the live parse path. Signs participate in a subtype hierarchy, feature appropriateness is validated, general feature unification preserves reentrancy/structure sharing, and phrase mothers unify daughter `SYNSEM` structures rather than relying only on flat TypeScript object merging. Structural AVMs are immutable and memoized because the medication grammar reuses a small number of SYNSEM shapes heavily.
@@ -786,22 +968,35 @@ Key rules:
786
968
  - Pure frequency schedules (`BID`, `TID`, etc.) fall back to clinic-defined institution times.
787
969
  - All timestamps are emitted as ISO strings that include the clinic time-zone offset.
788
970
 
971
+ Timezone-aware scheduling and supply require `Intl.DateTimeFormat.prototype.formatToParts` and support for the requested IANA time zone.
972
+
789
973
  `from` is required and marks the evaluation window. `orderedAt` is optional—when supplied it acts as the baseline for interval calculations; otherwise the `from` timestamp is reused. The options bag also accepts `timeZone`, `eventClock`, `mealOffsets`, and `frequencyDefaults` at the top level (mirroring the legacy `config` object). `limit` defaults to 10 when omitted.
790
974
 
791
975
  ### Medication amount calculation
792
976
 
793
- `calculateTotalUnits` computes the total amount of medication (and optionally the number of containers) required for a specific duration. It accounts for complex schedules, dose ranges (using the high value), and unit conversions between doses and containers.
977
+ `calculateTotalUnits` computes the total amount of medication (and optionally the number of containers) required for a specific duration. It accounts for complex schedules, dose ranges, and unit conversions between doses and containers. A range uses its upper quantity where feasible; interacting quantity and administration-count limits are considered together. For example, 1.5–2 tablets, at most once per day, with a three-tablet limit over 48 hours permits three tablets across two days as 1.5 + 1.5.
978
+
979
+ Ranged supply with interacting limits uses a bounded exact calculation.
980
+ Successful calls return a `TotalUnitsResult`. When the calculation cannot provide
981
+ an exact attainable maximum, it throws `MedicationQuantityCalculationError`;
982
+ catch the exception and inspect its `code`. For `ranged-capacity-complexity`,
983
+ use a shorter supply window or supply a resolved per-administration quantity.
984
+ For `ranged-capacity-open-maximum`, a strict range has a finite supremum but
985
+ no attainable maximum; the prescriber can resolve the dose or provide a closed
986
+ range before requesting a numeric maximum. These exceptions affect supply
987
+ calculation only. The structured instruction and source remain available for
988
+ parsing, display, persistence, and correction.
794
989
 
795
990
  ```ts
796
- import { calculateTotalUnits, parseSig } from "ezmedicationinput";
991
+ import { calculateTotalUnits, parseSig, FhirPeriodUnit } from "ezmedicationinput";
797
992
 
798
- const { fhir } = parseSig("1x3 po pc");
993
+ const { fhir } = parseSig("1 tab PO TID after meals");
799
994
 
800
995
  const result = calculateTotalUnits({
801
996
  dosage: fhir,
802
997
  from: "2024-01-01T08:00:00Z",
803
998
  durationValue: 7,
804
- durationUnit: "d",
999
+ durationUnit: FhirPeriodUnit.Day,
805
1000
  timeZone: "Asia/Bangkok",
806
1001
  context: {
807
1002
  containerValue: 30, // 30 tabs per bottle
@@ -823,7 +1018,7 @@ calculateTotalUnits({
823
1018
  dosage: parsed.fhir,
824
1019
  from: "2024-01-01T08:00:00Z",
825
1020
  durationValue: 7,
826
- durationUnit: "d",
1021
+ durationUnit: FhirPeriodUnit.Day,
827
1022
  timeZone: "Asia/Bangkok"
828
1023
  });
829
1024
 
@@ -858,16 +1053,19 @@ parseStrength("1%", { dosageForm: "cream" });
858
1053
  parseStrength("250mg/5mL");
859
1054
  // → { strengthRatio: { numerator: { value: 250, unit: "mg" }, denominator: { value: 5, unit: "mL" } } }
860
1055
 
861
- // Composite (sums components into a single ratio)
1056
+ // Composite (preserves each ingredient separately)
862
1057
  parseStrength("875mg + 125mg");
863
- // → { strengthQuantity: { value: 1000, unit: "mg" } }
1058
+ // → { strengthComponents: [
1059
+ // { strengthQuantity: { value: 875, unit: "mg" } },
1060
+ // { strengthQuantity: { value: 125, unit: "mg" } }
1061
+ // ] }
864
1062
 
865
1063
  // Simple Quantity
866
1064
  parseStrength("500mg");
867
1065
  // → { strengthQuantity: { value: 500, unit: "mg" } }
868
1066
  ```
869
1067
 
870
- `parseStrengthIntoRatio` is also available if you specifically need a FHIR Ratio object regardless of the denominator.
1068
+ `parseStrengthIntoRatio` is also available when you need a FHIR Ratio for one ingredient; it returns `null` for composite strengths.
871
1069
 
872
1070
  ### Ocular & intravitreal shortcuts
873
1071
 
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Interchange boundary for EZMED's canonical course.
3
+ *
4
+ * R6 input is read directly: never flatten to R5, attach persistence markers,
5
+ * decode those markers, and reconstruct clinical meaning merely to execute.
6
+ * R5 edit reconciliation remains the R5 adapter's responsibility. Both output
7
+ * versions are projections of the same canonical clinical course. Unknown
8
+ * source metadata is retained separately and never consulted by execution.
9
+ */
10
+ import type { FhirDosage, EzDosage, FhirR6Dosage, FhirR6DosageInstruction, FhirR6DosageInstructionInput, FhirR6DoseLimit, FhirR6DosageSafety, FhirR6DosageStep, CanonicalSigClause, FhirR6RelativeTime, FhirQuantity, FhirR6Quantity, FhirRange, FhirR6Range, FhirRatio, ParseBatchResult, NextDueDoseOptions, FhirR6Extension, FormatOptions } from "../types";
11
+ import type { CanonicalMeasure, CanonicalAmount, CanonicalRange, CanonicalAdministration, CanonicalSafety, CanonicalDoseLimit, CanonicalCourse, CanonicalStage, CanonicalBoundary, CanonicalScheduleInput } from "../canonical/course";
12
+ import type { FhirProjectionOptions } from "../fhir";
13
+ /** A maximum without both endpoint objects is retained source, not an invented R6 limit. */
14
+ export declare const R5_SOURCE_ONLY_MAXIMUM_URL = "urn:ezmedicationinput:StructureDefinition:r5-source-only-maximum";
15
+ export declare function measureFromWire(q: FhirQuantity | FhirR6Quantity | undefined): CanonicalMeasure | undefined;
16
+ export declare function rangeFromFhir(r: FhirRange | FhirR6Range | undefined): CanonicalRange | undefined;
17
+ export declare function boundaryFromR6(b: FhirR6RelativeTime | undefined): CanonicalBoundary | undefined;
18
+ /** Every understood safety rule is typed. Unknown element metadata stays
19
+ * only on the retained external source object, never in an executable bag. */
20
+ export declare function doseLimitFromWire(limit: FhirR6DoseLimit): CanonicalDoseLimit;
21
+ export declare function safetyFromWire(safety: FhirR6DosageSafety | undefined, includeLimits?: boolean): CanonicalSafety | undefined;
22
+ /** Wire safety output owns coding/retained external metadata; clinical facts
23
+ * own the live ifExceeded and limits. No generic internal safety fields leak. */
24
+ export declare function safetyToWire(policy: CanonicalSafety | undefined, source: FhirR6DosageSafety | undefined, limits?: CanonicalDoseLimit[], inferCoding?: boolean): FhirR6DosageSafety | undefined;
25
+ export declare function amountFromWire(a: NonNullable<FhirR6Dosage["doseAndRate"]>[number], r5?: boolean): CanonicalAmount;
26
+ /** Import one native R6 administration WITHOUT any R5 projection. */
27
+ export declare function administrationFromR6(raw: FhirR6Dosage, sourceContext?: boolean): CanonicalAdministration;
28
+ /** Remove only generated source mirrors already owned by a lifted partial
29
+ * limit. Authored markers and unmatched Ratios keep their exact multiplicity. */
30
+ export declare function removeLiftedPartialMaximumMirrors(fresh: CanonicalAdministration, row: FhirDosage, safety: FhirR6DosageSafety | undefined): void;
31
+ export declare function administrationFromR5(raw: FhirDosage | EzDosage, sourceContext?: boolean): CanonicalAdministration;
32
+ export declare function courseFromR6(raw: FhirR6DosageInstructionInput, sourceContext?: boolean): CanonicalCourse;
33
+ /** Reconciliation is solely an R5 import concern, never part of native
34
+ * course execution. A simple scalar needs no course reconstruction. */
35
+ export declare function isR6DosageInstruction(input: object): input is FhirR6DosageInstructionInput;
36
+ export declare function inputToCanonical(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalScheduleInput, alternativeChoices?: NextDueDoseOptions["alternativeChoices"]): CanonicalScheduleInput;
37
+ export declare function boundaryToWire(b: CanonicalBoundary | undefined): FhirR6RelativeTime | undefined;
38
+ /** Use the supplied dose unit, including one carried by either range endpoint. */
39
+ export declare function r5MaximumDoseBasis(amounts: FhirDosage["doseAndRate"]): FhirQuantity | undefined;
40
+ interface SelectedR5Maximum {
41
+ quantity: CanonicalMeasure;
42
+ /** A same-code label can establish a comparison scale without rewriting the winning quantity. */
43
+ comparisonBasis?: CanonicalMeasure;
44
+ definite: boolean;
45
+ strict: boolean;
46
+ index?: number;
47
+ }
48
+ export interface R5MaximumSelection extends SelectedR5Maximum {
49
+ groups?: Map<string, SelectedR5Maximum>;
50
+ }
51
+ /** Select a comparable numeric upper bound for R5's singular maximum field.
52
+ * Equal bounds retain the last annotated source; a strict bound wins an equal
53
+ * inclusive one. Approximate siblings stay retained without replacing an
54
+ * available definite upper bound. Prefer the dose-compatible group when known.
55
+ * Only interleaved units allocate group state. */
56
+ export declare function selectR5Maximum(current: R5MaximumSelection | undefined, quantity: CanonicalMeasure, index?: number, dose?: CanonicalMeasure): R5MaximumSelection;
57
+ /** Shared wire serializer for current maxima and retained R5 edit baselines. */
58
+ export declare function periodMaximumToR5(amount: CanonicalMeasure, period: CanonicalMeasure, source?: object): FhirRatio;
59
+ /** Both direct wire projection and supplied parser rows carry this native
60
+ * dose fact. The anatomical count marker is deliberately not allocation proof. */
61
+ export declare function writeAdministrationDoseAllocation(output: FhirDosage | FhirR6Dosage, administration: CanonicalAdministration): void;
62
+ /** Direct native-to-R6 component writer. */
63
+ /** Emit native R6 directly from modeled clinical facts. Shared serializers
64
+ * encode vocabulary and grammar-source annotations only, never an R5 course. */
65
+ export declare function administrationToR6(a: CanonicalAdministration, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause, phaseSequence?: number, trackCycleMember?: boolean): FhirR6Dosage;
66
+ /** Direct native-to-R5 component writer. No R6 component is constructed. */
67
+ export declare function administrationToR5(a: CanonicalAdministration, sequence: number | undefined, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause, trackCycleMember?: boolean): FhirDosage;
68
+ /** Header/step metadata is shared fragment serialization, NOT a course in
69
+ * another external format. The R5 writer encodes it directly in R5 extensions. */
70
+ export declare function courseMetadataToWire(course: CanonicalCourse): Omit<FhirR6DosageInstruction, "step" | "renderedInstruction">;
71
+ /** Native typed facts come from metadata fragments, not from a whole other
72
+ * external course. Foreign annotations are kept on the source envelope. */
73
+ export declare function stageFromFields(fields: Omit<FhirR6DosageStep, "component">, members: CanonicalAdministration[]): CanonicalStage;
74
+ export declare function stageMetadataToWire(stage: CanonicalStage): Omit<FhirR6DosageStep, "component">;
75
+ /** Ordinary native export must derive source-annotation views from current
76
+ * native fields because callers may have edited them. */
77
+ export declare function courseToR6(course: CanonicalCourse, options?: FhirProjectionOptions): FhirR6DosageInstruction;
78
+ /** Parser construction-only export: the caller has JUST compiled these exact
79
+ * clauses and has not exposed them for edits. Reusing their annotation views
80
+ * avoids rebuilding every canonical clause merely to write its first output.
81
+ * This is not a persistent cache and is never used for public edited exports. */
82
+ export declare function projectFreshlyCompiledCourseToR6(course: CanonicalCourse, options?: FhirProjectionOptions): FhirR6DosageInstruction;
83
+ export declare function courseToR5(course: CanonicalCourse): FhirDosage[];
84
+ /** Source-only R6 instructions have no structured administration to preview.
85
+ * A nonempty header on a structured import is original text, not evidence
86
+ * that its dose/timing still agrees with the independently editable fields. */
87
+ export declare function unchangedR6SourceDisplay(raw: FhirR6DosageInstructionInput, options?: FormatOptions): string | undefined;
88
+ /** Explicit editable import for applications that already hold R5 rows.
89
+ * Import normalization and persistence reconciliation happen once here, not
90
+ * inside any native edit, formatter, or execution operation. Metadata-only
91
+ * R6 headers share R5's Element shape; use fromFhir for that known-R6 input. */
92
+ export declare function importCanonicalCourse(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalCourse): CanonicalCourse;
93
+ /**
94
+ * R6-only serialization of editable information that has no active core slot.
95
+ * These annotations contain current FHIR fragments, never a persisted native
96
+ * model. Draft steps remain source data; a one-step safety projection records
97
+ * its original scope so an unchanged export can be reopened for editing.
98
+ */
99
+ export declare const R6_DRAFT_STEPS_SOURCE_URL = "urn:ezmedicationinput:r6-draft-steps-source";
100
+ export declare const R6_SINGLE_STEP_SAFETY_SOURCE_URL = "urn:ezmedicationinput:r6-single-step-safety-source";
101
+ export declare const R6_SCOPED_SAFETY_MODIFIER_URL = "urn:ezmedicationinput:r6-scoped-safety-policy";
102
+ export declare function retainDraftSteps(output: FhirR6DosageInstruction, drafts: Array<{
103
+ index: number;
104
+ step: Omit<FhirR6DosageStep, "component">;
105
+ }> | undefined, synthesizedStarts?: number[]): void;
106
+ /** Restore inactive editable stages while their active phase owners and
107
+ * boundaries still agree. Current doses and other live fields stay current. */
108
+ export declare function editableCourseSteps(input: FhirR6DosageInstructionInput): FhirR6DosageStep[];
109
+ /** Indices from the current external draft source, for R5 membership edits. */
110
+ export declare function retainedDraftStepIndices(input: {
111
+ extension?: FhirR6Extension[];
112
+ }): readonly number[] | undefined;
113
+ interface LiftedSafety {
114
+ course?: FhirR6DosageSafety;
115
+ step: FhirR6DosageSafety;
116
+ projected: FhirR6DosageSafety;
117
+ ownerId?: string;
118
+ ownerComponentIds?: string[];
119
+ ownerFingerprint?: string;
120
+ /** Resolved current wire owner; never part of the serialized source record. */
121
+ owner?: FhirR6DosageStep;
122
+ }
123
+ /** Only a matching live policy can reuse its saved scope. A later wire edit
124
+ * replaces that authority rather than reviving an old safety instruction. */
125
+ export declare function retainedSingleStepSafety(input: FhirR6DosageInstructionInput): LiftedSafety | undefined;
126
+ export declare function liftSingleStepSafety(output: FhirR6DosageInstruction): void;
127
+ /** Conflicting externally edited choices have no single active clinical meaning.
128
+ * Keep every submitted value in typed source data, leaving the independent
129
+ * dose/rate dimension available without inventing a winner for the conflict. */
130
+ export declare function retainConflictingAmountChoices(amount: Record<string, unknown>, doseConflict: boolean, rateConflict: boolean): void;
131
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Direct CanonicalCourse -> R5 writer.
3
+ *
4
+ * Native clinical fields write the R5 dosage once. Only facts R5 cannot hold
5
+ * go into the existing typed R5 retention extension. The extension spelling
6
+ * stays compatible with saved client data; it is NOT an intermediate R6
7
+ * dosage/course used to obtain the R5 result.
8
+ */
9
+ import type { FhirDosage, EzDosage, EzCourseMetadata, CanonicalSigClause } from "../types";
10
+ import type { CanonicalCourse, CanonicalAdministration } from "../canonical/course";
11
+ import type { FhirProjectionOptions } from "../fhir";
12
+ import { type DosageSourceTextBaseline } from "../dosage-course";
13
+ /** A standalone source component uses the same native facts and retained-field
14
+ * writer as a complete course, without inventing surrounding stages. */
15
+ export declare function projectNativeR5Administration(administration: CanonicalAdministration, sequence: number | undefined, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirDosage;
16
+ /** Native course metadata is serialized once into its FINAL R5 extension
17
+ * header. Step/member loops write direct rows and their local retained fields.
18
+ * No R6 object is built, flattened, imported, or used as an adapter input. */
19
+ export declare function projectNativeR5Course(course: CanonicalCourse, options?: FhirProjectionOptions, editable?: boolean, freshlyCompiled?: boolean, attachInstruction?: boolean, strictPreview?: boolean, suppliedRows?: readonly (FhirDosage | EzDosage)[], deferSourceProvenance?: boolean): {
20
+ dosages: EzDosage[];
21
+ course: EzCourseMetadata;
22
+ strictDosages?: FhirDosage[];
23
+ sourceBaselines?: readonly (DosageSourceTextBaseline | undefined)[];
24
+ };
25
+ export declare function courseFromR5(dosages: readonly (FhirDosage | EzDosage)[], renderedInstruction?: string, course?: EzCourseMetadata, options?: {
26
+ resolvedPhaseSequences?: readonly number[];
27
+ }, sourceContext?: boolean, classifiedCarriers?: Set<number>): CanonicalCourse;
@@ -1,3 +1,4 @@
1
+ import type { MedicationConditionLexicalFeatures } from "./medication-condition";
1
2
  import { AdviceFrame, AdviceModality } from "./types";
2
3
  export interface AdviceLocaleRealizationInput {
3
4
  frame: AdviceFrame;
@@ -6,14 +7,37 @@ export interface AdviceLocaleRealizationInput {
6
7
  argText?: string;
7
8
  modalityText?: string;
8
9
  relationText?: string;
10
+ /** Complete wording from the selected typed action. Stock realization keeps
11
+ * its argument roles and relations; registered providers may replace it. */
12
+ typedText?: string;
9
13
  }
10
14
  export interface AdviceLocaleAdapter {
11
15
  locale: string;
16
+ medicationConditions?: MedicationConditionLexicalFeatures;
17
+ referentIdentity?(text: string): string;
18
+ siteCoordination?(text: string): {
19
+ left: string;
20
+ right: string;
21
+ connector: string;
22
+ } | undefined;
12
23
  realizeModality(modality: AdviceModality | undefined): string | undefined;
13
24
  siteArgument(text: string): string;
14
25
  joinArguments(texts: string[]): string | undefined;
15
26
  realize(input: AdviceLocaleRealizationInput): string;
16
27
  finalize(text: string): string;
17
28
  }
29
+ /** Revision of the registered lexical capabilities used by derived caches. */
30
+ export declare function adviceLocaleAdapterRevision(): number;
18
31
  export declare function registerAdviceLocaleAdapter(adapter: AdviceLocaleAdapter): void;
19
32
  export declare function getAdviceLocaleAdapter(locale: string): AdviceLocaleAdapter;
33
+ /** A registered wording provider keeps its complete advice realization even
34
+ * when typed graph facts can supply the stock default. Recognition-only
35
+ * registration does not replace that default; no callback runs for this test. */
36
+ export declare function hasRegisteredAdviceWording(locale: string, hook?: "realize" | "realizeModality" | "siteArgument" | "joinArguments" | "finalize"): boolean;
37
+ /** Stock wording is used only to recognize an unchanged materialized label. */
38
+ export declare function getDefaultAdviceLocaleAdapter(locale: string): AdviceLocaleAdapter;
39
+ /** Recognize a connector independently of the languages of its two nouns. */
40
+ export declare function matchAdviceSiteCoordination(text: string, locale: string): ReturnType<NonNullable<AdviceLocaleAdapter["siteCoordination"]>>;
41
+ /** Clause admission consumes registered lexical cues independently of the
42
+ * language selected for rendering; registration owns matcher cursor semantics. */
43
+ export declare function isAdviceConditionCue(text: string): boolean;
package/dist/advice.d.ts CHANGED
@@ -1,4 +1,27 @@
1
- import { AdditionalInstructionDefinition, AdviceForce, AdviceFrame, FhirCoding, TextRange } from "./types";
1
+ import type { LexToken } from "./lexer/token-types";
2
+ import { AdditionalInstructionDefinition, AdviceArgument, AdviceForce, AdviceFrame, FhirCoding, MedicationInstructionActionDefinition, TextRange } from "./types";
3
+ /** Directed clinical Coding identity; presentation and Element annotations stay on their owner. */
4
+ export declare function preservesAdviceCoding(selected: FhirCoding | undefined, actual: FhirCoding | undefined): boolean;
5
+ export declare function preservesAdviceCodings(selected: readonly FhirCoding[] | undefined, actual: readonly FhirCoding[] | undefined): boolean;
6
+ export declare function preservesAdviceComponents(selected: readonly {
7
+ role: string;
8
+ text?: string;
9
+ coding?: FhirCoding;
10
+ }[] | undefined, actual: readonly {
11
+ role: string;
12
+ text?: string;
13
+ coding?: FhirCoding;
14
+ }[] | undefined): boolean;
15
+ /** Text, source spans and retained Element annotations are not typed argument facts. */
16
+ export declare function hasAdviceArgumentFacts(argument: AdviceArgument): boolean;
17
+ export declare function preservesAdviceArgumentFacts(selected: AdviceArgument, actual: AdviceArgument): boolean;
18
+ /** Argument roles are independent slots; the order within a role is retained. */
19
+ export declare function correspondingAdviceArguments(selected: readonly AdviceArgument[], actual: readonly AdviceArgument[], matches: (left: AdviceArgument, right: AdviceArgument) => boolean, complete?: boolean): boolean;
20
+ /**
21
+ * Preserve selected typed facts while a caller licenses the same occurrence/head.
22
+ * Source/value correspondence and provisional opaque valence remain caller-owned.
23
+ */
24
+ export declare function preservesAdviceFrameFacts(selected: AdviceFrame, actual: AdviceFrame): boolean;
2
25
  export interface ParsedAdditionalInstruction {
3
26
  text?: string;
4
27
  coding?: FhirCoding & {
@@ -19,21 +42,56 @@ export interface AdviceParseContext {
19
42
  export declare function matchComposedAdviceCodings(frames: readonly AdviceFrame[]): AdditionalInstructionDefinition[];
20
43
  /** Determine whether a rule's coding must be rechecked against scoped HPSG frames. */
21
44
  export declare function adviceCodingNeedsComposedScope(system: string, code: string): boolean;
45
+ /** Return the same composed-only declaration for preview lexical ownership. */
46
+ export declare function composedAdviceCodingDefinition(system: string, code: string): AdditionalInstructionDefinition | undefined;
47
+ /** Retain the selected occurrences whose complete qualifiers are represented by
48
+ * the coding template. One unrepresented member does not invalidate its siblings;
49
+ * source locations and registered lexical enrichment are not additional meaning.
50
+ * Association without a selected locale must retain every supplied predicate label. */
51
+ export declare function adviceTemplateRepresentedActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code" | "_system">, locale?: string): AdviceFrame[];
22
52
  /**
23
- * Standardized coded warnings retain their clinical wording when precisely
24
- * one composed action entails that warning. Return its original action source
25
- * for exclusion from a DUPLICATE realization; neither action nor code is lost.
53
+ * Retain the existing coding matcher's exact supporting action objects for
54
+ * occurrence-aware realization. Clinical coding and wording remain with their
55
+ * existing owners; no action identity is reconstructed from rendered text.
26
56
  */
27
- export declare function composedCodedWarningActionSources(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code"> | undefined): string[];
57
+ export declare function composedCodedAdviceActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code" | "_system"> | undefined): AdviceFrame[];
28
58
  /** Existing advice terminology supplies manner modifiers to the main action
29
59
  * grammar. It is lexical evidence, not a second clause parser. */
30
60
  export declare function resolveAdviceMannerModifier(surface: string): {
31
61
  lemma: string;
32
62
  i18n?: Record<string, string>;
33
63
  } | undefined;
34
- export declare function realizeAdviceFramesText(frames: AdviceFrame[], locale?: string): string | undefined;
64
+ /** Exact advice nominals share their existing lexical identity with action arguments. */
65
+ export declare function resolveAdviceNominalArgument(surface: string, sourceText?: string): AdviceArgument | undefined;
66
+ /** A complete compound nominal retains its lexical owner when its final word
67
+ * also names a generic event. Only declared compounds ending at that word are checked. */
68
+ export declare function resolveCompoundAdviceNominalEndingAt(tokens: readonly Pick<LexToken, "canonical" | "lower">[], endExclusive: number): {
69
+ start: number;
70
+ argument: AdviceArgument;
71
+ } | undefined;
72
+ /** The same declared compound owner resolves a complete following conjunct. */
73
+ export declare function resolveCompoundAdviceNominalAt(tokens: readonly Pick<LexToken, "canonical" | "lower">[], start: number): {
74
+ end: number;
75
+ argument: AdviceArgument;
76
+ } | undefined;
77
+ export declare function classifyArgument(text: string, completeNominal?: boolean): AdviceArgument;
78
+ export declare function realizeAdviceFramesText(frames: AdviceFrame[], locale?: string, typed?: {
79
+ text: string;
80
+ argumentText: (argument: AdviceArgument) => string;
81
+ }): string | undefined;
35
82
  export declare function parseAdditionalInstructions(sourceText: string, span: TextRange, context?: AdviceParseContext): ParsedAdditionalInstruction[];
83
+ /** Complete registered wording permits only the existing presentation variants.
84
+ * This proves stock lexical ownership, never equality of rendered instructions. */
85
+ export declare function isStockAdditionalInstructionWording(text: string | undefined, definition: AdditionalInstructionDefinition): boolean;
86
+ /** Exact registered advice remains one lexical constituent before a generic
87
+ * action frame can split its nominal or relation-shaped words. */
88
+ export declare function resolveRegisteredAdditionalInstruction(sourceText: string, span: TextRange, selectedAction: MedicationInstructionActionDefinition | undefined): ParsedAdditionalInstruction | undefined;
36
89
  export declare function findAdditionalInstructionDefinitionByCoding(system: string, code: string): AdditionalInstructionDefinition | undefined;
90
+ /** Select known advice meaning without reducing the original wire coding list. */
91
+ export declare function selectAdditionalInstructionCoding<T extends {
92
+ system?: string;
93
+ code?: string;
94
+ }>(codings: readonly T[] | undefined): T | undefined;
37
95
  export declare const __test__: {
38
96
  createDefinitionFromSource(source: {
39
97
  system?: string;
@@ -43,4 +101,13 @@ export declare const __test__: {
43
101
  thai: string;
44
102
  }): AdditionalInstructionDefinition;
45
103
  };
104
+ /** Keep authored wording when the selected advice identity has no display. */
105
+ export declare function additionalInstructionFallbackText(concept: {
106
+ text?: string;
107
+ coding?: readonly {
108
+ display?: string;
109
+ }[];
110
+ }, selectedCoding: {
111
+ display?: string;
112
+ } | undefined): string | undefined;
46
113
  export declare function buildAdditionalInstructionFramesFromCoding(system: string, code: string, sourceText?: string, span?: TextRange): AdviceFrame[] | undefined;