ezmedicationinput 0.2.0 → 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 (61) hide show
  1. package/README.md +201 -10
  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 +36 -5
  5. package/dist/body-site-lookup.d.ts +3 -0
  6. package/dist/body-site-spatial.d.ts +6 -2
  7. package/dist/body-site-target.d.ts +9 -3
  8. package/dist/canonical/compile.d.ts +79 -0
  9. package/dist/canonical/course.d.ts +352 -0
  10. package/dist/canonical/format-course.d.ts +36 -0
  11. package/dist/dosage-course.d.ts +294 -29
  12. package/dist/execution/calendar.d.ts +107 -0
  13. package/dist/execution/engine.d.ts +11 -0
  14. package/dist/fhir-quantity-operator.d.ts +53 -0
  15. package/dist/fhir-translations.d.ts +5 -6
  16. package/dist/fhir.d.ts +99 -14
  17. package/dist/format.d.ts +105 -3
  18. package/dist/hpsg/constructions.d.ts +11 -3
  19. package/dist/hpsg/defaults.d.ts +2 -0
  20. package/dist/hpsg/lexical-classes.d.ts +115 -4
  21. package/dist/hpsg/procedural-context.d.ts +3 -3
  22. package/dist/hpsg/projection.d.ts +28 -1
  23. package/dist/hpsg/rule-context.d.ts +104 -7
  24. package/dist/hpsg/rules/clinical-quantity-rules.d.ts +16 -7
  25. package/dist/hpsg/rules/condition-rules.d.ts +0 -1
  26. package/dist/hpsg/rules/core-rules.d.ts +3 -0
  27. package/dist/hpsg/rules/instruction-rules.d.ts +2 -0
  28. package/dist/hpsg/rules/prn-rules.d.ts +3 -1
  29. package/dist/hpsg/rules/timing-rules.d.ts +17 -1
  30. package/dist/hpsg/signature.d.ts +13 -3
  31. package/dist/hpsg/unification.d.ts +3 -1
  32. package/dist/i18n.d.ts +37 -1
  33. package/dist/index.cjs +63500 -46393
  34. package/dist/index.d.ts +21 -9
  35. package/dist/index.js +63491 -46393
  36. package/dist/instruction-action-locale-adapter.d.ts +31 -3
  37. package/dist/instruction-action-terminology.d.ts +23 -3
  38. package/dist/instruction-concept-terminology.d.ts +7 -0
  39. package/dist/instruction-graph-fhir.d.ts +8 -2
  40. package/dist/instruction-graph.d.ts +80 -38
  41. package/dist/ir.d.ts +1 -1
  42. package/dist/lexer/surface-segmenter.d.ts +1 -1
  43. package/dist/lexer/surface.d.ts +1 -0
  44. package/dist/locale-detection.d.ts +3 -0
  45. package/dist/locales/course/en.d.ts +15 -0
  46. package/dist/locales/course/th.d.ts +12 -0
  47. package/dist/localization.d.ts +73 -0
  48. package/dist/maps.d.ts +10 -2
  49. package/dist/medication-condition.d.ts +1 -1
  50. package/dist/parser-state.d.ts +2 -2
  51. package/dist/regimen/grammar.d.ts +11 -0
  52. package/dist/regimen/parallel-course.d.ts +8 -41
  53. package/dist/regimen/regimen.d.ts +6 -2
  54. package/dist/relation-terminology.d.ts +1 -0
  55. package/dist/schedule.d.ts +14 -10
  56. package/dist/timing-summary.d.ts +82 -1
  57. package/dist/types.d.ts +510 -56
  58. package/dist/unit-lexicon.d.ts +7 -0
  59. package/dist/utils/text.d.ts +3 -0
  60. package/dist/utils/units.d.ts +19 -0
  61. package/package.json +1 -1
@@ -1,4 +1,11 @@
1
- import { FhirDayOfWeek, FhirDosage, FhirR6Dosage, FhirR6DosageDetails, MedicationCondition, EzDosage, EzCourseMetadata } from "./types";
1
+ import { FhirDayOfWeek, FhirDosage, FhirExtension, FhirR6Extension, FhirQuantity, FhirR6Dosage, FhirR6DosageCondition, FhirR6DosageInstruction, FhirR6DosageStep, FhirR6DosageInstructionInput, FhirR6DosageSafety, FhirR6TimingRepeat, MedicationCondition, EzDosage, EzCourseMetadata, EzCourseStep } from "./types";
2
+ /** R5 and R6 tim-8 requires the lower-count Element beside countMax, not a numeric
3
+ * minimum. Preserve authored companions; an absent minimum remains unknown. */
4
+ export declare function withTimingCountMinimum<T extends Pick<FhirR6TimingRepeat, "count" | "countMax" | "_count">>(repeat: T): T;
5
+ /** R5 and R6 tim-7 requires a lower-duration Element, without inventing a numeric bound. */
6
+ export declare function withTimingDurationMinimum<T extends Pick<FhirR6TimingRepeat, "duration" | "durationMax" | "_duration">>(repeat: T): T;
7
+ /** R5 and R6 tim-6 requires a lower-period Element, without inventing a numeric cadence. */
8
+ export declare function withTimingPeriodMinimum<T extends Pick<FhirR6TimingRepeat, "period" | "periodMax" | "_period">>(repeat: T): T;
2
9
  /** Modifier extensions: ignoring either can change whether a dose may be given. */
3
10
  export declare const DOSAGE_CONDITION_R5_URL = "urn:ezmedicationinput:StructureDefinition:medication-conditional-dose";
4
11
  /** Separate R6 DosageCondition-level extension: the R5 Dosage modifier has
@@ -6,6 +13,8 @@ export declare const DOSAGE_CONDITION_R5_URL = "urn:ezmedicationinput:StructureD
6
13
  export declare const DOSAGE_CONDITION_R6_LOGIC_URL = "urn:ezmedicationinput:StructureDefinition:medication-r6-condition-logic";
7
14
  export declare const DOSAGE_EXCLUDED_DATES_R5_URL = "urn:ezmedicationinput:StructureDefinition:medication-excluded-calendar-dates";
8
15
  export declare const DOSAGE_DETAILS_R5_URL = "urn:ezmedicationinput:StructureDefinition:medication-r6-course-details";
16
+ /** Keeps an expression-only R5 backbone element valid without inventing a dose. */
17
+ export declare const R5_EXPRESSION_SLOT_SOURCE_URL = "urn:ezmedicationinput:StructureDefinition:r5-expression-slot-source";
9
18
  /** Non-modifier metadata: preserves the author's entire literal instruction
10
19
  * without forcing ordinary R5 consumers to implement R6 safety semantics. */
