ezmedicationinput 0.1.67 → 0.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +222 -28
  2. package/dist/adapters/canonical-course.d.ts +128 -0
  3. package/dist/adapters/r5-course.d.ts +24 -0
  4. package/dist/advice.d.ts +52 -1
  5. package/dist/body-site-grammar.d.ts +34 -1
  6. package/dist/body-site-lookup.d.ts +3 -0
  7. package/dist/body-site-spatial.d.ts +6 -2
  8. package/dist/body-site-target.d.ts +9 -3
  9. package/dist/canonical/compile.d.ts +79 -0
  10. package/dist/canonical/course.d.ts +352 -0
  11. package/dist/canonical/format-course.d.ts +36 -0
  12. package/dist/date-interpretation.d.ts +2 -0
  13. package/dist/dosage-course.d.ts +453 -0
  14. package/dist/execution/calendar.d.ts +107 -0
  15. package/dist/execution/engine.d.ts +11 -0
  16. package/dist/fhir-quantity-operator.d.ts +53 -0
  17. package/dist/fhir-translations.d.ts +5 -6
  18. package/dist/fhir.d.ts +233 -13
  19. package/dist/format.d.ts +113 -3
  20. package/dist/hpsg/constructions.d.ts +113 -0
  21. package/dist/hpsg/defaults.d.ts +2 -0
  22. package/dist/hpsg/lexical-classes.d.ts +282 -2
  23. package/dist/hpsg/procedural-context.d.ts +18 -4
  24. package/dist/hpsg/projection.d.ts +38 -3
  25. package/dist/hpsg/rule-context.d.ts +117 -7
  26. package/dist/hpsg/rules/clinical-quantity-rules.d.ts +18 -0
  27. package/dist/hpsg/rules/condition-rules.d.ts +14 -0
  28. package/dist/hpsg/rules/core-rules.d.ts +32 -0
  29. package/dist/hpsg/rules/instruction-rules.d.ts +11 -1
  30. package/dist/hpsg/rules/prn-rules.d.ts +3 -1
  31. package/dist/hpsg/rules/timing-rules.d.ts +138 -8
  32. package/dist/hpsg/signature.d.ts +353 -5
  33. package/dist/hpsg/type-system.d.ts +16 -1
  34. package/dist/hpsg/unification.d.ts +4 -1
  35. package/dist/i18n.d.ts +39 -1
  36. package/dist/index.cjs +65539 -30893
  37. package/dist/index.d.ts +35 -7
  38. package/dist/index.js +65505 -30892
  39. package/dist/instruction-action-locale-adapter.d.ts +32 -3
  40. package/dist/instruction-action-terminology.d.ts +38 -3
  41. package/dist/instruction-concept-terminology.d.ts +8 -1
  42. package/dist/instruction-graph-fhir.d.ts +9 -3
  43. package/dist/instruction-graph.d.ts +85 -7
  44. package/dist/ir.d.ts +13 -2
  45. package/dist/lexer/surface-segmenter.d.ts +1 -1
  46. package/dist/lexer/surface.d.ts +1 -0
  47. package/dist/locale-detection.d.ts +3 -0
  48. package/dist/locales/course/en.d.ts +15 -0
  49. package/dist/locales/course/th.d.ts +12 -0
  50. package/dist/localization.d.ts +73 -0
  51. package/dist/maps.d.ts +24 -1
  52. package/dist/medication-condition.d.ts +42 -0
  53. package/dist/parser-state.d.ts +6 -2
  54. package/dist/parser.d.ts +5 -2
  55. package/dist/regimen/coordination-scope.d.ts +53 -0
  56. package/dist/regimen/grammar.d.ts +79 -0
  57. package/dist/regimen/parallel-course.d.ts +52 -0
  58. package/dist/regimen/planner.d.ts +19 -0
  59. package/dist/regimen/regimen.d.ts +70 -0
  60. package/dist/relation-terminology.d.ts +1 -0
  61. package/dist/schedule.d.ts +12 -5
  62. package/dist/stable-structure.d.ts +23 -1
  63. package/dist/timing-summary.d.ts +82 -1
  64. package/dist/types.d.ts +899 -40
  65. package/dist/unit-lexicon.d.ts +7 -0
  66. package/dist/utils/strength.d.ts +16 -0
  67. package/dist/utils/text.d.ts +3 -0
  68. package/dist/utils/units.d.ts +19 -0
  69. package/package.json +3 -2
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  ## Features
6
6
 
7
7
  - Converts shorthand strings (e.g. `1x3 po pc`, `500 mg po q6h prn pain`) into FHIR-compliant dosage JSON.
8
- - Parses multi-clause sigs into multiple dosage items (e.g. `OD ... , OS ...`) while preserving a first-item compatibility shape for legacy single-dose consumers.
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.
11
11
  - Outputs SNOMED CT route codings (while providing friendly text) and round-trips known SNOMED routes back into the parser.
@@ -37,12 +37,13 @@ import { parseSig } from "ezmedicationinput";
37
37
 