11
20
  export declare const DOSAGE_RENDERED_INSTRUCTION_R5_URL = "urn:ezmedicationinput:StructureDefinition:medication-rendered-instruction";
@@ -13,6 +22,41 @@ export declare const DOSAGE_EXCLUDED_WEEKDAYS_R5_URL = "urn:ezmedicationinput:St
13
22
  /** Non-modifier provenance emitted when an editable R5 projection and its
14
23
  * retained R6 source cannot be merged one-to-one. */
15
24
  export declare const DOSAGE_RECONCILIATION_WARNING_URL = "urn:ezmedicationinput:StructureDefinition:medication-course-reconciliation-warning";
25
+ export { DOSAGE_RECONCILIATION_SOURCE_URL } from "./fhir-quantity-operator";
26
+ export declare const DOSAGE_RETAINED_R5_SEQUENCE_URL = "urn:ezmedicationinput:StructureDefinition:medication-retained-r5-sequence";
27
+ /** R6 doseAndRate is Element. Preserve any older R5-local metadata in the
28
+ * Element.extension slot without emitting illegal modifierExtension keys. */
29
+ export declare const R5_RATE_MODIFIERS_R6_URL = "urn:ezmedicationinput:StructureDefinition:r5-dose-and-rate-modifier-extensions";
30
+ /** The finite repetition count belongs to the complete treatment course.
31
+ * R6 step.count repeats one step; neither R5 nor R6 has a core course-count
32
+ * slot, so both boundary adapters share this narrow modifier extension. */
33
+ export declare const COURSE_CYCLE_COUNT_EXTENSION_URL = "urn:ezmedicationinput:StructureDefinition:medication-course-cycle-count";
34
+ type CourseCountField = Pick<FhirExtension, "url" | "valueInteger"> & {
35
+ _valueInteger?: unknown;
36
+ };
37
+ type CourseCountOwner = {
38
+ modifierExtension?: readonly CourseCountField[];
39
+ };
40
+ /** Null retains an authored primitive whose finite count is not known. */
41
+ export declare function getCourseCycleCount(owner: CourseCountOwner): number | null | undefined;
42
+ /** Write the current typed count while preserving unrelated modifiers and
43
+ * metadata on an existing recognized count annotation. Output owns writes. */
44
+ export declare function setCourseCycleCount(owner: {
45
+ modifierExtension?: FhirExtension[];
46
+ }, count: number | undefined): FhirExtension[] | undefined;
47
+ export declare function setCourseCycleCount(owner: {
48
+ modifierExtension?: FhirR6Extension[];
49
+ }, count: number | undefined): FhirR6Extension[] | undefined;
50
+ type ModifierWrapperOwner = {
51
+ extension?: FhirR6Extension[];
52
+ modifierExtension?: FhirR6Extension[];
53
+ };
54
+ /** Project the editable modifier owner on an already-owned output fragment.
55
+ * Step and doseAndRate share this Element boundary, including wrapper metadata. */
56
+ export declare function projectR6ModifierWrapper(output: ModifierWrapperOwner, url: string): void;
57
+ export declare function projectR5ModifierWrapper(output: ModifierWrapperOwner, url: string): void;
58
+ export declare function r6StepMetadata(step: Partial<EzCourseStep>): Omit<FhirR6DosageStep, "component">;
59
+ export declare function r5StepMetadata(step: Omit<FhirR6DosageStep, "component">): Omit<EzCourseStep, "sequence">;
16
60
  /** Treatment-relative phase origin for an independent parallel component. */
17
61
  export declare const PARALLEL_COMPONENT_PHASE_ORIGIN_URL = "urn:ezmedicationinput:StructureDefinition:medication-parallel-component-phase-origin";
18
62
  /** Local must-understand profile for exclusive administration choices.
@@ -30,13 +74,13 @@ export interface DosageAlternativeChoice {
30
74
  * @param dosage An R5 or R6 dosage carrying the same modifier-extension shape.
31
75
  * @returns Recognized membership, or undefined while unfamiliar data stays attached.
32
76
  */
33
- export declare function getDosageAlternativeChoice(dosage: Pick<FhirDosage, "modifierExtension">): DosageAlternativeChoice | undefined;
77
+ export declare function getDosageAlternativeChoice(dosage: Pick<FhirR6Dosage, "modifierExtension">): DosageAlternativeChoice | undefined;
34
78
  /** Assign membership already established by the typed regimen graph.
35
79
  * This does not choose a branch, deduce a group from wording, or add conditions.
36
80
  * @param dosage The editable R5 or R6 component to update.
37
81
  * @param choice Proven membership; undefined explicitly clears this modifier.
38
82
  */
39
- export declare function setDosageAlternativeChoice(dosage: Pick<FhirDosage, "modifierExtension">, choice: DosageAlternativeChoice | undefined): void;
83
+ export declare function setDosageAlternativeChoice(dosage: Pick<FhirR6Dosage, "modifierExtension" | "extension">, choice: DosageAlternativeChoice | undefined): void;
40
84
  /** Machine-readable declaration of the local alternative-choice modifier.
41
85
  * It is generated beside its only codec, avoiding a second copied schema or
42
86
  * an undocumented native FHIR field. Callers can publish/validate the returned
@@ -119,70 +163,291 @@ export declare function buildDosageAlternativeChoiceStructureDefinition(): {
119
163
  })[];
120
164
  };
121
165
  };
166
+ /** Generated copies may be consumed only when their typed predicate agrees. */
167
+ export declare function exactConditionBridgePredicate(extension: FhirExtension): MedicationCondition | undefined;
168
+ export declare function isExactConditionBridge(extension: FhirExtension): boolean;
122
169
  export declare function assertUnderstoodDosageModifiers(_dosage: FhirDosage | EzDosage): void;
123
- export declare function getDosageCondition(dosage: FhirDosage | EzDosage): MedicationCondition | undefined;
170
+ declare function parseDosageCondition(dosage: Pick<FhirR6Dosage, "modifierExtension"> & {
171
+ condition?: FhirR6DosageCondition[];
172
+ }): MedicationCondition | undefined;
173
+ export declare function getDosageCondition(dosage: Pick<FhirR6Dosage, "modifierExtension"> & {
174
+ condition?: FhirR6DosageCondition[];
175
+ }): MedicationCondition | undefined;
124
176
  /** A whole-day evaluation is licensed only for the same live predicate that
125
177
  * the source grammar identified as calendar membership. An edited native
126
178
  * condition or a mixed measurement/day predicate cannot inherit that claim.
127
179
  * @param dosage Native or R5 dosage with optional source-owned day-domain metadata.
128
180
  */
129
- export declare function getDosageCalendarDayCondition(dosage: FhirDosage | EzDosage): MedicationCondition | undefined;
181
+ export declare function getDosageCalendarDayCondition(dosage: FhirDosage | EzDosage | FhirR6Dosage): MedicationCondition | undefined;
130
182
  /** Encode the clinical predicate and its independently supplied day-domain type.
131
183
  * @param dosage Editable target dosage; other modifiers remain untouched.
132
184
  * @param condition Live clinical predicate, or undefined to clear it.
133
185
  * @param calendarDayCondition Source-certified whole-day predicate, never inferred from prose.
134
186
  */
135
187
  export declare function setDosageCondition(dosage: FhirDosage, condition: MedicationCondition | undefined, calendarDayCondition?: MedicationCondition): void;
136
- export declare function getDosageExcludedDates(dosage: FhirDosage | EzDosage): string[];
188
+ export declare function getDosageExcludedDates(dosage: FhirDosage | EzDosage | FhirR6Dosage): string[];
137
189
  export declare function setDosageExcludedDates(dosage: FhirDosage, dates: string[]): void;
138
- export declare function getDosageExcludedWeekdays(dosage: FhirDosage): FhirDayOfWeek[];
190
+ export declare function getDosageExcludedWeekdays(dosage: FhirDosage | FhirR6Dosage): FhirDayOfWeek[];
139
191
  export declare function setDosageExcludedWeekdays(dosage: FhirDosage, days: FhirDayOfWeek[]): void;
192
+ export declare function conditionToR6(condition: MedicationCondition): FhirR6DosageCondition;
193
+ declare function toR6Safety(dosage: FhirDosage, includePartialPeriods?: boolean): FhirR6DosageSafety | undefined;
194
+ /**
195
+ * Apply edits made through R5 maximum-dose fields without discarding safety
196
+ * semantics that R5 cannot carry. Existing backbone metadata stays attached
197
+ * to the corresponding representable scope; expression/integer limits and
198
+ * the safety-level exceeded action remain byte-for-byte authoritative.
199
+ */
200
+ export declare function reconcileR5SafetyEdits(retained: FhirR6DosageSafety, projected: FhirR6DosageSafety | undefined, baseline?: string, dose?: FhirQuantity): FhirR6DosageSafety | undefined;
201
+ /**
202
+ * Reconcile the two editable views of safety against the row's saved source.
203
+ * Explicit safety edits win. An unchanged lifted safety copy must not hide a
204
+ * changed/deleted R5 maximum; field-local merging retains R6-only limits and
205
+ * authored safety metadata. This runs only for rows with retained safety.
206
+ */
207
+ export declare function reconcileR5SafetySnapshot(row: EzDosage, retained: FhirR6DosageSafety, baseline: string | undefined): FhirR6DosageSafety | undefined;
208
+ export declare function reconcileLiftedR5Safety(row: EzDosage): FhirR6DosageSafety | undefined;
140
209
  /** Lift real R6 concepts once into the familiar flat R5 dosage shape. */
141
210
  export declare function toEzDosages(dosages: readonly (FhirDosage | EzDosage)[]): EzDosage[];
211
+ export declare function isRenderedInstructionMarker(extension: FhirExtension): boolean;
212
+ export declare function hasUnrecognizedEditMetadata(marker: FhirExtension): boolean;
142
213
  /** Project one R6 component without building course-storage metadata. Used by
143
214
  * both strict exports and read-only rendering; source objects are not mutated.
144
215
  * @param dosage Native R6 component.
145
216
  * @param sequence Ordered global course step for its R5 projection.
146
217
  */
147
218
  export declare function fromR6Dosage(dosage: FhirR6Dosage, sequence: number): FhirDosage;