38
38
  const batch = parseSig("1x3 po pc", { context: { dosageForm: "tab" } });
39
39
 
40
- // New API
41
- console.log(batch.count); // 1
42
- console.log(batch.items[0].fhir);
40
+ // Individual clause and one FHIR Dosage
41
+ console.log(batch.count); // 1
42
+ console.log(batch.items[0].fhir); // Single FHIR dosage
43
43
 
44
- // Legacy compatibility (first parsed item)
45
- console.log(batch.fhir);
44
+ // Complete batch for multi-dose or phased instructions
45
+ console.log(batch.fhir); // EzDosage[]: flat R5-compatible rows
46
+ console.log(batch.fhirNext); // Current FHIR R6 DosageInstruction
46
47
  ```
47
48
 
48
49
  Example output:
@@ -68,23 +69,127 @@ Example output:
68
69
  }
69
70
  }
70
71
  ],
71
- "fhir": { "...": "same as items[0].fhir for compatibility" }
72
+ "fhir": [{ "doseAndRate": [{ "doseQuantity": { "value": 1, "unit": "tab" } }] }]
72
73
  }
73
74
  ```
74
75
 
75
- ### Multi-clause parsing and legacy compatibility
76
+ ### Batch dosage output
77
+
78
+ `parseSig` and `parseSigAsync` return one batch result containing:
79
+
80
+ - `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`: native FHIR R6 `DosageInstruction`, with sequential steps and concurrent dosing components.
84
+ - `meta.segments`: source ranges for each clause.
85
+ - `shortText`, `longText`, `warnings`, and `meta`: batch-level display and diagnostics.
86
+
87
+ Use `items[0].fhir` when displaying or editing a single dosage, and
88
+ `batch.fhir` when processing the complete flat prescription.
89
+ `formatSig` and `fromFhirDosage` accept one dosage; `formatSigBatch`
90
+ accepts an array of dosages.
91
+
92
+ The R5 array under `fhir` remains the compatibility/editing surface.
93
+ The `fhirNext` object follows the **pinned HL7 R6 CI build dated November 13, 2026**,
94
+ whose profiles use the version label `6.0.0-snapshot1`. The
95
+ [checked-in contract](fhir/r6/official-snapshot1-20261113-contract.json) records
96
+ the supported schema: `DosageInstruction.step[].component[]` contains R6
97
+ `Dosage` values. Use `fromFhir(fhirNext)` to import that structure.
98
+ The [published September 2026 snapshot](https://www.hl7.org/fhir/6.0.0-snapshot1/dosage.html)
99
+ uses the same version label but defines `DosageDetails`; that schema is not a
100
+ supported interchange target. The importer checks the current structural
101
+ contract, not a datatype name or release tag absent from the JSON. Objects in
102
+ the structural overlap are accepted, including text-only `renderedInstruction`
103
+ objects and structured dosages using shared fields. Acceptance does not identify
104
+ which release produced the object or add support for the September schema.
105
+ TypeScript callers of the earlier R6 draft should replace `FhirR6DosageDetails`
106
+ with `FhirR6DosageInstruction`. Its `step` property is optional, matching the
107
+ current wire contract:
76
108
 
77
- `parseSig` / `parseSigAsync` return a **batch** object:
109
+ ```ts
110
+ import type { FhirR6DosageInstruction } from "ezmedicationinput";
78
111
 
79
- - `count`: number of parsed dosage clauses
80
- - `items`: array of full parse results (one per clause)
81
- - `meta.segments`: source ranges for each clause
112
+ function firstStepComponents(instruction: FhirR6DosageInstruction) {
113
+ return instruction.step?.[0]?.component ?? [];
114
+ }
115
+ ```
82
116
 
83
- For single-dose integrations that haven't migrated yet, the batch also keeps legacy first-item fields:
117
+ Empty R6 step lists are omitted on output. For a header containing only shared
118
+ Element metadata (such as an ID and unknown extensions), use the explicit
119
+ `fromFhir` boundary; mixed R5/R6 dispatch cannot infer a version from those fields.
120
+ The R5 editing/export APIs are unchanged; the current reader accepts previously
121
+ saved R5 rows without a downstream storage migration. New exports encode an
122
+ approximation on `SimpleQuantity` using the EMA quantity-operator coding. The
123
+ current reader accepts both that encoding and the older package comparator
124
+ child. Older package readers may not recover `~` from a new export; this is not
125
+ a guarantee that an older reader can interpret every newer extension encoding.
126
+
127
+ A phase beginning on the day after the preceding phase uses an application-owned
128
+ `step.start.contextCode`: system
129
+ `urn:ezmedicationinput:CodeSystem:course-phase-event`, code
130
+ `previous-phase-next-day`. It names local midnight following the predecessor's
131
+ last occupied treatment day. The scheduler derives that date from the completed
132
+ phase, including admitted doses and administration durations, so delayed starts,
133
+ count limits, and daylight-saving changes retain their meaning. Any supplied
134
+ `offsetDuration` or exact `offsetRange` is applied from that midnight. The
135
+ relation binds to the current preceding step in the ordered course. Reordering or
136
+ removing a step changes that predecessor; a first step has no predecessor and
137
+ leaves the relation unresolved.
138
+ The existing R5 course metadata preserves this boundary and its annotations
139
+ through saves. Patient-facing wording comes from the course language facet.
140
+
141
+ ### R5 clocks alongside event-based timing
142
+
143
+ For mixed schedules such as `1 tab with meals and @ 10:00`, the R5
144
+ `Timing.repeat.when` retains the meal event. Additional clocks are stored in
145
+ `Timing.repeat.extension` under
146
+ `urn:ezmedicationinput:StructureDefinition:medication-timing-additional-clock`.
147
+ Read each matching extension's `valueTime`; `_valueTime` holds its optional
148
+ primitive metadata. Do not rely only on `repeat.timeOfDay` to recover clocks
149
+ from a mixed R5 schedule.
84
150
 
85
- - `fhir`, `shortText`, `longText`, `warnings`, `meta`, and for linting `result`/`issues`
151
+ ```json
152
+ {
153
+ "repeat": {
154
+ "when": ["C"],
155
+ "extension": [{
156
+ "url": "urn:ezmedicationinput:StructureDefinition:medication-timing-additional-clock",
157
+ "valueTime": "10:00:00"
158
+ }]
159
+ }
160
+ }
161
+ ```
86
162
 
87
- So existing code that expects one result can continue using first-item compatibility while newer code uses `items[]`.
163
+ ### Internal native clinical model (unstable)
164
+
165
+ **INTERNAL USE ONLY — NOT A BACKWARD-COMPATIBLE API OR PERSISTENCE FORMAT.**
166
+ `CanonicalCourse`, `CanonicalStage`, `CanonicalAdministration`, their
167
+ nested clinical types, `meta.canonical`, and the native
168
+ import/project/format helpers are implementation surfaces for EZMED
169
+ development. **Their structures, identities, field names, invariants, and
170
+ function signatures may be changed or removed at any time without
171
+ deprecation, migration, compatibility adapters, or support for earlier
172
+ internal shapes.** This remains true even where TypeScript types or helper
173
+ functions are currently exported from the package. Do not persist these
174
+ objects, build downstream integrations against them, or assume one version
175
+ can load another version's internal model.
176
+
177
+ **Only the documented external interchange contracts are compatibility
178
+ boundaries:** `.fhir` and the established R5 editing/persistence APIs
179
+ remain R5; `.fhirNext` and `fromFhir` use the *current supported* R6
180
+ structure, not obsolete R6 drafts. The internal model is deliberately free
181
+ to evolve for maximum clinical expressiveness, performance, and
182
+ maintainability; no old internal representation must be retained.
183
+
184
+ Native courses are parser implementation data. EZMED does not expose a native
185
+ editing workflow. Parser and projection outputs, including borrowed provider
186
+ listings, are immutable by caller contract; ordinary imports do not deep-clone
187
+ or freeze them defensively. Instruction action and concept vocabulary lookups
188
+ and listings also return borrowed immutable definitions.
189
+ Applications that modify external R5 or current R6 data pass those values back
190
+ through the corresponding import boundary. Native scheduling, formatting, and
191
+ supply consume clinical facts directly; the R5 reconciliation bridge is confined
192
+ to R5 persistence and interchange.
88
193
 
89
194
  ### PRN reasons & additional instructions
90
195
 
@@ -94,7 +199,7 @@ codes them with SNOMED CT whenever possible.
94
199
  ```ts
95
200
  const result = parseSig("1 tab po q4h prn headache; do not exceed 6 tabs/day");
96
201
 
97
- result.fhir.asNeededFor;
202
+ result.items[0].fhir.asNeededFor;
98
203
  // → [{
99
204
  // text: "headache",
100
205
  // coding: [{
@@ -104,7 +209,7 @@ result.fhir.asNeededFor;
104
209
  // }]
105
210
  // }]
106
211
 
107
- result.fhir.additionalInstruction;
212
+ result.items[0].fhir.additionalInstruction;
108
213
  // → [{ text: "Do not exceed 6 tablets daily" }]
109
214
  ```
110
215
 
@@ -235,6 +340,79 @@ Highlights:
235
340
  without imposing timing-sensitive test thresholds.
236
341
 
237
342
 
343
+ ## Extending course realization to another language
344
+
345
+ **Internal extension example:** the native course-realization facet and its
346
+ clinical-model inputs are not a versioned third-party plugin contract.
347
+ They may be restructured along with the internal model, without preserving
348
+ previous facet shapes. Future language packs should depend on language
349
+ boundaries and shared clinical semantics rather than pinning a historic
350
+ `CanonicalCourse` layout.
351
+
352
+ Whole-course wording is a typed optional `course` facet on the existing
353
+ `SigLocalization` registration. It complements the same `formatShort` and
354
+ `formatLong` clause hooks—there is no separate registry or second parser.
355
+
356
+ The `formatLong` callback receives the complete clause, `defaultText`, and
357
+ `formatDefault(style)`. Its returned string is the final clause wording: custom
358
+ formatters may wrap or replace the whole clause and are responsible for that
359
+ wording. Defaults use the resolved locale and include the clause's native timing
360
+ qualifiers, authored directions, and independent advice. Built-in defaults compose
361
+ medication conditions and independent advice from typed facts.
362
+
363
+ ```ts
364
+ import {
365
+ importCanonicalCourse,
366
+ FhirPeriodUnit,
367
+ registerSigLocalization,
368
+ resolveSigLocalization,
369
+ formatCanonicalCourse,
370
+ } from "ezmedicationinput";
371
+
372
+ const english = resolveSigLocalization("en")!;
373
+ registerSigLocalization({
374
+ locale: "example",
375
+ formatShort: ({ defaultText }) => defaultText,
376
+ formatLong: ({ defaultText }) => defaultText,
377
+ course: {
378
+ ...english.course!,
379
+ dayRange: (first, last) => `Jours ${first}–${last}`,
380
+ noDoseDays: (first, last) => `Pause ${first}–${last}.`,
381
+ rateLabel: "Débit: ",
382
+ unspecified: "non spécifié",
383
+ },
384
+ });
385
+
386
+ // An explicit treatment-day window uses both clause and course wording.
387
+ const treatmentDayStart = { coding: [{
388
+ system: "urn:ezmedicationinput:CodeSystem:course-phase-event", code: "treatment-day-start",
389
+ }] };
390
+ const nativeCourse = importCanonicalCourse({ step: [{
391
+ start: { contextCode: treatmentDayStart, offsetDuration: { value: 0, unit: "d" } },
392
+ end: { contextCode: treatmentDayStart, offsetDuration: { value: 3, unit: "d" } },
393
+ component: [{
394
+ doseAndRate: [{ doseQuantity: { value: 1, unit: "tab" } }],
395
+ timing: { repeat: { frequency: 1, period: 1, periodUnit: FhirPeriodUnit.Day } },
396
+ }],
397
+ }] });
398
+ const text = formatCanonicalCourse(nativeCourse, "long", {
399
+ locale: "example", realizationMode: "normalized",
400
+ });
401
+ // text includes "Jours 1–3" from the registered course.dayRange callback.
402
+ ```
403
+
404
+ A full language implementation supplies its own clause hooks and course facet;
405
+ the example deliberately inherits the other English strings. Course templates
406
+ receive resolved counts, intervals, unit codes, predicates and stage windows.
407
+ They do not change clinical scope, calculate dates, choose a treatment branch,
408
+ or reinterpret dose numbers. `i18n.inherit`/`i18n.course` can inherit or override
409
+ the facet using the existing per-call configuration.
410
+
411
+ Adding course wording alone does **not** add parsing or autocomplete in that
412
+ language. Lexer, relation/action terminology and suggestion registrations keep
413
+ their existing roles. This boundary lets a future language-pack installer group
414
+ those registrations without changing the shared clinical engine.
415
+
238
416
  ## Formal HPSG substrate
239
417
 
240
418
  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.
@@ -251,7 +429,7 @@ The HPSG chart uses packed semantic state, an indexed agenda, and a compatible s
251
429
 
252
430
  FHIR cannot represent zero as `Timing.repeat.frequency` because the primitive is positive; a package-owned extension preserves an explicit lower bound of zero while `frequencyMax`, `period`, and `periodUnit` remain standard fields:
253
431
 
254
- `https://solublelabs.com/fhir/StructureDefinition/medication-timing-frequency-min`
432
+ `urn:ezmedicationinput:StructureDefinition:medication-timing-frequency-min`
255
433
 
256
434
  ## Procedural instruction semantics and opaque-span enrichment
257
435
 
@@ -343,7 +521,7 @@ import { parseSig } from "ezmedicationinput";
343
521
 
344
522
  const result = parseSig("apply cream to left arm twice daily");
345
523
 
346
- result.fhir.site?.coding?.[0];
524
+ result.items[0].fhir.site?.coding?.[0];
347
525
  // → { system: "http://snomed.info/sct", code: "368208006", display: "Left upper arm structure" }
348
526
  ```
349
527
 
@@ -353,7 +531,7 @@ and in `ParseResult.meta.normalized.site.spatialRelation`.
353
531
  ```ts
354
532
  const result = parseSig("apply to area between fingers");
355
533
 
356
- result.fhir.site?.text;
534
+ result.items[0].fhir.site?.text;
357
535
  // → "area between fingers"
358
536
 
359
537
  result.meta.normalized.site?.spatialRelation;
@@ -783,22 +961,35 @@ Key rules:
783
961
  - Pure frequency schedules (`BID`, `TID`, etc.) fall back to clinic-defined institution times.
784
962
  - All timestamps are emitted as ISO strings that include the clinic time-zone offset.
785
963
 
964
+ Timezone-aware scheduling and supply require `Intl.DateTimeFormat.prototype.formatToParts` and support for the requested IANA time zone.
965
+
786
966
  `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.
787
967
 
788
968
  ### Medication amount calculation
789
969
 
790
- `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.
970
+ `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.
971
+
972
+ Ranged supply with interacting limits uses a bounded exact calculation.
973
+ Successful calls return a `TotalUnitsResult`. When the calculation cannot provide
974
+ an exact attainable maximum, it throws `MedicationQuantityCalculationError`;
975
+ catch the exception and inspect its `code`. For `ranged-capacity-complexity`,
976
+ use a shorter supply window or supply a resolved per-administration quantity.
977
+ For `ranged-capacity-open-maximum`, a strict range has a finite supremum but
978
+ no attainable maximum; the prescriber can resolve the dose or provide a closed
979
+ range before requesting a numeric maximum. These exceptions affect supply
980
+ calculation only. The structured instruction and source remain available for
981
+ parsing, display, persistence, and correction.
791
982
 
792
983
  ```ts
793
- import { calculateTotalUnits, parseSig } from "ezmedicationinput";
984
+ import { calculateTotalUnits, parseSig, FhirPeriodUnit } from "ezmedicationinput";
794
985
 
795
- const { fhir } = parseSig("1x3 po pc");
986
+ const { fhir } = parseSig("1 tab PO TID after meals");
796
987
 
797
988
  const result = calculateTotalUnits({
798
989
  dosage: fhir,
799
990
  from: "2024-01-01T08:00:00Z",
800
991
  durationValue: 7,
801
- durationUnit: "d",
992
+ durationUnit: FhirPeriodUnit.Day,
802
993
  timeZone: "Asia/Bangkok",
803
994
  context: {
804
995
  containerValue: 30, // 30 tabs per bottle
@@ -820,7 +1011,7 @@ calculateTotalUnits({
820
1011
  dosage: parsed.fhir,
821
1012
  from: "2024-01-01T08:00:00Z",
822
1013
  durationValue: 7,
823
- durationUnit: "d",
1014
+ durationUnit: FhirPeriodUnit.Day,
824
1015
  timeZone: "Asia/Bangkok"
825
1016
  });
826
1017
 
@@ -855,16 +1046,19 @@ parseStrength("1%", { dosageForm: "cream" });
855
1046
  parseStrength("250mg/5mL");
856
1047
  // → { strengthRatio: { numerator: { value: 250, unit: "mg" }, denominator: { value: 5, unit: "mL" } } }
857
1048
 
858
- // Composite (sums components into a single ratio)
1049
+ // Composite (preserves each ingredient separately)
859
1050
  parseStrength("875mg + 125mg");
860
- // → { strengthQuantity: { value: 1000, unit: "mg" } }
1051
+ // → { strengthComponents: [
1052
+ // { strengthQuantity: { value: 875, unit: "mg" } },
1053
+ // { strengthQuantity: { value: 125, unit: "mg" } }
1054
+ // ] }
861
1055
 
862
1056
  // Simple Quantity
863
1057
  parseStrength("500mg");
864
1058
  // → { strengthQuantity: { value: 500, unit: "mg" } }
865
1059
  ```
866
1060
 
867
- `parseStrengthIntoRatio` is also available if you specifically need a FHIR Ratio object regardless of the denominator.
1061
+ `parseStrengthIntoRatio` is also available when you need a FHIR Ratio for one ingredient; it returns `null` for composite strengths.
868
1062
 
869
1063
  ### Ocular & intravitreal shortcuts
870
1064
 
@@ -0,0 +1,128 @@
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, 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): 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
+ /** Direct native-to-R6 component writer. */
60
+ /** Emit native R6 directly from modeled clinical facts. Shared serializers
61
+ * encode vocabulary and grammar-source annotations only, never an R5 course. */
62
+ export declare function administrationToR6(a: CanonicalAdministration, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirR6Dosage;
63
+ /** Direct native-to-R5 component writer. No R6 component is constructed. */
64
+ export declare function administrationToR5(a: CanonicalAdministration, sequence: number | undefined, options?: FhirProjectionOptions, currentSyntax?: CanonicalSigClause): FhirDosage;
65
+ /** Header/step metadata is shared fragment serialization, NOT a course in
66
+ * another external format. The R5 writer encodes it directly in R5 extensions. */
67
+ export declare function courseMetadataToWire(course: CanonicalCourse): Omit<FhirR6DosageInstruction, "step" | "renderedInstruction">;
68
+ /** Native typed facts come from metadata fragments, not from a whole other
69
+ * external course. Foreign annotations are kept on the source envelope. */
70
+ export declare function stageFromFields(fields: Omit<FhirR6DosageStep, "component">, members: CanonicalAdministration[]): CanonicalStage;
71
+ export declare function stageMetadataToWire(stage: CanonicalStage): Omit<FhirR6DosageStep, "component">;
72
+ /** Ordinary native export must derive source-annotation views from current
73
+ * native fields because callers may have edited them. */
74
+ export declare function courseToR6(course: CanonicalCourse, options?: FhirProjectionOptions): FhirR6DosageInstruction;
75
+ /** Parser construction-only export: the caller has JUST compiled these exact
76
+ * clauses and has not exposed them for edits. Reusing their annotation views
77
+ * avoids rebuilding every canonical clause merely to write its first output.
78
+ * This is not a persistent cache and is never used for public edited exports. */
79
+ export declare function projectFreshlyCompiledCourseToR6(course: CanonicalCourse, options?: FhirProjectionOptions): FhirR6DosageInstruction;
80
+ export declare function courseToR5(course: CanonicalCourse): FhirDosage[];
81
+ /** Source-only R6 instructions have no structured administration to preview.
82
+ * A nonempty header on a structured import is original text, not evidence
83
+ * that its dose/timing still agrees with the independently editable fields. */
84
+ export declare function unchangedR6SourceDisplay(raw: FhirR6DosageInstructionInput, options?: FormatOptions): string | undefined;
85
+ /** Explicit editable import for applications that already hold R5 rows.
86
+ * Import normalization and persistence reconciliation happen once here, not
87
+ * inside any native edit, formatter, or execution operation. Metadata-only
88
+ * R6 headers share R5's Element shape; use fromFhir for that known-R6 input. */
89
+ export declare function importCanonicalCourse(input: FhirDosage | readonly FhirDosage[] | FhirR6DosageInstructionInput | ParseBatchResult | CanonicalCourse): CanonicalCourse;
90
+ /**
91
+ * R6-only serialization of editable information that has no active core slot.
92
+ * These annotations contain current FHIR fragments, never a persisted native
93
+ * model. Draft steps remain source data; a one-step safety projection records
94
+ * its original scope so an unchanged export can be reopened for editing.
95
+ */
96
+ export declare const R6_DRAFT_STEPS_SOURCE_URL = "urn:ezmedicationinput:r6-draft-steps-source";
97
+ export declare const R6_SINGLE_STEP_SAFETY_SOURCE_URL = "urn:ezmedicationinput:r6-single-step-safety-source";
98
+ export declare const R6_SCOPED_SAFETY_MODIFIER_URL = "urn:ezmedicationinput:r6-scoped-safety-policy";
99
+ export declare function retainDraftSteps(output: FhirR6DosageInstruction, drafts: Array<{
100
+ index: number;
101
+ step: Omit<FhirR6DosageStep, "component">;
102
+ }> | undefined, synthesizedStarts?: number[]): void;
103
+ /** Restore inactive editable stages while their active phase owners and
104
+ * boundaries still agree. Current doses and other live fields stay current. */
105
+ export declare function editableCourseSteps(input: FhirR6DosageInstructionInput): FhirR6DosageStep[];
106
+ /** Indices from the current external draft source, for R5 membership edits. */
107
+ export declare function retainedDraftStepIndices(input: {
108
+ extension?: FhirR6Extension[];
109
+ }): readonly number[] | undefined;
110
+ interface LiftedSafety {
111
+ course?: FhirR6DosageSafety;
112
+ step: FhirR6DosageSafety;
113
+ projected: FhirR6DosageSafety;
114
+ ownerId?: string;
115
+ ownerComponentIds?: string[];
116
+ ownerFingerprint?: string;
117
+ /** Resolved current wire owner; never part of the serialized source record. */
118
+ owner?: FhirR6DosageStep;
119
+ }
120
+ /** Only a matching live policy can reuse its saved scope. A later wire edit
121
+ * replaces that authority rather than reviving an old safety instruction. */
122
+ export declare function retainedSingleStepSafety(input: FhirR6DosageInstructionInput): LiftedSafety | undefined;
123
+ export declare function liftSingleStepSafety(output: FhirR6DosageInstruction): void;
124
+ /** Conflicting externally edited choices have no single active clinical meaning.
125
+ * Keep every submitted value in typed source data, leaving the independent
126
+ * dose/rate dimension available without inventing a winner for the conflict. */
127
+ export declare function retainConflictingAmountChoices(amount: Record<string, unknown>, doseConflict: boolean, rateConflict: boolean): void;
128
+ export {};
@@ -0,0 +1,24 @@
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 } from "../types";
10
+ import type { CanonicalCourse } from "../canonical/course";
11
+ import type { FhirProjectionOptions } from "../fhir";
12
+ import { type DosageSourceTextBaseline } from "../dosage-course";
13
+ /** Native course metadata is serialized once into its FINAL R5 extension
14
+ * header. Step/member loops write direct rows and their local retained fields.
15
+ * No R6 object is built, flattened, imported, or used as an adapter input. */
16
+ export declare function projectNativeR5Course(course: CanonicalCourse, options?: FhirProjectionOptions, editable?: boolean, freshlyCompiled?: boolean, attachInstruction?: boolean, strictPreview?: boolean, suppliedRows?: readonly (FhirDosage | EzDosage)[], deferSourceProvenance?: boolean): {
17
+ dosages: EzDosage[];
18
+ course: EzCourseMetadata;
19
+ strictDosages?: FhirDosage[];
20
+ sourceBaselines?: readonly (DosageSourceTextBaseline | undefined)[];
21
+ };
22
+ export declare function courseFromR5(dosages: readonly (FhirDosage | EzDosage)[], renderedInstruction?: string, course?: EzCourseMetadata, options?: {
23
+ resolvedPhaseSequences?: readonly number[];
24
+ }, sourceContext?: boolean, classifiedCarriers?: Set<number>): CanonicalCourse;
package/dist/advice.d.ts CHANGED
@@ -1,4 +1,24 @@
1
- import { AdditionalInstructionDefinition, AdviceForce, AdviceFrame, FhirCoding, TextRange } from "./types";
1
+ import { AdditionalInstructionDefinition, AdviceArgument, AdviceForce, AdviceFrame, FhirCoding, TextRange } from "./types";
2
+ /** Directed clinical Coding identity; presentation and Element annotations stay on their owner. */
3
+ export declare function preservesAdviceCoding(selected: FhirCoding | undefined, actual: FhirCoding | undefined): boolean;
4
+ export declare function preservesAdviceCodings(selected: readonly FhirCoding[] | undefined, actual: readonly FhirCoding[] | undefined): boolean;
5
+ export declare function preservesAdviceComponents(selected: readonly {
6
+ role: string;
7
+ text?: string;
8
+ coding?: FhirCoding;
9
+ }[] | undefined, actual: readonly {
10
+ role: string;
11
+ text?: string;
12
+ coding?: FhirCoding;
13
+ }[] | undefined): boolean;
14
+ /** Text, source spans and retained Element annotations are not typed argument facts. */
15
+ export declare function hasAdviceArgumentFacts(argument: AdviceArgument): boolean;
16
+ export declare function preservesAdviceArgumentFacts(selected: AdviceArgument, actual: AdviceArgument): boolean;
17
+ /**
18
+ * Preserve selected typed facts while a caller licenses the same occurrence/head.
19
+ * Source/value correspondence and provisional opaque valence remain caller-owned.
20
+ */
21
+ export declare function preservesAdviceFrameFacts(selected: AdviceFrame, actual: AdviceFrame): boolean;
2
22
  export interface ParsedAdditionalInstruction {
3
23
  text?: string;
4
24
  coding?: FhirCoding & {
@@ -11,6 +31,28 @@ export interface AdviceParseContext {
11
31
  defaultForce?: AdviceForce;
12
32
  allowFreeTextFallback?: boolean;
13
33
  }
34
+ /**
35
+ * Resolve semantic qualifier codings from the COMPLETE composed action program.
36
+ * This is the existing structural matcher, with no string-based reparsing of
37
+ * clinical instructions after FHIR projection.
38
+ */
39
+ export declare function matchComposedAdviceCodings(frames: readonly AdviceFrame[]): AdditionalInstructionDefinition[];
40
+ /** Determine whether a rule's coding must be rechecked against scoped HPSG frames. */
41
+ export declare function adviceCodingNeedsComposedScope(system: string, code: string): boolean;
42
+ /**
43
+ * Retain the existing coding matcher's exact supporting action objects for
44
+ * occurrence-aware realization. Clinical coding and wording remain with their
45
+ * existing owners; no action identity is reconstructed from rendered text.
46
+ */
47
+ export declare function composedCodedAdviceActions(frames: readonly AdviceFrame[], coding: Pick<FhirCoding, "system" | "code"> | undefined): AdviceFrame[];
48
+ /** Existing advice terminology supplies manner modifiers to the main action
49
+ * grammar. It is lexical evidence, not a second clause parser. */
50
+ export declare function resolveAdviceMannerModifier(surface: string): {
51
+ lemma: string;
52
+ i18n?: Record<string, string>;
53
+ } | undefined;
54
+ /** Exact advice nominals share their existing lexical identity with action arguments. */
55
+ export declare function resolveAdviceNominalArgument(surface: string, sourceText?: string): AdviceArgument | undefined;
14
56
  export declare function realizeAdviceFramesText(frames: AdviceFrame[], locale?: string): string | undefined;
15
57
  export declare function parseAdditionalInstructions(sourceText: string, span: TextRange, context?: AdviceParseContext): ParsedAdditionalInstruction[];
16
58
  export declare function findAdditionalInstructionDefinitionByCoding(system: string, code: string): AdditionalInstructionDefinition | undefined;
@@ -23,4 +65,13 @@ export declare const __test__: {
23
65
  thai: string;
24
66
  }): AdditionalInstructionDefinition;
25
67
  };
68
+ /** Keep authored wording when the selected advice identity has no display. */
69
+ export declare function additionalInstructionFallbackText(concept: {
70
+ text?: string;
71
+ coding?: readonly {
72
+ display?: string;
73
+ }[];
74
+ }, selectedCoding: {
75
+ display?: string;
76
+ } | undefined): string | undefined;
26
77
  export declare function buildAdditionalInstructionFramesFromCoding(system: string, code: string, sourceText?: string, span?: TextRange): AdviceFrame[] | undefined;
@@ -1,4 +1,4 @@
1
- import { BodySiteDefinition, BodySiteSpatialRelation, FhirCoding } from "./types";
1
+ import { BodySiteDefinition, BodySiteSpatialRelation, FhirCoding, type BodySiteRestriction, type BodySiteRestrictionPredicate, type TextRange } from "./types";
2
2
  import type { BodySiteLocativeRelation } from "./relation-terminology";
3
3
  export type BodySiteGrammarKind = "nominal" | "partitive" | "locative";
4
4
  export type { BodySiteLocativeRelation };
@@ -49,6 +49,11 @@ export interface ResolvedBodySitePhrase {
49
49
  definition?: BodySiteDefinition;
50
50
  features: BodySiteFeatureStructure;
51
51
  englishObjectText: string;
52
+ /** Composed localization of clinical qualifier + known nominal head.
53
+ * It deliberately grants no code to a qualified site merely because its
54
+ * unqualified anatomy is coded. */
55
+ siteI18n?: Record<string, string>;
56
+ restrictions?: BodySiteRestriction[];
52
57
  preferredPreposition?: "to" | "at" | "in" | "into";
53
58
  }
54
59
  export interface BodySitePhraseContext {
@@ -56,4 +61,32 @@ export interface BodySitePhraseContext {
56
61
  allowTerminalModifierInheritance?: boolean;
57
62
  }
58
63
  export declare function lookupBodySiteDefinition(map: Record<string, BodySiteDefinition> | undefined, canonical: string): BodySiteDefinition | undefined;
64
+ /** One lexical interpretation for standalone and clause-level site predicates.
65
+ * Introducers and terminology are resolved here once, never in FHIR lowering.
66
+ * @param text Predicate surface text, excluding the relation marker.
67
+ * @param range Optional original-source span owned by the lexical sign.
68
+ */
69
+ export declare function resolveBodySiteRestrictionPredicate(text: string, range: TextRange): BodySiteRestrictionPredicate & {
70
+ range: TextRange;
71
+ };
72
+ export declare function resolveBodySiteRestrictionPredicate(text: string, range?: TextRange): BodySiteRestrictionPredicate;
73
+ /** Construct the same typed relative clause for either entrypoint. Full-SIG
74
+ * attachment remains the HPSG head-adjunct construction's responsibility.
75
+ * @param predicate Already interpreted lexical predicate.
76
+ * @param markerRange Original span of the relative marker.
77
+ * @param sourceText Original complete relative clause, when available.
78
+ */
79
+ export declare function formBodySiteRestriction(predicate: BodySiteRestrictionPredicate, markerRange?: TextRange, sourceText?: string): BodySiteRestriction;
80
+ /** Realize a typed restriction by lexical identity, never by re-parsing prose.
81
+ * @param restriction Typed site-local relative clause.
82
+ * @param locale English or Thai output locale.
83
+ */
84
+ export declare function realizeBodySiteRestriction(restriction: BodySiteRestriction, locale: "en" | "th"): string | undefined;
59
85
  export declare function resolveBodySitePhrase(text: string, customSiteMap?: Record<string, BodySiteDefinition>, context?: BodySitePhraseContext): ResolvedBodySitePhrase | undefined;
86
+ /** Anatomical vocabulary lookup only. Full-SIG lexical rules use this entrypoint
87
+ * so a lexical site cannot independently absorb a relative clause.
88
+ * @param text Anatomical constituent selected by the caller's grammar.
89
+ * @param customSiteMap Registered anatomy and custom terminology.
90
+ * @param context Contextual anatomy/terminal-modifier lookup options.
91
+ */
92
+ export declare function resolveBodySiteLexeme(text: string, customSiteMap?: Record<string, BodySiteDefinition>, context?: BodySitePhraseContext): ResolvedBodySitePhrase | undefined;
@@ -75,6 +75,9 @@ export declare function lookupBodySite(input: string, options?: BodySiteLookupOp
75
75
  export declare function lookupBodySiteAsync(input: string, options?: BodySiteLookupOptions): Promise<BodySiteLookupResult | undefined>;
76
76
  export declare function getBodySiteCode(input: string, options?: BodySiteLookupOptions): BodySiteCode | undefined;
77
77
  export declare function getBodySiteCodeAsync(input: string, options?: BodySiteLookupOptions): Promise<BodySiteCode | undefined>;
78
+ /** Realize an already selected laterality with the existing anatomical text owner.
79
+ * Internal consumers must establish anatomical compatibility before calling. */
80
+ export declare function bodySiteTextWithLaterality(text: string, lateralityCode: string): string | undefined;
78
81
  export declare function getBodySiteText(input: BodySiteCodeInput, options?: BodySiteTextOptions): string | undefined;
79
82
  export declare function getBodySiteTextAsync(input: BodySiteCodeInput, options?: BodySiteTextOptions): Promise<string | undefined>;
80
83
  export declare function suggestBodySites(input: string, options?: BodySiteLookupOptions): BodySiteLookupResult[];