219
+ /** A text-only course's latest full marker may already embed previous
220
+ * reconciliation sources. Keep those sources in their existing flat list,
221
+ * and preserve only the immediate preceding course snapshot as a new item.
222
+ * This strips solely the nested source-history wrapper at the known course
223
+ * top level; it retains unknown fields, safety, warnings and other extensions. */
224
+ export declare function sourceWithoutNestedHistory(marker: FhirExtension): FhirExtension;
225
+ /** Preserve unmatched step metadata in its original typed extension structure.
226
+ * @param step Source step that could not be matched to a live dosage.
227
+ */
228
+ export declare function retainedCourseStepSource(step: NonNullable<EzCourseMetadata["step"]>[number]): FhirExtension;
229
+ /** Compare live projections without sorted copies or serialization. Validator
230
+ * additions are tolerated only on Coding metadata, never on clinical fields.
231
+ * @param original Original typed projection.
232
+ * @param current Current editable projection.
233
+ * @param context Metadata context for Coding-system/version additions.
234
+ */
235
+ export declare function equivalentProjection(original: unknown, current: unknown, context?: "general" | "coding-list" | "coding-item"): boolean;
236
+ /**
237
+ * Inspect the live R5 projection independently of the embedded R6 snapshot.
238
+ * Modifier metadata is deliberately excluded from the comparison: it can
239
+ * describe a course but must never replace subsequently edited dosage values.
240
+ */
241
+ export declare function liveDosageProjection(dosage: FhirDosage | EzDosage, includeText?: boolean): object;
242
+ export declare function compactProjectionFingerprint(value: unknown): string;
243
+ /** Matching keys narrow candidates; exact equivalence is checked before
244
+ * claiming identity. Added Coding.system/version annotations do not force
245
+ * every edited row to rescan every original row. Existing baseline hashes
246
+ * remain byte-for-byte unchanged. */
247
+ export declare function matchingProjectionFingerprint(value: unknown): string;
248
+ /** Hash the current editable clinical view without allocating a stripped
249
+ * dosage tree on every call. Retained edit baselines themselves are excluded;
250
+ * active local row fields and all unrelated source annotations remain hashed.
251
+ * The exact token order is identical to compactProjectionFingerprint so
252
+ * existing persisted edit identities require no migration. */
253
+ export declare function dosageProjectionFingerprint(dosage: FhirDosage | EzDosage | FhirR6Dosage): string;
254
+ /** New agreement excludes narrative annotations; legacy untagged hashes keep
255
+ * their exact saved algorithm. An old hash alone cannot recover prior metadata. */
256
+ export declare function dosageClinicalProjectionFingerprint(dosage: FhirDosage | EzDosage | FhirR6Dosage): string;
257
+ export declare function matchesDosageProjectionFingerprint(dosage: FhirDosage | EzDosage | FhirR6Dosage, expected: string | undefined): boolean;
258
+ /** Source text can be retained without claiming it agrees with current
259
+ * external clinical fields. The compact annotation is local to every row. */
260
+ export declare function getDosageSourceTextFingerprint(dosage: Pick<FhirR6Dosage, "extension">): string | undefined;
261
+ /** The original clinical baseline stays bound to its original narrative across saves. */
262
+ export declare function getDosageSourceProjectionFingerprint(dosage: Pick<FhirR6Dosage, "extension">): string | undefined;
263
+ /** An unchanged source may receive its equivalent target-version baseline.
264
+ * Changed clinical fields retain the old hash so saving cannot certify stale text. */
265
+ export declare function retainedSourceProjectionFingerprint(dosage: FhirDosage | EzDosage | FhirR6Dosage): string | undefined;
266
+ /** Wording coverage and permission to replay clinical text are distinct.
267
+ * A declared coverage bit follows its exact source; legacy agreement keeps
268
+ * its existing requirement for a saved clinical projection. */
269
+ export declare function dosageHasAgreedSourceText(dosage: FhirDosage | EzDosage | FhirR6Dosage): boolean;
270
+ export declare function getDosageSourceTextAgreement(dosage: Pick<FhirR6Dosage, "extension" | "text">, acceptTextEdits?: boolean): boolean | undefined;
271
+ /** Source ownership of an immutable parser row. These flags identify the
272
+ * original HPSG projection; no clinical values are copied or watched. */
273
+ export interface FreshDoseSource {
274
+ defaulted: boolean;
275
+ clocks: boolean;
276
+ events: boolean;
277
+ site: boolean;
278
+ }
279
+ export declare function markFreshDoseSource(dosage: FhirDosage, defaulted: boolean, sourceTextAgreed?: boolean, sourceTextCovered?: boolean): void;
280
+ export declare function getFreshDoseSource(dosage: FhirDosage): FreshDoseSource | undefined;
281
+ export interface DosageSourceOwnership {
282
+ clocks?: boolean;
283
+ events?: boolean;
284
+ site?: boolean;
285
+ }
286
+ export declare function sourceOwnership(marker: FhirR6Extension): DosageSourceOwnership | undefined;
287
+ /** Saved primary-field ownership. Missing evidence never licenses removal
288
+ * of independent clocks, event anchors, or sites supplied only by the graph. */
289
+ export declare function getDosageSourceOwnership(dosage: Pick<FhirR6Dosage, "extension">): DosageSourceOwnership | undefined;
290
+ /** Known agreement remains owned even when its source Element has annotations. */
291
+ export declare function isSourceAgreementMarker(marker: FhirExtension): boolean;
292
+ export declare function isCompactSourceAgreementMarker(marker: FhirExtension | FhirR6Extension): boolean;
293
+ /** Verify each immutable submitted dosage's source clinical authority once.
294
+ * Missing provenance is unknown, not a mismatch. Fresh submissions always
295
+ * compare their current fields with the retained projection fingerprint. */
296
+ export declare function dosageMatchesSavedProjection(dosage: FhirDosage | EzDosage | FhirR6Dosage): boolean | undefined;
297
+ export declare function dosageTextFingerprint(dosage: FhirDosage | EzDosage | FhirR6Dosage): string;
148
298
  /**
149
299
  * Attach source/display provenance using repeated, structured row extensions.
150
300
  * Both primary parser output and strict R5 export use this same representation.
151
301
  * @param dosages Independently editable rows being returned to the caller.
152
- * @param instruction The author's unmodified instruction.
302
+ * @param instruction The author's unmodified instruction, when supplied.
303
+ * @param sourceAgreement Whether the producer established that wording agrees with the clinical fields.
153
304
  */
154
- export declare function withDosageEditProvenance<T extends FhirDosage | EzDosage>(dosages: readonly T[], instruction: string): T[];
155
- /**
156
- * Export the R5-style extended dose array as strict R6 DosageDetails.
157
- * The optional course.step rows use the official R6 step fields, grouped
158
- * by the existing global R5 sequence number.
159
- * @param dosages Authoritative live R5 rows, including retained course metadata.
160
- * @param renderedInstruction Explicit replacement whole-course display.
161
- * @param course Explicit editable course and step metadata, when supplied.
162
- * @param options Confirm corrected phase sequences after editing saved rows.
163
- * Only their persisted conflict flags are cleared; live disagreements still
164
- * block numeric execution and the prior conflict remains source provenance.
165
- * @returns The editable R6 course with any unresolved context retained.
166
- */
167
- export declare function toDosageDetails(dosages: readonly (FhirDosage | EzDosage)[], renderedInstruction?: string, course?: EzCourseMetadata, options?: {
305
+ export interface DosageSourceTextBaseline {
306
+ sourceAgreement: boolean;
307
+ sourceTextAgreed?: boolean;
308
+ projectionFingerprint?: string;
309
+ textFingerprint?: string;
310
+ sourceHasStructuredClocks?: boolean;
311
+ sourceHasStructuredEvents?: boolean;
312
+ sourceHasStructuredSite?: boolean;
313
+ }
314
+ export declare function withDosageEditProvenance<T extends FhirDosage | EzDosage>(dosages: readonly T[], instruction: string | undefined, sourceAgreement?: boolean, rowSources?: readonly (DosageSourceTextBaseline | undefined)[], headerCovered?: boolean): T[];
315
+ /** R6 imports follow the *current* DosageInstruction contract, not historical
316
+ * drafts. This runs only at the R6 import boundary, never on ordinary SIG
317
+ * parsing or R5 editing hot paths. Typed extensions and unknown value[x]
318
+ * payloads remain intact instead of being interpreted as clinical language. */
319
+ /** Compatibility name for the requested R6 export: R5 -> native -> R6.
320
+ * The native importer owns all row/phase reconciliation. */
321
+ export declare function toDosageDetails(rows: readonly (FhirDosage | EzDosage)[], instruction?: string, metadata?: EzCourseMetadata, options?: {
168
322
  resolvedPhaseSequences?: readonly number[];
169
- }): FhirR6DosageDetails;
170
- /** Import a complete R6 course without replacing EZMED's flat dosage layout. */
171
- export declare function fromDosageDetails(details: FhirR6DosageDetails): {
323
+ }): FhirR6DosageInstruction;
324
+ export declare function assertCurrentR6DosageInstruction(value: FhirR6DosageInstructionInput): string[];
325
+ /** A supplied R6 instruction is an input source, not an intermediate.
326
+ * Normalize it once and serialize requested R5 views directly. */
327
+ export declare function projectEditableR5Course(details: FhirR6DosageInstructionInput, strictPreview?: boolean): {
328
+ dosages: EzDosage[];
329
+ course: EzCourseMetadata;
330
+ strictDosages?: FhirDosage[];
331
+ };
332
+ /** Import the complete native R6 course into the established editable R5
333
+ * interchange contract. New internal course paths do not use this function. */
334
+ export declare function fromDosageDetails(details: FhirR6DosageInstructionInput): {
172
335
  dosages: EzDosage[];
173
336
  course: EzCourseMetadata;
174
337
  };
175
- /** Flatten R6 steps to R5 Dosage.sequence with explicit modifier extensions. */
176
- export declare function toFhirR5Dosages(input: FhirR6DosageDetails | readonly (FhirDosage | EzDosage)[], course?: EzCourseMetadata): FhirDosage[];
338
+ /** Requested R5 export: either input version is imported into native
339
+ * clinical facts, then written directly to R5. Neither external format is an
340
+ * intermediate representation for the other. */
341
+ export declare function toFhirR5Dosages(input: FhirR6DosageInstructionInput | readonly (FhirDosage | EzDosage)[], metadata?: EzCourseMetadata): FhirDosage[];
342
+ /** R5-only fields whose original R6 spelling or metadata needs a local delta. */
343
+ export interface ComponentDeltaBaseline {
344
+ condition?: string;
345
+ safety?: string;
346
+ site?: string;
347
+ doseAndRate?: Array<{
348
+ dose?: string;
349
+ rate?: string;
350
+ doseExpression?: string;
351
+ rateExpression?: string;
352
+ expressionSlot?: boolean;
353
+ }>;
354
+ timing?: string;
355
+ }
356
+ /** Each marker belongs to its live row, never to another component's snapshot. */
357
+ export interface CompactCourseRow {
358
+ rowIndex: number;
359
+ sequence: number;
360
+ stepCount: number;
361
+ /** Current saved-row contract: step.count repeats only that step. */
362
+ countScope?: "step";
363
+ step?: Omit<FhirR6DosageStep, "component">;
364
+ component?: Partial<FhirR6Dosage>;
365
+ /** R6 offsets are typed extension children, never R5 Extension.valueTiming. */
366
+ timingOffsets?: Pick<FhirR6TimingRepeat, "startOffset" | "endOffset">;
367
+ baseline?: ComponentDeltaBaseline;
368
+ context?: string;
369
+ contextRequired?: boolean;
370
+ course?: Omit<FhirR6DosageInstruction, "step" | "renderedInstruction">;
371
+ emptyStep?: EzCourseStep[];
372
+ missingContext?: string[];
373
+ }
374
+ /** Period-local offsets are measured within the cadence period. A frequency
375
+ * edit does not change that window while the R6 frequency > 1 constraint holds. */
376
+ export declare function offsetCadenceFingerprint(timing: FhirDosage["timing"] | FhirR6Dosage["timing"]): string;
377
+ export declare function matchesOffsetCadence(timing: FhirDosage["timing"] | FhirR6Dosage["timing"], baseline: string | undefined): boolean;
177
378
  /** Encode local phase metadata and unrepresentable component fields.
178
379
  * Course-wide metadata has one owner, referenced by all participating rows.
179
380
  * All rows are newly created by the caller; no source course is mutated.
180
381
  * @param dosages Fresh flattened output rows in step/component order.
181
382
  * @param details Typed source course, used only to calculate missing metadata.
182
383
  */
183
- export declare function attachCourseDetailsExtensions(dosages: (FhirDosage | EzDosage)[], details: FhirR6DosageDetails): void;
384
+ export declare function attachCourseDetailsExtensions(dosages: (FhirDosage | EzDosage)[], details: FhirR6DosageInstruction): void;
385
+ /** These are R5 extension codecs, not version converters. A native writer
386
+ * supplies only final retained fields which cannot live in an R5 Dosage row.
387
+ * The old extension names remain stable so existing persisted edits reopen. */
388
+ export declare function attachR5RetainedRow(row: FhirDosage | EzDosage, retained: CompactCourseRow): void;
389
+ /** Qualifiers in SimpleQuantity cannot be ignored as exact numeric doses.
390
+ * The clause writer calls this only after finding a typed qualifier, using the
391
+ * same modifier and edit baseline as the direct native R5 writer. */
392
+ export declare function attachQualifiedR5AmountDetails(row: FhirDosage): void;
393
+ /** A course with no administration has a source carrier, not a fabricated
394
+ * dosage. Encode the header and empty-stage metadata directly into its R5
395
+ * extension; do not allocate an intermediate external course. */
396
+ export declare function createR5EmptyCourseCarrier(fields: Omit<FhirR6DosageInstruction, "step" | "renderedInstruction">, steps: Omit<FhirR6DosageStep, "component">[], instruction?: string): FhirDosage;
397
+ /** Comparison views used only by the retained-row codec. These project small
398
+ * individual fields, never a whole R6 dosage/course to serve as R5 input. */
399
+ export declare const r5ConditionBaseline: typeof parseDosageCondition;
400
+ export declare const r5SafetyBaseline: typeof toR6Safety;
401
+ /** Decode only retained R5 profile fields, not a synthetic external course. */
402
+ export declare function decodeR5RetainedFields(marker: FhirR6Extension): Partial<CompactCourseRow>;
403
+ export declare function encodeR5RetainedFields(value: Partial<CompactCourseRow>): FhirExtension[];
404
+ /** Detect the row-local contract without decoding ordinary R5 inputs.
405
+ * @param dosage Live row carrying optional course metadata.
406
+ */
407
+ export declare function compactCourseMarker(dosage: FhirDosage | EzDosage): FhirExtension | undefined;
408
+ /** Preserve a superseded local delta without nesting its course owner again.
409
+ * @param marker The row's original structured extension.
410
+ */
411
+ export declare function localReconciliationSource(marker: FhirExtension): FhirExtension;
412
+ /** Align R6-only dose/rate choices with surviving R5 entries by their
413
+ * native Element.id or unique clinical type. Position is meaningful only if
414
+ * the list cardinality is unchanged; without identity, deleting one of two
415
+ * indistinguishable projected entries cannot prove which was removed.
416
+ *
417
+ * Only called for a course row that actually carries R6-only choices.
418
+ * @returns Live index -> retained source index; unmatched sources stay inert.
419
+ */
420
+ export declare function retainedDoseRateMatches(source: readonly NonNullable<FhirR6Dosage["doseAndRate"]>[number][], live: readonly NonNullable<FhirR6Dosage["doseAndRate"]>[number][], baselines?: ComponentDeltaBaseline["doseAndRate"]): Map<number, number>;
421
+ /** Phase fields whose disagreement can change administration or supply.
422
+ * IDs and non-modifier annotations remain editable without blocking execution.
423
+ * @param step Local phase metadata without dosage components.
424
+ */
425
+ export declare function executablePhaseMetadata(step: NonNullable<CompactCourseRow["step"]>): {
426
+ start: import("./types").FhirR6RelativeTime | undefined;
427
+ end: import("./types").FhirR6RelativeTime | undefined;
428
+ count: number | undefined;
429
+ safety: FhirR6DosageSafety | undefined;
430
+ };
184
431
  /** Identify unavailable or contradictory context before numeric execution.
185
432
  * Parsing, formatting and editing continue to preserve all surviving data.
186
433
  * @param course Reconstructed course with typed context markers on its components.
187
434
  */
188
- export declare function getCourseContextIssue(course: FhirR6DosageDetails): "missing-course-context" | "conflicting-course-phase" | undefined;
435
+ export declare function getCourseContextIssue(course: FhirR6DosageInstruction): "missing-course-context" | "conflicting-course-phase" | undefined;
436
+ export declare function encodeR6SourceMetadata(url: string, value: object, kind: "drafts" | "safety" | "step"): FhirExtension;
437
+ export declare function decodeR6SourceMetadata(marker: FhirR6Extension, kind: "drafts" | "safety" | "step"): Record<string, unknown> | undefined;
438
+ /** Preserve an unfamiliar field as explicit typed extension content, never an
439
+ * opaque JSON string. Known FHIR fields use the named datatype schemas above;
440
+ * this escape hatch only retains future/unrecognized native fields verbatim.
441
+ * @param url The enclosing field name.
442
+ * @param value The actual source value; no clinical interpretation is inferred.
443
+ */
444
+ export declare function retainField(url: string, value: unknown): FhirExtension;
445
+ /** Read retained fields without evaluating them or reparsing serialized text.
446
+ * @param node One preserved field extension.
447
+ */
448
+ export declare function readRetainedField(node: FhirR6Extension): unknown;
449
+ /** Recover a course from a structured extension, leaving malformed originals
450
+ * with the caller for preservation. No string payload is interpreted here.
451
+ * @param node The dosageDetails extension child.
452
+ */
453
+ export declare function decodeCourseDetails(node: FhirExtension): FhirR6DosageInstruction | undefined;
@@ -0,0 +1,107 @@
1
+ /** Civil-clock primitives shared by clinical occurrence and supply execution.
2
+ * Calendar stepping preserves the prescribed wall clock across DST and month
3
+ * boundaries. No medication, FHIR, parser, or persistence type lives here. */
4
+ export declare const SECONDS_PER_MINUTE = 60;
5
+ /** Caches expensive Intl.DateTimeFormat objects per time zone. */
6
+ export declare const dateTimeFormatCache: Map<string, Intl.DateTimeFormat>;
7
+ /** Separate cache for weekday formatting to avoid rebuilding formatters. */
8
+ export declare const weekdayFormatCache: Map<string, Intl.DateTimeFormat>;
9
+ export interface TimeParts {
10
+ year: number;
11
+ month: number;
12
+ day: number;
13
+ hour: number;
14
+ minute: number;
15
+ second: number;
16
+ }
17
+ export interface DateTimeFormatPart {
18
+ type: string;
19
+ value: string;
20
+ }
21
+ export interface IntlDateTimeFormatOptionsExtended extends Intl.DateTimeFormatOptions {
22
+ calendar?: string;
23
+ numberingSystem?: string;
24
+ }
25
+ export interface DateTimeFormatWithParts {
26
+ formatToParts?: (date?: number | Date) => DateTimeFormatPart[];
27
+ }
28
+ /** Simple zero-padding helper for numeric components. */
29
+ export declare function pad(value: number, length?: number): string;
30
+ export declare function formatToParts(formatter: Intl.DateTimeFormat, date: Date): DateTimeFormatPart[];
31
+ /**
32
+ * Normalizes HH:mm or HH:mm:ss clocks into a consistent HH:mm:ss string.
33
+ */
34
+ export declare function normalizeClock(clock: string): string;
35
+ /** Retrieves (and caches) an Intl formatter for calendar components. */
36
+ export declare function getDateTimeFormat(timeZone: string): Intl.DateTimeFormat;
37
+ /** Retrieves (and caches) a formatter for weekday lookups. */
38
+ export declare function getWeekdayFormat(timeZone: string): Intl.DateTimeFormat;
39
+ /**
40
+ * Extracts calendar components for a Date interpreted within the supplied time
41
+ * zone.
42
+ */
43
+ export declare function getTimeParts(date: Date, timeZone: string): TimeParts;
44
+ /** Calculates the time-zone offset in minutes for a given instant. */
45
+ export declare function getOffset(date: Date, timeZone: string): number;
46
+ /** Locate the offset transition within one civil day. Calendar arithmetic
47
+ * can then split at the real discontinuity instead of assuming local wall
48
+ * clocks are monotone across a DST fold. Ordinary days need two lookups. */
49
+ export declare function calendarOffsetTransition(start: Date, end: Date, timeZone: string): number | undefined;
50
+ /**
51
+ * Renders an ISO-8601 string that reflects the provided time zone instead of
52
+ * defaulting to UTC.
53
+ */
54
+ export declare function formatZonedIso(date: Date, timeZone: string): string;
55
+ /**
56
+ * Builds a Date representing a local wall-clock time in the target time zone.
57
+ */
58
+ export declare function makeZonedDate(timeZone: string, year: number, month: number, day: number, hour: number, minute: number, second: number): Date | null;
59
+ /** Calendar boundaries use the iCalendar DATE-TIME convention for a
60
+ * nonexistent wall clock: apply the pre-gap offset and advance through the
61
+ * gap. Do not use this for prescribed dose events; a missing explicit
62
+ * timeOfDay still has no exact administration instant. */
63
+ export declare function calendarBoundaryDate(timeZone: string, year: number, month: number, day: number, hour: number, minute: number, second: number): Date | null;
64
+ export interface ClockParts {
65
+ hour: number;
66
+ minute: number;
67
+ second: number;
68
+ milliseconds: number;
69
+ }
70
+ /** Decode a clock once for reuse by the existing civil-date constructor. */
71
+ export declare function parseClockParts(clock: string): ClockParts;
72
+ /** Convenience wrapper around makeZonedDate for day-level math. */
73
+ export declare function makeZonedDateFromDay(base: Date, timeZone: string, clock: string | ClockParts): Date | null;
74
+ /** Returns a Date pinned to the start of the local day. */
75
+ export declare function startOfLocalDay(date: Date, timeZone: string): Date;
76
+ /** Adds a number of calendar days while remaining aligned to the time zone. */
77
+ export declare function addLocalDays(date: Date, days: number, timeZone: string): Date;
78
+ /** Advance a *calendar* dose cycle by local days while keeping its
79
+ * prescribed wall clock. Unlike an elapsed q24h interval, a course cycle
80
+ * cannot lose an hour at daylight-saving transitions. */
81
+ export declare function addCalendarDaysAtClock(instant: Date, days: number, timeZone: string, clock: Pick<TimeParts, "hour" | "minute" | "second">): Date | null;
82
+ /** A calendar cycle keeps its original wall clock even after one boundary
83
+ * falls into a DST gap. The next boundary resumes the prescribed hour. */
84
+ export declare function calendarDayStepper(anchor: Date, days: number, timeZone: string, originalClock?: Pick<TimeParts, "hour" | "minute" | "second">): (instant: Date) => Date | null;
85
+ /** Computes the local weekday token (mon..sun). */
86
+ export declare function getLocalWeekday(date: Date, timeZone: string): string;
87
+ export declare function getLocalDayNumber(date: Date, timeZone: string): number;
88
+ export declare function getLocalMonthIndex(date: Date, timeZone: string): number;
89
+ /** Parses arbitrary string/Date inputs into a valid Date instance. */
90
+ export declare function coerceDate(value: Date | string, label: string): Date;
91
+ /**
92
+ * Adds calendar months while respecting varying month lengths and DST.
93
+ *
94
+ * @param date Starting instant.
95
+ * @param months Number of calendar months to add.
96
+ * @param timeZone IANA timezone used for wall-clock preservation.
97
+ * @returns Shifted date preserving local clock and clamped day-of-month.
98
+ */
99
+ export declare function addCalendarMonths(date: Date, months: number, timeZone: string, originalClock?: Pick<TimeParts, "hour" | "minute" | "second">): Date;
100
+ /**
101
+ * Formats a date into a local `HH:MM:SS` clock for the supplied timezone.
102
+ *
103
+ * @param date Source instant.
104
+ * @param timeZone IANA timezone to interpret the instant.
105
+ * @returns Local wall-clock time in `HH:MM:SS` format.
106
+ */
107
+ export declare function toLocalClock(date: Date, timeZone: string): string;
@@ -0,0 +1,11 @@
1
+ import type { CanonicalScheduleInput, CanonicalSupplyOptions } from "../canonical/course";
2
+ import type { NextDueDoseOptions, TotalUnitsResult } from "../types";
3
+ export declare function nextDueDoses(dosage: CanonicalScheduleInput, options: NextDueDoseOptions): string[];
4
+ /** Supply math is deterministic only when the administered amount is known.
5
+ * Clinical conditions/PRN are represented as a maximum permitted supply,
6
+ * not as a claim that every available dose will actually be administered. */
7
+ export declare class MedicationQuantityCalculationError extends Error {
8
+ readonly code: string;
9
+ constructor(code: string, message: string);
10
+ }
11
+ export declare function calculateTotalUnits(options: CanonicalSupplyOptions): TotalUnitsResult;
@@ -0,0 +1,53 @@
1
+ /** Established EMA SPOR Quantity Operator representation for R5 quantities.
2
+ *
3
+ * R5 Dosage.doseAndRate.doseQuantity / rateQuantity use SimpleQuantity,
4
+ * which has no comparator field. EMA's published comparator extension is
5
+ * applicable to Element and preserves the qualifier without erasing the
6
+ * numeric dose. General Quantity supports native comparators; SimpleQuantity
7
+ * remains comparator-free in both R5 and R6.
8
+ *
9
+ * Sources:
10
+ * EMA http://ema.europa.eu/fhir/extension/comparator
11
+ * EMA http://spor.ema.europa.eu/v1/lists/100000000008
12
+ * HL7 http://hl7.org/fhir/quantity-comparator
13
+ */
14
+ /** Inactive retained wire data is shared by the version-boundary codecs.
15
+ * Keep this identifier in the leaf codec so annotation conversion does not
16
+ * initialize the course importer or clinical grammar. */
17
+ export declare const DOSAGE_RECONCILIATION_SOURCE_URL = "urn:ezmedicationinput:StructureDefinition:medication-course-reconciliation-source";
18
+ import type { FhirQuantity, FhirR6Quantity, FhirSimpleQuantity, FhirR6SimpleQuantity, FhirR6Coding, FhirR6Extension, FhirPrimitiveElement, FhirR6PrimitiveElement } from "./types";
19
+ export declare const EMA_QUANTITY_COMPARATOR_EXTENSION_URL = "http://ema.europa.eu/fhir/extension/comparator";
20
+ export declare const EMA_QUANTITY_OPERATOR_SYSTEM = "http://spor.ema.europa.eu/v1/lists/100000000008";
21
+ export declare const FHIR_QUANTITY_COMPARATOR_SYSTEM = "http://hl7.org/fhir/quantity-comparator";
22
+ /** Read the published EMA Coding without treating "average", "equivalent"
23
+ * or "range" as invented HL7 comparator semantics. */
24
+ export declare function getEmaQuantityComparator(quantity: Pick<FhirR6Quantity, "extension"> | undefined): FhirR6Quantity["comparator"];
25
+ /** Read the active qualifier. A clinician-edited native Quantity comparator
26
+ * wins over retained EMA metadata; SimpleQuantity falls back to EMA Coding.
27
+ * Use this for meaning/display, not the extension-only inspection API. */
28
+ export declare function getQuantityComparator(quantity: Pick<FhirR6Quantity, "comparator" | "extension"> | undefined): FhirR6Quantity["comparator"];
29
+ /** Translations describe a particular code, not an operator slot. Preserve
30
+ * superseded labels under their original Coding, outside the active operator. */
31
+ export declare const QUANTITY_OPERATOR_SOURCE_URL = "urn:ezmedicationinput:StructureDefinition:quantity-operator-source";
32
+ export declare function quantityAnnotationExtensions(source: FhirR6Extension[], target: "r5" | "r6"): FhirR6Extension[];
33
+ export declare function quantityCodingForWire(coding: FhirR6Coding | undefined, target: "r5" | "r6"): FhirR6Coding | undefined;
34
+ /** The known Quantity choice is projected; all unrelated opaque annotations
35
+ * retain their original datatype and fields at this version boundary. */
36
+ export declare function quantityPrimitiveForR5(primitive: FhirR6PrimitiveElement | undefined): FhirPrimitiveElement | undefined;
37
+ export declare function simpleQuantityForR5(quantity: FhirR6Quantity | undefined): FhirSimpleQuantity | undefined;
38
+ /** R6 SimpleQuantity keeps native primitive annotations while using the same
39
+ * comparator-free scalar representation as R5. */
40
+ export declare function simpleQuantityForR6(quantity: FhirR6Quantity | undefined): FhirR6SimpleQuantity | undefined;
41
+ /** A general R5 Quantity supports older native comparators. Its only
42
+ * missing R6 comparator is "~"; use the EMA extension for that case. */
43
+ export declare function quantityForR5(quantity: FhirR6Quantity | undefined): FhirQuantity | undefined;
44
+ /** A native Quantity operator has one active owner. Retain authored EMA
45
+ * annotations as inert source when writing that owner, so a subsequent edit
46
+ * of the external native comparator cannot revive a hidden duplicate. EMA-only
47
+ * input still owns its qualifier, and SimpleQuantity still writes active EMA. */
48
+ export declare function quantityForR6(quantity: FhirR6Quantity | undefined): FhirR6Quantity | undefined;
49
+ /** Read the current quantity operator at either FHIR boundary. The same EMA
50
+ * coding owns a SimpleQuantity in R5 and R6; native comparators take priority.
51
+ * Authored annotations and superseded labels remain recoverable source. */
52
+ export declare function quantityFromWire(quantity: FhirQuantity | FhirR6Quantity | FhirSimpleQuantity | undefined): FhirR6Quantity | undefined;
53
+ export { quantityFromWire as quantityFromR5 };
@@ -1,11 +1,10 @@
1
- import { FhirExtension, FhirPrimitiveElement } from "./types";
1
+ import { FhirExtension, FhirPrimitiveElement, FhirR6PrimitiveElement, FhirR6Extension } from "./types";
2
2
  export declare const FHIR_TRANSLATION_EXTENSION_URL = "http://hl7.org/fhir/StructureDefinition/translation";
3
3
  export declare function cloneI18nRecord(i18n: Record<string, string> | undefined): Record<string, string> | undefined;
4
4
  export declare function mergeI18nRecords(...records: Array<Record<string, string> | undefined>): Record<string, string> | undefined;
5
- export declare function cloneExtension(extension: FhirExtension): FhirExtension;
6
- export declare function cloneExtensions(extensions: FhirExtension[] | undefined): FhirExtension[] | undefined;
7
- export declare function clonePrimitiveElement(element: FhirPrimitiveElement | undefined): FhirPrimitiveElement | undefined;
5
+ export declare function cloneExtensions(extensions: FhirR6Extension[] | undefined): FhirExtension[] | undefined;
6
+ export declare function clonePrimitiveElement(element: FhirR6PrimitiveElement | undefined): FhirPrimitiveElement | undefined;
8
7
  export declare function buildTranslationPrimitiveElement(translations: Record<string, string> | undefined, base?: FhirPrimitiveElement): FhirPrimitiveElement | undefined;
9
8
  export declare function mergeTranslationPrimitiveElement(base: FhirPrimitiveElement | undefined, translations: Record<string, string> | undefined): FhirPrimitiveElement | undefined;
10
- export declare function getPrimitiveTranslation(element: FhirPrimitiveElement | undefined, locale: string | undefined): string | undefined;
11
- export declare function getPrimitiveTranslations(element: FhirPrimitiveElement | undefined): Record<string, string> | undefined;
9
+ export declare function getPrimitiveTranslation(element: FhirR6PrimitiveElement | undefined, locale: string | undefined): string | undefined;
10
+ export declare function getPrimitiveTranslations(element: FhirR6PrimitiveElement | undefined): Record<string, string> | undefined;