fhir-runtime 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +211 -0
  2. package/LICENSE +21 -0
  3. package/README.md +261 -0
  4. package/dist/cjs/index.cjs +7368 -0
  5. package/dist/cjs/index.cjs.map +7 -0
  6. package/dist/cjs/index.d.ts +4224 -0
  7. package/dist/cjs/package.json +5 -0
  8. package/dist/esm/index.d.ts +4224 -0
  9. package/dist/esm/index.mjs +7250 -0
  10. package/dist/esm/index.mjs.map +7 -0
  11. package/dist/esm/package.json +5 -0
  12. package/dist/index.d.ts +4224 -0
  13. package/dist/lib/context/bundle-loader.d.ts +124 -0
  14. package/dist/lib/context/bundle-loader.d.ts.map +1 -0
  15. package/dist/lib/context/core-definitions/index.d.ts +72 -0
  16. package/dist/lib/context/core-definitions/index.d.ts.map +1 -0
  17. package/dist/lib/context/errors.d.ts +114 -0
  18. package/dist/lib/context/errors.d.ts.map +1 -0
  19. package/dist/lib/context/fhir-context.d.ts +72 -0
  20. package/dist/lib/context/fhir-context.d.ts.map +1 -0
  21. package/dist/lib/context/index.d.ts +21 -0
  22. package/dist/lib/context/index.d.ts.map +1 -0
  23. package/dist/lib/context/inheritance-resolver.d.ts +98 -0
  24. package/dist/lib/context/inheritance-resolver.d.ts.map +1 -0
  25. package/dist/lib/context/inner-type-extractor.d.ts +80 -0
  26. package/dist/lib/context/inner-type-extractor.d.ts.map +1 -0
  27. package/dist/lib/context/loaders/composite-loader.d.ts +47 -0
  28. package/dist/lib/context/loaders/composite-loader.d.ts.map +1 -0
  29. package/dist/lib/context/loaders/file-loader.d.ts +47 -0
  30. package/dist/lib/context/loaders/file-loader.d.ts.map +1 -0
  31. package/dist/lib/context/loaders/index.d.ts +11 -0
  32. package/dist/lib/context/loaders/index.d.ts.map +1 -0
  33. package/dist/lib/context/loaders/memory-loader.d.ts +42 -0
  34. package/dist/lib/context/loaders/memory-loader.d.ts.map +1 -0
  35. package/dist/lib/context/registry.d.ts +116 -0
  36. package/dist/lib/context/registry.d.ts.map +1 -0
  37. package/dist/lib/context/types.d.ts +266 -0
  38. package/dist/lib/context/types.d.ts.map +1 -0
  39. package/dist/lib/fhirpath/atoms.d.ts +228 -0
  40. package/dist/lib/fhirpath/atoms.d.ts.map +1 -0
  41. package/dist/lib/fhirpath/cache.d.ts +79 -0
  42. package/dist/lib/fhirpath/cache.d.ts.map +1 -0
  43. package/dist/lib/fhirpath/date.d.ts +17 -0
  44. package/dist/lib/fhirpath/date.d.ts.map +1 -0
  45. package/dist/lib/fhirpath/functions.d.ts +28 -0
  46. package/dist/lib/fhirpath/functions.d.ts.map +1 -0
  47. package/dist/lib/fhirpath/index.d.ts +20 -0
  48. package/dist/lib/fhirpath/index.d.ts.map +1 -0
  49. package/dist/lib/fhirpath/lexer/parse.d.ts +100 -0
  50. package/dist/lib/fhirpath/lexer/parse.d.ts.map +1 -0
  51. package/dist/lib/fhirpath/lexer/tokenize.d.ts +80 -0
  52. package/dist/lib/fhirpath/lexer/tokenize.d.ts.map +1 -0
  53. package/dist/lib/fhirpath/parse.d.ts +101 -0
  54. package/dist/lib/fhirpath/parse.d.ts.map +1 -0
  55. package/dist/lib/fhirpath/tokenize.d.ts +20 -0
  56. package/dist/lib/fhirpath/tokenize.d.ts.map +1 -0
  57. package/dist/lib/fhirpath/types.d.ts +111 -0
  58. package/dist/lib/fhirpath/types.d.ts.map +1 -0
  59. package/dist/lib/fhirpath/utils.d.ts +81 -0
  60. package/dist/lib/fhirpath/utils.d.ts.map +1 -0
  61. package/dist/lib/index.d.ts +24 -0
  62. package/dist/lib/index.d.ts.map +1 -0
  63. package/dist/lib/model/canonical-profile.d.ts +381 -0
  64. package/dist/lib/model/canonical-profile.d.ts.map +1 -0
  65. package/dist/lib/model/element-definition.d.ts +503 -0
  66. package/dist/lib/model/element-definition.d.ts.map +1 -0
  67. package/dist/lib/model/index.d.ts +14 -0
  68. package/dist/lib/model/index.d.ts.map +1 -0
  69. package/dist/lib/model/primitives.d.ts +464 -0
  70. package/dist/lib/model/primitives.d.ts.map +1 -0
  71. package/dist/lib/model/structure-definition.d.ts +263 -0
  72. package/dist/lib/model/structure-definition.d.ts.map +1 -0
  73. package/dist/lib/parser/choice-type-parser.d.ts +182 -0
  74. package/dist/lib/parser/choice-type-parser.d.ts.map +1 -0
  75. package/dist/lib/parser/index.d.ts +16 -0
  76. package/dist/lib/parser/index.d.ts.map +1 -0
  77. package/dist/lib/parser/json-parser.d.ts +171 -0
  78. package/dist/lib/parser/json-parser.d.ts.map +1 -0
  79. package/dist/lib/parser/parse-error.d.ts +146 -0
  80. package/dist/lib/parser/parse-error.d.ts.map +1 -0
  81. package/dist/lib/parser/primitive-parser.d.ts +136 -0
  82. package/dist/lib/parser/primitive-parser.d.ts.map +1 -0
  83. package/dist/lib/parser/serializer.d.ts +64 -0
  84. package/dist/lib/parser/serializer.d.ts.map +1 -0
  85. package/dist/lib/parser/structure-definition-parser.d.ts +63 -0
  86. package/dist/lib/parser/structure-definition-parser.d.ts.map +1 -0
  87. package/dist/lib/profile/canonical-builder.d.ts +87 -0
  88. package/dist/lib/profile/canonical-builder.d.ts.map +1 -0
  89. package/dist/lib/profile/constraint-merger.d.ts +100 -0
  90. package/dist/lib/profile/constraint-merger.d.ts.map +1 -0
  91. package/dist/lib/profile/element-merger.d.ts +80 -0
  92. package/dist/lib/profile/element-merger.d.ts.map +1 -0
  93. package/dist/lib/profile/element-sorter.d.ts +81 -0
  94. package/dist/lib/profile/element-sorter.d.ts.map +1 -0
  95. package/dist/lib/profile/errors.d.ts +150 -0
  96. package/dist/lib/profile/errors.d.ts.map +1 -0
  97. package/dist/lib/profile/index.d.ts +27 -0
  98. package/dist/lib/profile/index.d.ts.map +1 -0
  99. package/dist/lib/profile/path-utils.d.ts +180 -0
  100. package/dist/lib/profile/path-utils.d.ts.map +1 -0
  101. package/dist/lib/profile/slicing-handler.d.ts +121 -0
  102. package/dist/lib/profile/slicing-handler.d.ts.map +1 -0
  103. package/dist/lib/profile/snapshot-generator.d.ts +73 -0
  104. package/dist/lib/profile/snapshot-generator.d.ts.map +1 -0
  105. package/dist/lib/profile/types.d.ts +220 -0
  106. package/dist/lib/profile/types.d.ts.map +1 -0
  107. package/dist/lib/validator/errors.d.ts +83 -0
  108. package/dist/lib/validator/errors.d.ts.map +1 -0
  109. package/dist/lib/validator/index.d.ts +23 -0
  110. package/dist/lib/validator/index.d.ts.map +1 -0
  111. package/dist/lib/validator/invariant-validator.d.ts +62 -0
  112. package/dist/lib/validator/invariant-validator.d.ts.map +1 -0
  113. package/dist/lib/validator/path-extractor.d.ts +123 -0
  114. package/dist/lib/validator/path-extractor.d.ts.map +1 -0
  115. package/dist/lib/validator/slicing-validator.d.ts +119 -0
  116. package/dist/lib/validator/slicing-validator.d.ts.map +1 -0
  117. package/dist/lib/validator/structure-validator.d.ts +74 -0
  118. package/dist/lib/validator/structure-validator.d.ts.map +1 -0
  119. package/dist/lib/validator/types.d.ts +288 -0
  120. package/dist/lib/validator/types.d.ts.map +1 -0
  121. package/dist/lib/validator/validation-rules.d.ts +198 -0
  122. package/dist/lib/validator/validation-rules.d.ts.map +1 -0
  123. package/dist/tsdoc-metadata.json +11 -0
  124. package/package.json +76 -0
@@ -0,0 +1,4224 @@
1
+ /**
2
+ * `@medxai/fhir-core` — Public API (Frozen at v0.1.0)
3
+ *
4
+ * Re-exports all public types and functions from the six core modules:
5
+ * model → parser → context → profile → validator (+ fhirpath internal)
6
+ *
7
+ * This file defines the frozen public API surface for @medxai/fhir-core v0.1.
8
+ * Any symbol exported here is subject to the v0.1 compatibility contract.
9
+ * See: docs/specs/engine-capability-contract-v0.1.md
10
+ * docs/api/fhir-core-api-v0.1.md
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+
15
+ /**
16
+ * Brand symbol used to distinguish FHIR primitive types at compile time.
17
+ * This provides nominal typing over TypeScript's structural type system,
18
+ * preventing accidental assignment between semantically different types
19
+ * (e.g., assigning a FhirUri to a FhirCode) while maintaining zero runtime overhead.
20
+ */
21
+ declare const __brand: unique symbol;
22
+
23
+ /**
24
+ * How resource references can be aggregated.
25
+ * @see https://hl7.org/fhir/R4/valueset-resource-aggregation-mode.html
26
+ */
27
+ export declare type AggregationMode = 'contained' | 'referenced' | 'bundled';
28
+
29
+ /**
30
+ * All core definition filenames in dependency order:
31
+ * base → primitives → complex types → resources.
32
+ */
33
+ export declare const ALL_CORE_DEFINITIONS: readonly string[];
34
+
35
+ /**
36
+ * Interface for all AST nodes in the FHIRPath expression tree.
37
+ * Each node can evaluate itself given a context and input collection.
38
+ */
39
+ declare interface Atom {
40
+ /**
41
+ * Evaluate this atom against the given input collection.
42
+ * @param context - The evaluation context (variables, parent scope).
43
+ * @param input - The input collection of typed values.
44
+ * @returns The result collection.
45
+ */
46
+ eval(context: AtomContext, input: TypedValue[]): TypedValue[];
47
+ /** Returns a string representation of this atom (for debugging). */
48
+ toString(): string;
49
+ }
50
+
51
+ /**
52
+ * Evaluation context for FHIRPath expressions.
53
+ * Supports nested scoping via the `parent` chain, used by functions
54
+ * like `where()` and `select()` that introduce `$this`.
55
+ */
56
+ declare interface AtomContext {
57
+ readonly parent?: AtomContext;
58
+ readonly variables: Record<string, TypedValue>;
59
+ }
60
+
61
+ /**
62
+ * Base definition for all elements that are defined inside a resource,
63
+ * but not those in a data type.
64
+ * @see https://hl7.org/fhir/R4/backboneelement.html
65
+ */
66
+ export declare interface BackboneElement extends Element {
67
+ /** Extensions that cannot be ignored even if unrecognized (0..*) */
68
+ modifierExtension?: Extension[];
69
+ }
70
+
71
+ /**
72
+ * Base resource types — the foundation of the FHIR type hierarchy.
73
+ * These MUST be loaded first as other definitions depend on them.
74
+ */
75
+ export declare const BASE_RESOURCES: readonly ["Resource", "DomainResource", "Element", "BackboneElement", "Extension"];
76
+
77
+ /**
78
+ * Thrown when the base StructureDefinition required for snapshot generation
79
+ * cannot be loaded from any source.
80
+ *
81
+ * This is a fatal error — snapshot generation cannot proceed without the
82
+ * base profile's snapshot to merge against.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * throw new BaseNotFoundError(
87
+ * 'http://hl7.org/fhir/StructureDefinition/Patient',
88
+ * 'http://hl7.org/fhir/StructureDefinition/UnknownBase'
89
+ * );
90
+ * ```
91
+ */
92
+ export declare class BaseNotFoundError extends ProfileError {
93
+ readonly name = "BaseNotFoundError";
94
+ /** The canonical URL of the derived profile being generated. */
95
+ readonly derivedUrl: string;
96
+ /** The canonical URL of the base that could not be found. */
97
+ readonly baseUrl: string;
98
+ constructor(derivedUrl: string, baseUrl: string, cause?: Error);
99
+ }
100
+
101
+ /**
102
+ * A resolved value set binding on a canonical element.
103
+ *
104
+ * Corresponds to a simplified version of `ElementDefinition.binding`.
105
+ */
106
+ export declare interface BindingConstraint {
107
+ /**
108
+ * required | extensible | preferred | example
109
+ *
110
+ * Indicates the degree of conformance expectation.
111
+ * @see https://hl7.org/fhir/R4/valueset-binding-strength.html
112
+ */
113
+ strength: BindingStrength;
114
+ /**
115
+ * Canonical URL of the bound value set.
116
+ *
117
+ * Resolved from `ElementDefinitionBinding.valueSet`.
118
+ */
119
+ valueSetUrl?: string;
120
+ /** Human-readable description of the binding. */
121
+ description?: string;
122
+ }
123
+
124
+ /**
125
+ * Indication of the degree of conformance expectations associated with a binding.
126
+ * @see https://hl7.org/fhir/R4/valueset-binding-strength.html
127
+ */
128
+ export declare type BindingStrength = 'required' | 'extensible' | 'preferred' | 'example';
129
+
130
+ /**
131
+ * Generic branded type. Intersects a base type with a unique brand tag.
132
+ * @typeParam Base - The underlying TypeScript type (string, number, boolean)
133
+ * @typeParam Brand - A unique string literal identifying the FHIR type
134
+ */
135
+ declare type Branded<Base, Brand extends string> = Base & {
136
+ readonly [__brand]: Brand;
137
+ };
138
+
139
+ /**
140
+ * Convert ElementDefinitionBinding to BindingConstraint.
141
+ *
142
+ * Returns undefined if binding is undefined or has no strength.
143
+ *
144
+ * @param binding - The FHIR binding from an ElementDefinition.
145
+ * @returns Normalized BindingConstraint or undefined.
146
+ */
147
+ export declare function buildBindingConstraint(binding: ElementDefinitionBinding | undefined): BindingConstraint | undefined;
148
+
149
+ /**
150
+ * Convert a single ElementDefinition to a CanonicalElement.
151
+ *
152
+ * Applies the following normalizations:
153
+ * - `max: "*"` → `max: 'unbounded'`; numeric strings → numbers
154
+ * - `mustSupport/isModifier/isSummary: undefined` → `false`
155
+ * - `constraint: undefined` → `[]`
156
+ * - `type: undefined` → `[]`
157
+ *
158
+ * @param ed - The ElementDefinition from a snapshot.
159
+ * @returns The normalized CanonicalElement.
160
+ */
161
+ export declare function buildCanonicalElement(ed: ElementDefinition): CanonicalElement;
162
+
163
+ /**
164
+ * Convert a StructureDefinition (with snapshot) to a CanonicalProfile.
165
+ *
166
+ * Precondition: `sd.snapshot` must exist (generated by SnapshotGenerator).
167
+ * If snapshot is missing, throws an error.
168
+ *
169
+ * @param sd - The StructureDefinition with populated snapshot.
170
+ * @returns The internal CanonicalProfile representation.
171
+ * @throws Error if sd.snapshot is missing.
172
+ */
173
+ export declare function buildCanonicalProfile(sd: StructureDefinition): CanonicalProfile;
174
+
175
+ /**
176
+ * Convert ElementDefinitionConstraint[] to Invariant[].
177
+ *
178
+ * Returns an empty array if constraints is undefined or empty.
179
+ *
180
+ * @param constraints - The FHIR constraint array from an ElementDefinition.
181
+ * @returns Normalized Invariant array.
182
+ */
183
+ export declare function buildInvariants(constraints: readonly ElementDefinitionConstraint[] | undefined): Invariant[];
184
+
185
+ /**
186
+ * Convert ElementDefinitionSlicing to SlicingDefinition.
187
+ *
188
+ * Returns undefined if slicing is undefined.
189
+ * Normalizes `ordered` to boolean (default false).
190
+ *
191
+ * @param slicing - The FHIR slicing from an ElementDefinition.
192
+ * @returns Normalized SlicingDefinition or undefined.
193
+ */
194
+ export declare function buildSlicingDefinition(slicing: ElementDefinitionSlicing | undefined): SlicingDefinition | undefined;
195
+
196
+ /**
197
+ * Convert ElementDefinitionType[] to TypeConstraint[].
198
+ *
199
+ * Returns an empty array if types is undefined or empty.
200
+ *
201
+ * @param types - The FHIR type array from an ElementDefinition.
202
+ * @returns Normalized TypeConstraint array.
203
+ */
204
+ export declare function buildTypeConstraints(types: readonly ElementDefinitionType[] | undefined): TypeConstraint[];
205
+
206
+ /**
207
+ * Build a PascalCase type name from path segments.
208
+ *
209
+ * @param components - Path segments (e.g., `['Patient', 'contact']`)
210
+ * @returns PascalCase type name (e.g., `'PatientContact'`)
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * buildTypeName(['Patient', 'contact']) // → 'PatientContact'
215
+ * buildTypeName(['Bundle', 'entry', 'request']) // → 'BundleEntryRequest'
216
+ * buildTypeName(['Patient']) // → 'Patient'
217
+ * ```
218
+ */
219
+ export declare function buildTypeName(components: string[]): string;
220
+
221
+ /**
222
+ * Describes a single error encountered while loading a StructureDefinition.
223
+ */
224
+ export declare interface BundleLoadError {
225
+ /** The name of the StructureDefinition that failed. */
226
+ name: string;
227
+ /** The canonical URL of the StructureDefinition that failed. */
228
+ url: string;
229
+ /** The error that occurred. */
230
+ error: Error;
231
+ /** Parse issues, if the failure was during parsing. */
232
+ parseIssues?: readonly ParseIssue[];
233
+ }
234
+
235
+ /**
236
+ * Options for filtering which StructureDefinitions to load from a bundle.
237
+ */
238
+ export declare interface BundleLoadOptions {
239
+ /** Only include entries where kind matches. Default: all kinds. */
240
+ filterKind?: StructureDefinitionKind | StructureDefinitionKind[];
241
+ /** Exclude abstract definitions. Default: false (include abstract). */
242
+ excludeAbstract?: boolean;
243
+ /** Only include entries where type matches one of these. */
244
+ filterTypes?: string[];
245
+ }
246
+
247
+ /**
248
+ * Result of loading one or more bundles.
249
+ */
250
+ export declare interface BundleLoadResult {
251
+ /** Successfully loaded CanonicalProfiles. */
252
+ profiles: CanonicalProfile[];
253
+ /** Errors encountered during loading (partial failures). */
254
+ errors: BundleLoadError[];
255
+ /** Summary statistics. */
256
+ stats: {
257
+ /** Total StructureDefinition entries found in bundle(s). */
258
+ total: number;
259
+ /** Successfully parsed and converted to CanonicalProfile. */
260
+ loaded: number;
261
+ /** Filtered out by options (kind, abstract, type). */
262
+ skipped: number;
263
+ /** Failed to parse or convert. */
264
+ failed: number;
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Minimal Bundle shape for type-safe access.
270
+ */
271
+ declare interface BundleShape {
272
+ resourceType: string;
273
+ entry?: Array<{
274
+ resource?: Record<string, unknown>;
275
+ }>;
276
+ }
277
+
278
+ /**
279
+ * A single resolved element within a CanonicalProfile.
280
+ *
281
+ * This is the internal, pre-resolved representation of an
282
+ * `ElementDefinition` from a StructureDefinition snapshot.
283
+ * All values are resolved and normalized for efficient downstream use.
284
+ *
285
+ * ## Key differences from ElementDefinition
286
+ *
287
+ * | Aspect | ElementDefinition (FHIR) | CanonicalElement (internal) |
288
+ * |--------|--------------------------|----------------------------|
289
+ * | `max` | `string` (`"1"`, `"*"`) | `number \| 'unbounded'` |
290
+ * | `mustSupport` | `boolean \| undefined` | `boolean` (always present) |
291
+ * | `isModifier` | `boolean \| undefined` | `boolean` (always present) |
292
+ * | `isSummary` | `boolean \| undefined` | `boolean` (always present) |
293
+ * | `constraints` | `array \| undefined` | `array` (always present, may be empty) |
294
+ * | `types` | `array \| undefined` | `array` (always present, may be empty) |
295
+ */
296
+ export declare interface CanonicalElement {
297
+ /** Element path (e.g., `Patient.name.given`). */
298
+ path: string;
299
+ /**
300
+ * Element id (e.g., `Patient.name.given`).
301
+ *
302
+ * In most cases identical to `path`, but may differ for sliced elements
303
+ * (e.g., `Patient.identifier:MRN`).
304
+ */
305
+ id: string;
306
+ /**
307
+ * Minimum cardinality.
308
+ *
309
+ * Resolved from `ElementDefinition.min`. Always a non-negative integer.
310
+ */
311
+ min: number;
312
+ /**
313
+ * Maximum cardinality.
314
+ *
315
+ * **Design decision:** Uses `number | 'unbounded'` instead of FHIR's
316
+ * `string` representation. The `"*"` from FHIR is converted to
317
+ * `'unbounded'` during snapshot resolution, eliminating the need for
318
+ * downstream code to repeatedly parse the string.
319
+ */
320
+ max: number | 'unbounded';
321
+ /**
322
+ * Allowed types for this element.
323
+ *
324
+ * Always an array (possibly empty). Empty means the element is a
325
+ * backbone element whose children define its structure.
326
+ */
327
+ types: TypeConstraint[];
328
+ /**
329
+ * Value set binding, if this element is coded.
330
+ */
331
+ binding?: BindingConstraint;
332
+ /**
333
+ * Formal constraints (invariants) on this element.
334
+ *
335
+ * **Design decision:** Always an array (possibly empty), never
336
+ * `undefined`. This simplifies downstream iteration — no need to
337
+ * check for `undefined` before looping.
338
+ */
339
+ constraints: Invariant[];
340
+ /**
341
+ * Slicing definition, if this element is a slicing root.
342
+ */
343
+ slicing?: SlicingDefinition;
344
+ /**
345
+ * Whether implementations must meaningfully support this element.
346
+ *
347
+ * **Design decision:** Always `boolean`, never `undefined`.
348
+ * Defaults to `false` during snapshot resolution.
349
+ */
350
+ mustSupport: boolean;
351
+ /**
352
+ * Whether this element can modify the meaning of other elements.
353
+ *
354
+ * **Design decision:** Always `boolean`, never `undefined`.
355
+ * Defaults to `false` during snapshot resolution.
356
+ */
357
+ isModifier: boolean;
358
+ /**
359
+ * Whether this element is included in summary views.
360
+ *
361
+ * **Design decision:** Always `boolean`, never `undefined`.
362
+ * Defaults to `false` during snapshot resolution.
363
+ */
364
+ isSummary: boolean;
365
+ /**
366
+ * Slice name for this element, if it is a named slice.
367
+ *
368
+ * Corresponds to `ElementDefinition.sliceName`. Only present on
369
+ * elements that represent a specific slice within a sliced array.
370
+ *
371
+ * @example `'MRN'` for `Patient.identifier:MRN`
372
+ */
373
+ sliceName?: string;
374
+ /**
375
+ * Fixed value constraint for this element.
376
+ *
377
+ * When present, the element value MUST exactly equal this value.
378
+ * Corresponds to `ElementDefinition.fixed[x]` in the FHIR spec.
379
+ *
380
+ * **Design decision:** Stored as `unknown` because fixed values can
381
+ * be any FHIR type (primitive or complex). The validator performs
382
+ * deep equality comparison at runtime.
383
+ */
384
+ fixed?: unknown;
385
+ /**
386
+ * Pattern value constraint for this element.
387
+ *
388
+ * When present, the element value must be a superset of this pattern —
389
+ * all fields in the pattern must exist in the value with matching values,
390
+ * but the value may contain additional fields.
391
+ * Corresponds to `ElementDefinition.pattern[x]` in the FHIR spec.
392
+ *
393
+ * **Design decision:** Stored as `unknown` for the same reason as `fixed`.
394
+ */
395
+ pattern?: unknown;
396
+ }
397
+
398
+ /**
399
+ * The internal, resolved representation of a FHIR StructureDefinition.
400
+ *
401
+ * A CanonicalProfile is produced by the snapshot generation algorithm
402
+ * (fhir-profile module) from a StructureDefinition. It flattens the
403
+ * inheritance chain and resolves all element constraints into a single,
404
+ * self-contained structure optimized for validation and runtime use.
405
+ *
406
+ * ## Usage
407
+ *
408
+ * ```typescript
409
+ * // Produced by fhir-profile (Phase 4):
410
+ * const profile: CanonicalProfile = snapshotGenerator.generate(structureDef);
411
+ *
412
+ * // O(1) element lookup:
413
+ * const nameElement = profile.elements.get('Patient.name');
414
+ *
415
+ * // Iteration in definition order (Map preserves insertion order):
416
+ * for (const [path, element] of profile.elements) { ... }
417
+ * ```
418
+ *
419
+ * ## Design note on `elements` ordering
420
+ *
421
+ * JavaScript `Map` preserves insertion order (ES2015+). The fhir-profile
422
+ * module MUST insert elements in the same order as the snapshot element
423
+ * array, so that iteration over `elements` yields elements in definition
424
+ * order. This is important for rendering and for algorithms that depend
425
+ * on element ordering (e.g., slicing evaluation).
426
+ */
427
+ export declare interface CanonicalProfile {
428
+ /**
429
+ * Canonical URL of this profile.
430
+ *
431
+ * Corresponds to `StructureDefinition.url`.
432
+ */
433
+ url: string;
434
+ /**
435
+ * Business version of this profile.
436
+ *
437
+ * Corresponds to `StructureDefinition.version`.
438
+ */
439
+ version?: string;
440
+ /**
441
+ * Computer-readable name.
442
+ *
443
+ * Corresponds to `StructureDefinition.name`.
444
+ */
445
+ name: string;
446
+ /**
447
+ * The kind of structure: primitive-type | complex-type | resource | logical.
448
+ *
449
+ * Corresponds to `StructureDefinition.kind`.
450
+ */
451
+ kind: StructureDefinitionKind;
452
+ /**
453
+ * The type defined or constrained (e.g., `Patient`, `Observation`).
454
+ *
455
+ * Corresponds to `StructureDefinition.type`.
456
+ */
457
+ type: string;
458
+ /**
459
+ * Canonical URL of the base profile, if any.
460
+ *
461
+ * Corresponds to `StructureDefinition.baseDefinition`.
462
+ */
463
+ baseProfile?: string;
464
+ /**
465
+ * Whether this type is abstract.
466
+ *
467
+ * Corresponds to `StructureDefinition.abstract`.
468
+ */
469
+ abstract: boolean;
470
+ /**
471
+ * specialization | constraint
472
+ *
473
+ * Corresponds to `StructureDefinition.derivation`.
474
+ */
475
+ derivation?: TypeDerivationRule;
476
+ /**
477
+ * All resolved elements, keyed by element path.
478
+ *
479
+ * **Design decision:** Uses `Map<string, CanonicalElement>` instead of
480
+ * an array for O(1) path lookup. `Map` preserves insertion order
481
+ * (ES2015+), so iteration yields elements in definition order matching
482
+ * the original snapshot element array.
483
+ *
484
+ * The fhir-profile module is responsible for populating this Map in
485
+ * the correct order during snapshot generation.
486
+ */
487
+ elements: Map<string, CanonicalElement>;
488
+ /**
489
+ * Inner types extracted from BackboneElement elements.
490
+ *
491
+ * Keyed by generated type name (e.g., `'PatientContact'`).
492
+ * Each inner type is itself a `CanonicalProfile` containing only
493
+ * the direct child elements of the BackboneElement.
494
+ *
495
+ * Populated by {@link extractInnerTypes} after snapshot generation.
496
+ * Inspired by Medplum's `InternalTypeSchema.innerTypes`.
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * const patientProfile = ...;
501
+ * const contactType = patientProfile.innerTypes?.get('PatientContact');
502
+ * // contactType.elements has: Patient.contact.relationship, Patient.contact.name, ...
503
+ * ```
504
+ */
505
+ innerTypes?: Map<string, CanonicalProfile>;
506
+ /**
507
+ * If this profile is an inner type, the generated type name of its parent.
508
+ *
509
+ * For example, `PatientContact` has `parentType: 'Patient'`.
510
+ * Top-level profiles have `parentType` as `undefined`.
511
+ */
512
+ parentType?: string;
513
+ }
514
+
515
+ /**
516
+ * Definition of a choice type [x] field.
517
+ *
518
+ * Each choice type field has a base name and a set of allowed type suffixes.
519
+ * The actual JSON property name is `baseName` + one of `allowedTypes`.
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * const field: ChoiceTypeField = {
524
+ * baseName: 'value',
525
+ * allowedTypes: ['String', 'Boolean', 'Integer', 'Quantity', ...],
526
+ * };
527
+ * // Matches: valueString, valueBoolean, valueInteger, valueQuantity, ...
528
+ * ```
529
+ */
530
+ export declare interface ChoiceTypeField {
531
+ /** Base property name (e.g., "value", "defaultValue", "fixed") */
532
+ readonly baseName: string;
533
+ /** Allowed type suffixes (e.g., ["String", "Boolean", "Quantity"]) */
534
+ readonly allowedTypes: readonly string[];
535
+ }
536
+
537
+ /**
538
+ * Parsed choice type value.
539
+ *
540
+ * Preserves the original JSON property name for round-trip serialization.
541
+ */
542
+ export declare interface ChoiceValue {
543
+ /** Type suffix (e.g., "String", "Quantity") */
544
+ readonly typeName: string;
545
+ /** The actual value from JSON */
546
+ readonly value: unknown;
547
+ /** Original JSON property name (e.g., "valueString") — for serialization */
548
+ readonly propertyName: string;
549
+ /** _element companion data, if present */
550
+ readonly elementExtension?: unknown;
551
+ }
552
+
553
+ /**
554
+ * Thrown when a circular `baseDefinition` chain is detected during
555
+ * inheritance resolution.
556
+ *
557
+ * @example
558
+ * ```typescript
559
+ * throw new CircularDependencyError([
560
+ * 'http://example.org/A',
561
+ * 'http://example.org/B',
562
+ * 'http://example.org/A', // cycle back to A
563
+ * ]);
564
+ * ```
565
+ */
566
+ export declare class CircularDependencyError extends ContextError {
567
+ readonly name = "CircularDependencyError";
568
+ /** The full chain of URLs that forms the cycle */
569
+ readonly chain: readonly string[];
570
+ constructor(chain: string[]);
571
+ }
572
+
573
+ /**
574
+ * A concept that may be defined by a formal reference to a terminology
575
+ * or ontology, or may be provided by text.
576
+ * @see https://hl7.org/fhir/R4/datatypes.html#CodeableConcept
577
+ */
578
+ export declare interface CodeableConcept extends Element {
579
+ /** Code defined by a terminology system (0..*) */
580
+ coding?: Coding[];
581
+ /** Plain text representation of the concept (0..1) */
582
+ text?: FhirString;
583
+ }
584
+
585
+ /**
586
+ * A reference to a code defined by a terminology system.
587
+ * @see https://hl7.org/fhir/R4/datatypes.html#Coding
588
+ */
589
+ export declare interface Coding extends Element {
590
+ /** Identity of the terminology system (0..1) */
591
+ system?: FhirUri;
592
+ /** Version of the system (0..1) */
593
+ version?: FhirString;
594
+ /** Symbol in syntax defined by the system (0..1) */
595
+ code?: FhirCode;
596
+ /** Representation defined by the system (0..1) */
597
+ display?: FhirString;
598
+ /** If this coding was chosen directly by the user (0..1) */
599
+ userSelected?: FhirBoolean;
600
+ }
601
+
602
+ /**
603
+ * Complex types — FHIR complex data types (non-resource).
604
+ */
605
+ export declare const COMPLEX_TYPES: readonly ["Address", "Age", "Annotation", "Attachment", "CodeableConcept", "Coding", "ContactDetail", "ContactPoint", "Count", "Distance", "Dosage", "Duration", "HumanName", "Identifier", "Meta", "Money", "Narrative", "Period", "Quantity", "Range", "Ratio", "Reference", "SampledData", "Signature", "Timing"];
606
+
607
+ /**
608
+ * A loader that delegates to an ordered list of child loaders.
609
+ *
610
+ * Resolution stops at the first loader that returns a non-null result.
611
+ * If a loader throws an error, the error is collected and the next
612
+ * loader is tried. If all loaders fail or return null, the first
613
+ * collected error (if any) is thrown.
614
+ *
615
+ * This follows the HAPI `ValidationSupportChain` pattern: record
616
+ * errors from individual loaders but continue trying remaining loaders.
617
+ *
618
+ * @example
619
+ * ```typescript
620
+ * const composite = new CompositeLoader([memoryLoader, fileLoader]);
621
+ * const sd = await composite.load(url);
622
+ * // Tries memoryLoader first, then fileLoader
623
+ * ```
624
+ */
625
+ export declare class CompositeLoader implements StructureDefinitionLoader {
626
+ private readonly _loaders;
627
+ /**
628
+ * @param loaders - Ordered list of loaders to try. First match wins.
629
+ * @throws Error if loaders array is empty
630
+ */
631
+ constructor(loaders: StructureDefinitionLoader[]);
632
+ load(url: string): Promise<StructureDefinition | null>;
633
+ canLoad(url: string): boolean;
634
+ getSourceType(): string;
635
+ /**
636
+ * Number of child loaders in the chain.
637
+ */
638
+ get loaderCount(): number;
639
+ }
640
+
641
+ /**
642
+ * The severity of a constraint violation.
643
+ * @see https://hl7.org/fhir/R4/valueset-constraint-severity.html
644
+ */
645
+ export declare type ConstraintSeverity = 'error' | 'warning';
646
+
647
+ /**
648
+ * Thrown when constraint merging detects an illegal tightening or
649
+ * incompatible constraint.
650
+ *
651
+ * This covers violations such as:
652
+ * - Cardinality loosening (`derived.min < base.min`)
653
+ * - Cardinality widening (`derived.max > base.max`)
654
+ * - Type expansion (derived types not a subset of base types)
655
+ * - Binding relaxation (relaxing a REQUIRED binding)
656
+ *
657
+ * Only thrown when {@link SnapshotGeneratorOptions.throwOnError} is `true`.
658
+ * Otherwise, violations are recorded as issues in the result.
659
+ *
660
+ * @example
661
+ * ```typescript
662
+ * throw new ConstraintViolationError(
663
+ * 'CARDINALITY_VIOLATION',
664
+ * 'Patient.identifier',
665
+ * 'Derived min (0) is less than base min (1)'
666
+ * );
667
+ * ```
668
+ */
669
+ export declare class ConstraintViolationError extends ProfileError {
670
+ readonly name = "ConstraintViolationError";
671
+ /** The type of constraint violation. */
672
+ readonly violationType: string;
673
+ /** The element path where the violation occurred. */
674
+ readonly path: string;
675
+ constructor(violationType: string, path: string, message: string);
676
+ }
677
+
678
+ /**
679
+ * Contact information for a person or organization.
680
+ * @see https://hl7.org/fhir/R4/metadatatypes.html#ContactDetail
681
+ */
682
+ export declare interface ContactDetail extends Element {
683
+ /** Name of an individual to contact (0..1) */
684
+ name?: FhirString;
685
+ /** Contact details for individual or organization (0..*) */
686
+ telecom?: ContactPoint[];
687
+ }
688
+
689
+ /**
690
+ * Details for all kinds of technology-mediated contact points.
691
+ * @see https://hl7.org/fhir/R4/datatypes.html#ContactPoint
692
+ */
693
+ export declare interface ContactPoint extends Element {
694
+ /** phone | fax | email | pager | url | sms | other (0..1) */
695
+ system?: FhirCode;
696
+ /** The actual contact point details (0..1) */
697
+ value?: FhirString;
698
+ /** home | work | temp | old | mobile (0..1) */
699
+ use?: FhirCode;
700
+ /** Specify preferred order of use (0..1) */
701
+ rank?: FhirPositiveInt;
702
+ /** Time period when the contact point was/is in use (0..1) */
703
+ period?: Period;
704
+ }
705
+
706
+ /**
707
+ * fhir-context — Error Types
708
+ *
709
+ * Structured error hierarchy for the FHIR context module.
710
+ * All errors extend {@link ContextError} so consumers can catch
711
+ * context-related failures with a single `catch` clause.
712
+ *
713
+ * Error hierarchy:
714
+ * ```
715
+ * ContextError (base)
716
+ * ├── ResourceNotFoundError
717
+ * ├── CircularDependencyError
718
+ * ├── LoaderError
719
+ * └── InvalidStructureDefinitionError
720
+ * ```
721
+ *
722
+ * @module fhir-context
723
+ */
724
+ /**
725
+ * Base error class for all fhir-context failures.
726
+ *
727
+ * Provides a stable `name` property and preserves the original `cause`
728
+ * when wrapping lower-level errors.
729
+ */
730
+ export declare class ContextError extends Error {
731
+ readonly name: string;
732
+ constructor(message: string, options?: ErrorOptions);
733
+ }
734
+
735
+ /**
736
+ * Runtime metrics for the {@link FhirContext}.
737
+ *
738
+ * Useful for monitoring cache effectiveness and diagnosing
739
+ * performance issues.
740
+ */
741
+ export declare interface ContextStatistics {
742
+ /** Total number of StructureDefinitions in the registry */
743
+ totalLoaded: number;
744
+ /** Number of `loadStructureDefinition` calls resolved from cache */
745
+ cacheHits: number;
746
+ /** Number of `loadStructureDefinition` calls that required loader delegation */
747
+ cacheMisses: number;
748
+ /** Total number of loader invocations across all loaders */
749
+ loaderCalls: number;
750
+ /** Number of inheritance chains resolved */
751
+ chainsResolved: number;
752
+ /** Number of `registerStructureDefinition` calls */
753
+ registrations: number;
754
+ }
755
+
756
+ /**
757
+ * Core clinical resources — commonly used FHIR resource types.
758
+ */
759
+ export declare const CORE_RESOURCES: readonly ["AllergyIntolerance", "Binary", "Bundle", "CarePlan", "Claim", "CodeSystem", "Condition", "DiagnosticReport", "DocumentReference", "Encounter", "Immunization", "Location", "Medication", "MedicationRequest", "Observation", "Organization", "Patient", "Practitioner", "Procedure", "Questionnaire", "ServiceRequest", "StructureDefinition", "ValueSet"];
760
+
761
+ /**
762
+ * Create a {@link DiffElementTracker} for a differential element.
763
+ *
764
+ * @param element - The differential ElementDefinition to track.
765
+ * @returns A tracker with `consumed` set to `false`.
766
+ */
767
+ export declare function createDiffTracker(element: ElementDefinition): DiffElementTracker;
768
+
769
+ /**
770
+ * Create a fresh statistics object with all counters at zero.
771
+ */
772
+ export declare function createEmptyStatistics(): ContextStatistics;
773
+
774
+ /**
775
+ * Create a single parse issue.
776
+ *
777
+ * Convenience factory to reduce boilerplate when constructing issues.
778
+ *
779
+ * @param severity - Error or warning
780
+ * @param code - Machine-readable error code
781
+ * @param message - Human-readable description
782
+ * @param path - JSON path where the issue was detected
783
+ */
784
+ export declare function createIssue(severity: ParseSeverity, code: ParseErrorCode, message: string, path: string): ParseIssue;
785
+
786
+ /**
787
+ * Create a default MergeContext.
788
+ */
789
+ export declare function createMergeContext(profileUrl: string, options?: {
790
+ fhirContext?: FhirContext;
791
+ maxDepth?: number;
792
+ }): MergeContext;
793
+
794
+ /**
795
+ * Create a {@link SnapshotIssue} with the given parameters.
796
+ *
797
+ * Convenience factory to reduce boilerplate when recording issues.
798
+ */
799
+ export declare function createSnapshotIssue(severity: SnapshotIssue['severity'], code: SnapshotIssueCode, message: string, path?: string, details?: string): SnapshotIssue;
800
+
801
+ /**
802
+ * Create a {@link ValidationIssue} with the given parameters.
803
+ *
804
+ * Convenience factory to reduce boilerplate when recording issues.
805
+ *
806
+ * @param severity - Issue severity level.
807
+ * @param code - Machine-readable issue code.
808
+ * @param message - Human-readable description.
809
+ * @param options - Optional path, expression, and diagnostics.
810
+ * @returns A frozen ValidationIssue object.
811
+ */
812
+ export declare function createValidationIssue(severity: ValidationIssue['severity'], code: ValidationIssueCode, message: string, options?: {
813
+ path?: string;
814
+ expression?: string;
815
+ diagnostics?: string;
816
+ }): ValidationIssue;
817
+
818
+ /**
819
+ * Minimal interface for loading a StructureDefinition by canonical URL.
820
+ *
821
+ * This decouples the resolver from the full {@link FhirContext} interface,
822
+ * making it independently testable. The `FhirContextImpl` class (Task 3.6)
823
+ * will satisfy this interface.
824
+ */
825
+ declare interface DefinitionProvider {
826
+ /**
827
+ * Load a StructureDefinition by canonical URL.
828
+ *
829
+ * Must throw {@link ResourceNotFoundError} if the URL cannot be resolved.
830
+ */
831
+ loadStructureDefinition(url: string): Promise<StructureDefinition>;
832
+ }
833
+
834
+ /**
835
+ * Tracks a differential element during snapshot generation.
836
+ *
837
+ * Implements the HAPI marker pattern where each differential element
838
+ * is tagged with `userData(GENERATED_IN_SNAPSHOT)` after being consumed
839
+ * by the merge algorithm. At the end of generation, any tracker with
840
+ * `consumed === false` indicates an unmatched differential element.
841
+ *
842
+ * @internal Used by {@link ElementMerger} and {@link SnapshotGenerator}.
843
+ */
844
+ export declare interface DiffElementTracker {
845
+ /** The original differential ElementDefinition. */
846
+ readonly element: ElementDefinition;
847
+ /**
848
+ * Whether this element has been consumed (matched and merged)
849
+ * during snapshot generation.
850
+ *
851
+ * Set to `true` by the merge algorithm when the element is
852
+ * successfully applied to the snapshot. Checked post-generation
853
+ * to detect unmatched differential elements.
854
+ */
855
+ consumed: boolean;
856
+ }
857
+
858
+ /**
859
+ * Detect whether diff matches constitute type slicing.
860
+ *
861
+ * Corresponds to HAPI's `diffsConstrainTypes()`. Type slicing is detected when:
862
+ * - Multiple diff matches exist
863
+ * - All diff matches constrain different types, OR
864
+ * - The base is a choice type `[x]` and diffs use concrete type paths
865
+ *
866
+ * @param diffMatches - The differential element trackers that matched a base path.
867
+ * @param basePath - The base element path.
868
+ * @param baseTypes - The base element's type list (optional).
869
+ * @returns `true` if the diffs represent type slicing.
870
+ */
871
+ export declare function diffsConstrainTypes(diffMatches: readonly DiffElementTracker[], basePath: string, baseTypes: readonly ElementDefinitionType[] | undefined): boolean;
872
+
873
+ /**
874
+ * How an element value is interpreted when discrimination is evaluated.
875
+ * @see https://hl7.org/fhir/R4/valueset-discriminator-type.html
876
+ */
877
+ export declare type DiscriminatorType = 'value' | 'exists' | 'pattern' | 'type' | 'profile';
878
+
879
+ /**
880
+ * A resource that includes narrative, extensions, and contained resources.
881
+ * Most FHIR resources inherit from DomainResource.
882
+ * @see https://hl7.org/fhir/R4/domainresource.html
883
+ */
884
+ export declare interface DomainResource extends Resource {
885
+ /** Text summary of the resource, for human interpretation (0..1) */
886
+ text?: Narrative;
887
+ /** Contained, inline Resources (0..*) */
888
+ contained?: Resource[];
889
+ /** Additional content defined by implementations (0..*) */
890
+ extension?: Extension[];
891
+ /** Extensions that cannot be ignored (0..*) */
892
+ modifierExtension?: Extension[];
893
+ }
894
+
895
+ /**
896
+ * Base definition for all elements in a resource.
897
+ * Every element in FHIR inherits from Element.
898
+ * @see https://hl7.org/fhir/R4/element.html
899
+ */
900
+ export declare interface Element {
901
+ /** Unique id for inter-element referencing (0..1) */
902
+ id?: FhirString;
903
+ /** Additional content defined by implementations (0..*) */
904
+ extension?: Extension[];
905
+ }
906
+
907
+ /**
908
+ * Captures constraints on each element within a resource, data type,
909
+ * or extension.
910
+ *
911
+ * ElementDefinition is the most complex data type in FHIR. Each instance
912
+ * describes a single element path (e.g., `Patient.name`, `Patient.name.given`)
913
+ * and carries all constraint information: cardinality, types, bindings,
914
+ * invariants, slicing, flags, and documentation.
915
+ *
916
+ * ElementDefinition appears in:
917
+ * - `StructureDefinition.snapshot.element` (complete, flattened)
918
+ * - `StructureDefinition.differential.element` (delta only)
919
+ *
920
+ * This interface extends BackboneElement (has `id`, `extension`,
921
+ * `modifierExtension`).
922
+ *
923
+ * @see https://hl7.org/fhir/R4/elementdefinition.html
924
+ */
925
+ export declare interface ElementDefinition extends BackboneElement {
926
+ /**
927
+ * Path of the element in the hierarchy of elements (1..1)
928
+ *
929
+ * The path is dot-separated, e.g., `Patient.name.given`.
930
+ * The first element in a snapshot always has a path equal to the
931
+ * resource/type name (e.g., `Patient`).
932
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.path
933
+ */
934
+ path: FhirString;
935
+ /**
936
+ * How this element is represented in instances (0..*)
937
+ *
938
+ * Controls serialization format (mainly relevant for XML).
939
+ * @see https://hl7.org/fhir/R4/valueset-property-representation.html
940
+ */
941
+ representation?: PropertyRepresentation[];
942
+ /**
943
+ * Name for this particular element (in a set of slices) (0..1)
944
+ *
945
+ * Unique within the context of the containing element. Used to
946
+ * identify slices in a slicing definition.
947
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.sliceName
948
+ */
949
+ sliceName?: FhirString;
950
+ /**
951
+ * If this slice definition constrains an inherited slice definition
952
+ * (or not) (0..1)
953
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.sliceIsConstraining
954
+ */
955
+ sliceIsConstraining?: FhirBoolean;
956
+ /**
957
+ * Name for element to display with or prompt for element (0..1)
958
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.label
959
+ */
960
+ label?: FhirString;
961
+ /**
962
+ * Corresponding codes in terminologies (0..*)
963
+ *
964
+ * Codes that define the meaning of this element, e.g., LOINC or
965
+ * SNOMED CT codes. Used for mapping and search.
966
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.code
967
+ */
968
+ code?: Coding[];
969
+ /**
970
+ * This element is sliced — slices follow (0..1)
971
+ *
972
+ * Defines how this element can be divided into a set of slices.
973
+ * Only appears on the "slicing root" element; individual slices
974
+ * are identified by `sliceName`.
975
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.slicing
976
+ */
977
+ slicing?: ElementDefinitionSlicing;
978
+ /**
979
+ * Concise definition for space-constrained presentations (0..1)
980
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.short
981
+ */
982
+ short?: FhirString;
983
+ /**
984
+ * Full formal definition of the element (0..1)
985
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.definition
986
+ */
987
+ definition?: FhirMarkdown;
988
+ /**
989
+ * Comments about the use of this element (0..1)
990
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.comment
991
+ */
992
+ comment?: FhirMarkdown;
993
+ /**
994
+ * Why this resource has been created (0..1)
995
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.requirements
996
+ */
997
+ requirements?: FhirMarkdown;
998
+ /**
999
+ * Other names (0..*)
1000
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.alias
1001
+ */
1002
+ alias?: FhirString[];
1003
+ /**
1004
+ * Minimum cardinality (0..1)
1005
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.min
1006
+ */
1007
+ min?: FhirUnsignedInt;
1008
+ /**
1009
+ * Maximum cardinality (number or "*") (0..1)
1010
+ *
1011
+ * A string value: either a non-negative integer or `"*"` for unbounded.
1012
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.max
1013
+ */
1014
+ max?: FhirString;
1015
+ /**
1016
+ * Base definition information for tools (0..1)
1017
+ *
1018
+ * Records the cardinality and path from the base StructureDefinition,
1019
+ * so tools can show what has changed in a derived profile without
1020
+ * needing to trace the full inheritance chain.
1021
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.base
1022
+ */
1023
+ base?: ElementDefinitionBase;
1024
+ /**
1025
+ * Reference to definition of content for the element (0..1)
1026
+ *
1027
+ * A URI that points to another element within the same
1028
+ * StructureDefinition, in the form `#<elementId>`. Indicates that
1029
+ * this element has the same meaning and constraints as the
1030
+ * referenced element.
1031
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.contentReference
1032
+ */
1033
+ contentReference?: FhirUri;
1034
+ /**
1035
+ * Data type and profile for this element (0..*)
1036
+ *
1037
+ * Defines the allowed types for this element. Multiple entries
1038
+ * indicate a choice type (e.g., value[x] can be valueString,
1039
+ * valueInteger, etc.).
1040
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.type
1041
+ */
1042
+ type?: ElementDefinitionType[];
1043
+ /**
1044
+ * Specified value if missing from instance (0..1)
1045
+ *
1046
+ * Choice type [x] — the actual JSON property will be
1047
+ * `defaultValueString`, `defaultValueBoolean`, etc.
1048
+ * Can be any FHIR data type.
1049
+ *
1050
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1051
+ * concrete dispatch in Phase 2.
1052
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.defaultValue_x_
1053
+ */
1054
+ defaultValue?: unknown;
1055
+ /**
1056
+ * Implicit meaning when this element is missing (0..1)
1057
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.meaningWhenMissing
1058
+ */
1059
+ meaningWhenMissing?: FhirMarkdown;
1060
+ /**
1061
+ * What the order of the elements means (0..1)
1062
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.orderMeaning
1063
+ */
1064
+ orderMeaning?: FhirString;
1065
+ /**
1066
+ * Value must be exactly this (0..1)
1067
+ *
1068
+ * Choice type [x] — `fixedString`, `fixedCoding`, etc.
1069
+ * If present, the element value in instances MUST match exactly.
1070
+ *
1071
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1072
+ * concrete dispatch in Phase 2.
1073
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.fixed_x_
1074
+ */
1075
+ fixed?: unknown;
1076
+ /**
1077
+ * Value must have at least these property values (0..1)
1078
+ *
1079
+ * Choice type [x] — `patternCodeableConcept`, `patternString`, etc.
1080
+ * More lenient than `fixed`: the instance value must contain at least
1081
+ * the properties and values specified by the pattern.
1082
+ *
1083
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1084
+ * concrete dispatch in Phase 2.
1085
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.pattern_x_
1086
+ */
1087
+ pattern?: unknown;
1088
+ /**
1089
+ * Example value (as defined for type) (0..*)
1090
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.example
1091
+ */
1092
+ example?: ElementDefinitionExample[];
1093
+ /**
1094
+ * Minimum allowed value (for some types) (0..1)
1095
+ *
1096
+ * Choice type [x] — `minValueDate`, `minValueInteger`, etc.
1097
+ * Only applicable to: date, dateTime, instant, time, decimal,
1098
+ * integer, positiveInt, unsignedInt, Quantity.
1099
+ *
1100
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1101
+ * concrete dispatch in Phase 2.
1102
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.minValue_x_
1103
+ */
1104
+ minValue?: unknown;
1105
+ /**
1106
+ * Maximum allowed value (for some types) (0..1)
1107
+ *
1108
+ * Choice type [x] — `maxValueDate`, `maxValueInteger`, etc.
1109
+ * Same type restrictions as `minValue`.
1110
+ *
1111
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1112
+ * concrete dispatch in Phase 2.
1113
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.maxValue_x_
1114
+ */
1115
+ maxValue?: unknown;
1116
+ /**
1117
+ * Max length for strings (0..1)
1118
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.maxLength
1119
+ */
1120
+ maxLength?: FhirInteger;
1121
+ /**
1122
+ * Reference to invariant about presence (0..*)
1123
+ *
1124
+ * A list of constraint keys (`ElementDefinitionConstraint.key`) that
1125
+ * are conditions on this element. When a constraint evaluates to false,
1126
+ * the element is not valid.
1127
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.condition
1128
+ */
1129
+ condition?: FhirId[];
1130
+ /**
1131
+ * Condition that must evaluate to true (0..*)
1132
+ *
1133
+ * Formal constraints (invariants) that must be met for the element
1134
+ * to be valid. Expressed as FHIRPath expressions.
1135
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.constraint
1136
+ */
1137
+ constraint?: ElementDefinitionConstraint[];
1138
+ /**
1139
+ * If the element must be supported (0..1)
1140
+ *
1141
+ * When `true`, implementations claiming conformance to this profile
1142
+ * MUST "meaningfully support" this element. The exact meaning of
1143
+ * mustSupport is defined per implementation guide.
1144
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.mustSupport
1145
+ */
1146
+ mustSupport?: FhirBoolean;
1147
+ /**
1148
+ * If this modifies the meaning of other elements (0..1)
1149
+ *
1150
+ * Modifier elements can change the interpretation of the containing
1151
+ * resource or element. Implementations MUST understand modifier elements.
1152
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.isModifier
1153
+ */
1154
+ isModifier?: FhirBoolean;
1155
+ /**
1156
+ * Reason that this element is marked as a modifier (0..1)
1157
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.isModifierReason
1158
+ */
1159
+ isModifierReason?: FhirString;
1160
+ /**
1161
+ * Include when _summary = true? (0..1)
1162
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.isSummary
1163
+ */
1164
+ isSummary?: FhirBoolean;
1165
+ /**
1166
+ * ValueSet details if this is coded (0..1)
1167
+ *
1168
+ * Binds this element to a specific value set. The `strength`
1169
+ * determines how strictly the binding applies.
1170
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.binding
1171
+ */
1172
+ binding?: ElementDefinitionBinding;
1173
+ /**
1174
+ * Map element to another set of definitions (0..*)
1175
+ *
1176
+ * Identifies a concept from an external specification (e.g., v2,
1177
+ * CDA, or a custom mapping) that corresponds to this element.
1178
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.mapping
1179
+ */
1180
+ mapping?: ElementDefinitionMapping[];
1181
+ }
1182
+
1183
+ /**
1184
+ * Information about the base definition of the element, provided to
1185
+ * make it unnecessary for tools to trace the deviation of the element
1186
+ * through the derived and related profiles.
1187
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.base
1188
+ */
1189
+ export declare interface ElementDefinitionBase extends Element {
1190
+ /** Path that identifies the base element (1..1) */
1191
+ path: FhirString;
1192
+ /** Min cardinality of the base element (1..1) */
1193
+ min: FhirUnsignedInt;
1194
+ /**
1195
+ * Max cardinality of the base element (1..1)
1196
+ *
1197
+ * A string value, either a number or "*" for unbounded.
1198
+ */
1199
+ max: FhirString;
1200
+ }
1201
+
1202
+ /**
1203
+ * Binds an element to a specific value set, indicating the degree of
1204
+ * conformance expectation.
1205
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.binding
1206
+ */
1207
+ export declare interface ElementDefinitionBinding extends Element {
1208
+ /**
1209
+ * required | extensible | preferred | example (1..1)
1210
+ *
1211
+ * Indicates the degree of conformance expectations associated with
1212
+ * this binding. Only `required` means mandatory in FHIR.
1213
+ * @see https://hl7.org/fhir/R4/valueset-binding-strength.html
1214
+ */
1215
+ strength: BindingStrength;
1216
+ /** Human explanation of the value set (0..1) */
1217
+ description?: FhirString;
1218
+ /**
1219
+ * Source of value set (0..1)
1220
+ *
1221
+ * Canonical URL reference to the value set bound to this element.
1222
+ */
1223
+ valueSet?: FhirCanonical;
1224
+ }
1225
+
1226
+ /**
1227
+ * Formal constraints (invariants) on the element that must be satisfied
1228
+ * for the element to be valid.
1229
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.constraint
1230
+ */
1231
+ export declare interface ElementDefinitionConstraint extends Element {
1232
+ /**
1233
+ * Target of 'condition' reference (1..1)
1234
+ *
1235
+ * Unique identifier for the constraint, used by `condition` fields
1236
+ * to reference which constraints apply.
1237
+ */
1238
+ key: FhirId;
1239
+ /** Why this constraint is necessary or appropriate (0..1) */
1240
+ requirements?: FhirString;
1241
+ /**
1242
+ * error | warning (1..1)
1243
+ * @see https://hl7.org/fhir/R4/valueset-constraint-severity.html
1244
+ */
1245
+ severity: ConstraintSeverity;
1246
+ /** Human description of constraint (1..1) */
1247
+ human: FhirString;
1248
+ /**
1249
+ * FHIRPath expression of constraint (0..1)
1250
+ *
1251
+ * A FHIRPath expression that must evaluate to `true` when
1252
+ * tested against the element and its children.
1253
+ */
1254
+ expression?: FhirString;
1255
+ /**
1256
+ * XPath expression of constraint (0..1)
1257
+ *
1258
+ * Deprecated in favor of `expression` (FHIRPath), but retained
1259
+ * for backward compatibility with older profiles.
1260
+ */
1261
+ xpath?: FhirString;
1262
+ /**
1263
+ * Reference to original source of constraint (0..1)
1264
+ *
1265
+ * Canonical URL of the StructureDefinition where this constraint
1266
+ * was originally defined.
1267
+ */
1268
+ source?: FhirCanonical;
1269
+ }
1270
+
1271
+ /**
1272
+ * A sample value for the element, providing an example for implementers.
1273
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.example
1274
+ */
1275
+ export declare interface ElementDefinitionExample extends Element {
1276
+ /** Describes the purpose of this example (1..1) */
1277
+ label: FhirString;
1278
+ /**
1279
+ * Value of Example (1..1)
1280
+ *
1281
+ * Choice type [x] — the actual property name in JSON will be
1282
+ * `valueString`, `valueBoolean`, `valueCoding`, etc.
1283
+ * Can be any FHIR data type.
1284
+ *
1285
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1286
+ * concrete dispatch in Phase 2.
1287
+ */
1288
+ value: unknown;
1289
+ }
1290
+
1291
+ /**
1292
+ * Identifies a concept from an external specification that roughly
1293
+ * corresponds to this element.
1294
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.mapping
1295
+ */
1296
+ export declare interface ElementDefinitionMapping extends Element {
1297
+ /**
1298
+ * Reference to mapping declaration (1..1)
1299
+ *
1300
+ * An internal reference to the StructureDefinition.mapping.identity
1301
+ * that this element mapping refers to.
1302
+ */
1303
+ identity: FhirId;
1304
+ /** Computable language of mapping (0..1) */
1305
+ language?: FhirCode;
1306
+ /** Details of the mapping (1..1) */
1307
+ map: FhirString;
1308
+ /** Comments about the mapping (0..1) */
1309
+ comment?: FhirString;
1310
+ }
1311
+
1312
+ /**
1313
+ * How an element is sliced — defines the discriminator(s) and rules
1314
+ * for matching slices in an instance.
1315
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.slicing
1316
+ */
1317
+ export declare interface ElementDefinitionSlicing extends Element {
1318
+ /**
1319
+ * Element values that are used to distinguish the slices (0..*)
1320
+ *
1321
+ * Each discriminator specifies a path and a type that together
1322
+ * identify which slice a given element instance belongs to.
1323
+ */
1324
+ discriminator?: SlicingDiscriminator[];
1325
+ /** Text description of how slicing works (or in profile determine how slicing is used) (0..1) */
1326
+ description?: FhirString;
1327
+ /** If elements must be in same order as slices (0..1) */
1328
+ ordered?: FhirBoolean;
1329
+ /**
1330
+ * closed | open | openAtEnd (1..1)
1331
+ *
1332
+ * - `closed`: no additional content allowed beyond the defined slices
1333
+ * - `open`: additional content allowed anywhere
1334
+ * - `openAtEnd`: additional content allowed, but only at the end
1335
+ * @see https://hl7.org/fhir/R4/valueset-resource-slicing-rules.html
1336
+ */
1337
+ rules: SlicingRules;
1338
+ }
1339
+
1340
+ /**
1341
+ * The data type or resource that is a permitted type for the element.
1342
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.type
1343
+ */
1344
+ export declare interface ElementDefinitionType extends Element {
1345
+ /**
1346
+ * Data type or Resource (name) (1..1)
1347
+ *
1348
+ * The URI of the data type or resource, e.g., `http://hl7.org/fhirpath/System.String`
1349
+ * for primitives or a simple name like `string`, `Patient`, `Reference`.
1350
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.type.code
1351
+ */
1352
+ code: FhirUri;
1353
+ /**
1354
+ * Profiles (StructureDefinition or IG) — one of which this type must
1355
+ * conform to (0..*)
1356
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.type.profile
1357
+ */
1358
+ profile?: FhirCanonical[];
1359
+ /**
1360
+ * Profile (StructureDefinition or IG) on the Reference target —
1361
+ * one of which the reference must conform to (0..*)
1362
+ *
1363
+ * Only meaningful when `code` is `Reference` or `canonical`.
1364
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.type.targetProfile
1365
+ */
1366
+ targetProfile?: FhirCanonical[];
1367
+ /**
1368
+ * contained | referenced | bundled (0..*)
1369
+ *
1370
+ * How resource references are aggregated. Only meaningful when
1371
+ * `code` is `Reference`.
1372
+ * @see https://hl7.org/fhir/R4/valueset-resource-aggregation-mode.html
1373
+ */
1374
+ aggregation?: AggregationMode[];
1375
+ /**
1376
+ * either | independent | specific (0..1)
1377
+ *
1378
+ * Whether references need to be version-specific.
1379
+ * @see https://hl7.org/fhir/R4/valueset-reference-version-rules.html
1380
+ */
1381
+ versioning?: ReferenceVersionRules;
1382
+ }
1383
+
1384
+ /**
1385
+ * Ensure all elements have an `id` property.
1386
+ *
1387
+ * If an element lacks an `id`, generates one from its path and sliceName.
1388
+ * This follows the FHIR convention:
1389
+ * - Unsliced: `id = path` (e.g., `"Patient.name"`)
1390
+ * - Sliced: `id = path:sliceName` (e.g., `"Patient.identifier:MRN"`)
1391
+ *
1392
+ * Corresponds to HAPI's `setIds()`.
1393
+ *
1394
+ * @param elements - The elements to process (mutated in place).
1395
+ * @param resourceType - The resource type name (used for the root element).
1396
+ */
1397
+ export declare function ensureElementIds(elements: ElementDefinition[], resourceType?: string): void;
1398
+
1399
+ /**
1400
+ * Evaluate a FHIRPath expression against a resource or other object.
1401
+ * Accepts raw values (auto-wrapped in TypedValue) or pre-wrapped TypedValue arrays.
1402
+ *
1403
+ * @param expression - The FHIRPath expression string or pre-parsed AST.
1404
+ * @param input - The resource or object to evaluate against.
1405
+ * @returns Array of result values (unwrapped from TypedValue).
1406
+ */
1407
+ export declare function evalFhirPath(expression: string | FhirPathAtom, input: unknown): unknown[];
1408
+
1409
+ /**
1410
+ * Evaluate a FHIRPath expression and return a boolean result.
1411
+ *
1412
+ * Useful for invariant validation where the expression must evaluate to `true`.
1413
+ * Uses FHIRPath boolean semantics: empty → false, single truthy → true.
1414
+ *
1415
+ * @param expression - FHIRPath expression string or pre-parsed AST.
1416
+ * @param input - The resource or typed values to evaluate against.
1417
+ * @param variables - Optional variable bindings.
1418
+ * @returns Boolean result of the expression.
1419
+ */
1420
+ export declare function evalFhirPathBoolean(expression: string | FhirPathAtom, input: unknown, variables?: Record<string, TypedValue>): boolean;
1421
+
1422
+ /**
1423
+ * Evaluate a FHIRPath expression and return the first result as a string.
1424
+ *
1425
+ * Useful for extracting display values, identifiers, etc.
1426
+ *
1427
+ * @param expression - FHIRPath expression string or pre-parsed AST.
1428
+ * @param input - The resource or typed values to evaluate against.
1429
+ * @param variables - Optional variable bindings.
1430
+ * @returns The first result value as a string, or `undefined` if empty.
1431
+ */
1432
+ export declare function evalFhirPathString(expression: string | FhirPathAtom, input: unknown, variables?: Record<string, TypedValue>): string | undefined;
1433
+
1434
+ /**
1435
+ * Evaluate a FHIRPath expression against typed input values.
1436
+ *
1437
+ * @param expression - The FHIRPath expression string or pre-parsed AST.
1438
+ * @param input - Array of TypedValue inputs.
1439
+ * @param variables - Optional variable bindings.
1440
+ * @returns Array of TypedValue results.
1441
+ */
1442
+ export declare function evalFhirPathTyped(expression: string | FhirPathAtom, input: TypedValue[], variables?: Record<string, TypedValue>): TypedValue[];
1443
+
1444
+ /**
1445
+ * An Extension: additional information that is not part of the basic
1446
+ * definition of the resource.
1447
+ * @see https://hl7.org/fhir/R4/extensibility.html#Extension
1448
+ */
1449
+ export declare interface Extension extends Element {
1450
+ /** Identifies the meaning of the extension (1..1) */
1451
+ url: FhirUri;
1452
+ /**
1453
+ * Value of extension (0..1).
1454
+ *
1455
+ * Choice type [x] — the actual property name in JSON will be
1456
+ * `valueString`, `valueCode`, `valueBoolean`, `valueCoding`, etc.
1457
+ * Allows **all** FHIR data types (~50+ types).
1458
+ *
1459
+ * Stage-1: represented as `unknown`; fhir-parser will handle
1460
+ * concrete dispatch in Phase 2.
1461
+ * @see https://hl7.org/fhir/R4/extensibility-definitions.html#Extension.value_x_
1462
+ */
1463
+ value?: unknown;
1464
+ }
1465
+
1466
+ /**
1467
+ * The context type for an extension definition.
1468
+ * @see https://hl7.org/fhir/R4/valueset-extension-context-type.html
1469
+ */
1470
+ export declare type ExtensionContextType = 'fhirpath' | 'element' | 'extension';
1471
+
1472
+ /**
1473
+ * Extract the type name from a concrete choice path given the choice base.
1474
+ *
1475
+ * @example
1476
+ * extractChoiceTypeName('Observation.value[x]', 'Observation.valueString') // 'String'
1477
+ * extractChoiceTypeName('Observation.value[x]', 'Observation.valueQuantity') // 'Quantity'
1478
+ * extractChoiceTypeName('Observation.value[x]', 'Observation.code') // undefined
1479
+ */
1480
+ export declare function extractChoiceTypeName(choicePath: string, concretePath: string): string | undefined;
1481
+
1482
+ /**
1483
+ * Extract inner types from a CanonicalProfile.
1484
+ *
1485
+ * Scans the profile's elements for BackboneElement/Element types and creates
1486
+ * independent `CanonicalProfile` instances for each, containing only their
1487
+ * direct child elements.
1488
+ *
1489
+ * The returned Map is keyed by the generated type name (e.g., `'PatientContact'`).
1490
+ * Each inner type has its `parentType` set to the profile's type name.
1491
+ *
1492
+ * **Note:** This function also handles nested BackboneElements. For example,
1493
+ * if `Bundle.entry` is a BackboneElement containing `Bundle.entry.request`
1494
+ * (also a BackboneElement), both `BundleEntry` and `BundleEntryRequest` will
1495
+ * be extracted. `BundleEntryRequest` will have `parentType: 'BundleEntry'`.
1496
+ *
1497
+ * @param profile - The CanonicalProfile to extract inner types from
1498
+ * @returns Map of inner type name → CanonicalProfile
1499
+ *
1500
+ * @example
1501
+ * ```typescript
1502
+ * const innerTypes = extractInnerTypes(patientProfile);
1503
+ * // innerTypes.get('PatientContact') → CanonicalProfile for Patient.contact
1504
+ * // innerTypes.get('PatientCommunication') → CanonicalProfile for Patient.communication
1505
+ * // innerTypes.get('PatientLink') → CanonicalProfile for Patient.link
1506
+ * ```
1507
+ */
1508
+ export declare function extractInnerTypes(profile: CanonicalProfile): Map<string, CanonicalProfile>;
1509
+
1510
+ /**
1511
+ * Extract the first slice name from an element id.
1512
+ *
1513
+ * @example
1514
+ * extractSliceName('Patient.identifier:MRN') // 'MRN'
1515
+ * extractSliceName('Patient.identifier:MRN.system') // 'MRN'
1516
+ * extractSliceName('Patient.identifier') // undefined
1517
+ */
1518
+ export declare function extractSliceName(elementId: string): string | undefined;
1519
+
1520
+ /**
1521
+ * fhir-validator — Path Extractor
1522
+ *
1523
+ * Extracts values from FHIR resource instances using element paths.
1524
+ * Handles nested objects, arrays, and choice type (`[x]`) paths.
1525
+ *
1526
+ * This is the core utility that bridges CanonicalProfile element paths
1527
+ * (e.g., `Patient.name.family`) to actual values in a resource JSON object.
1528
+ *
1529
+ * @module fhir-validator
1530
+ */
1531
+ /**
1532
+ * Extract values from a resource instance using an element path.
1533
+ *
1534
+ * Navigates the resource object following the dot-separated path segments.
1535
+ * Arrays are automatically expanded — if an intermediate node is an array,
1536
+ * extraction continues into each element.
1537
+ *
1538
+ * @param resource - The resource object to extract from.
1539
+ * @param path - Element path (e.g., `'Patient.name.family'`).
1540
+ * @returns Array of extracted values (empty if path not found).
1541
+ *
1542
+ * @example
1543
+ * ```typescript
1544
+ * const patient = {
1545
+ * resourceType: 'Patient',
1546
+ * name: [
1547
+ * { family: 'Smith', given: ['John', 'James'] },
1548
+ * { family: 'Doe' },
1549
+ * ],
1550
+ * };
1551
+ *
1552
+ * extractValues(patient, 'Patient.name')
1553
+ * // → [{ family: 'Smith', given: ['John', 'James'] }, { family: 'Doe' }]
1554
+ *
1555
+ * extractValues(patient, 'Patient.name.family')
1556
+ * // → ['Smith', 'Doe']
1557
+ *
1558
+ * extractValues(patient, 'Patient.name.given')
1559
+ * // → ['John', 'James']
1560
+ * ```
1561
+ */
1562
+ export declare function extractValues(resource: Record<string, unknown>, path: string): unknown[];
1563
+
1564
+ /**
1565
+ * FHIR base64Binary: base64 encoded content (RFC 4648).
1566
+ * Regex: `(\s*([0-9a-zA-Z\+\/\=]){4}\s*)+`
1567
+ * @see https://hl7.org/fhir/R4/datatypes.html#base64Binary
1568
+ */
1569
+ export declare type FhirBase64Binary = Branded<string, 'FhirBase64Binary'>;
1570
+
1571
+ /**
1572
+ * FHIR boolean: true | false
1573
+ * @see https://hl7.org/fhir/R4/datatypes.html#boolean
1574
+ */
1575
+ export declare type FhirBoolean = Branded<boolean, 'FhirBoolean'>;
1576
+
1577
+ /**
1578
+ * FHIR canonical: a URI that refers to a resource by its canonical URL,
1579
+ * optionally with a version suffix `|version`.
1580
+ * @see https://hl7.org/fhir/R4/datatypes.html#canonical
1581
+ */
1582
+ export declare type FhirCanonical = Branded<string, 'FhirCanonical'>;
1583
+
1584
+ /**
1585
+ * FHIR code: a string that is constrained to the set of allowed values
1586
+ * from a controlled vocabulary (value set).
1587
+ * Regex: `[^\s]+(\s[^\s]+)*`
1588
+ * @see https://hl7.org/fhir/R4/datatypes.html#code
1589
+ */
1590
+ export declare type FhirCode = Branded<string, 'FhirCode'>;
1591
+
1592
+ /**
1593
+ * Central registry and lifecycle manager for FHIR StructureDefinitions.
1594
+ *
1595
+ * `FhirContext` is the primary entry point for accessing FHIR definitions
1596
+ * at runtime. It manages loading, caching, and resolution of
1597
+ * StructureDefinitions from one or more sources.
1598
+ *
1599
+ * Conceptual mapping:
1600
+ * - HAPI `FhirContext` → registry + lifecycle
1601
+ * - HAPI `IValidationSupport` → loader delegation
1602
+ *
1603
+ * Phase 4 (`fhir-profile`) will use this interface to load base definitions
1604
+ * during snapshot generation.
1605
+ *
1606
+ * @example
1607
+ * ```typescript
1608
+ * const context = new FhirContextImpl({ loaders: [memoryLoader, fileLoader] });
1609
+ * await context.preloadCoreDefinitions();
1610
+ *
1611
+ * const patient = await context.loadStructureDefinition(
1612
+ * 'http://hl7.org/fhir/StructureDefinition/Patient'
1613
+ * );
1614
+ * const chain = await context.resolveInheritanceChain(patient.url!);
1615
+ * // → ['http://hl7.org/fhir/StructureDefinition/Patient',
1616
+ * // 'http://hl7.org/fhir/StructureDefinition/DomainResource',
1617
+ * // 'http://hl7.org/fhir/StructureDefinition/Resource']
1618
+ * ```
1619
+ */
1620
+ export declare interface FhirContext {
1621
+ /**
1622
+ * Load a StructureDefinition by canonical URL.
1623
+ *
1624
+ * Resolution order:
1625
+ * 1. Check internal registry (cache hit)
1626
+ * 2. Delegate to configured loaders (cache miss)
1627
+ * 3. Parse, validate, and register the result
1628
+ *
1629
+ * Supports versioned URLs in `url|version` format
1630
+ * (e.g., `"http://example.org/Profile|1.0.0"`).
1631
+ *
1632
+ * @param url - Canonical URL, optionally with `|version` suffix
1633
+ * @returns Resolved StructureDefinition
1634
+ * @throws {@link ResourceNotFoundError} if no loader can resolve the URL
1635
+ * @throws {@link LoaderError} if a loader fails during loading
1636
+ * @throws {@link InvalidStructureDefinitionError} if the loaded resource is malformed
1637
+ */
1638
+ loadStructureDefinition(url: string): Promise<StructureDefinition>;
1639
+ /**
1640
+ * Synchronously retrieve a StructureDefinition from the registry.
1641
+ *
1642
+ * Does **not** trigger any loader — only checks the in-memory registry.
1643
+ * Use {@link loadStructureDefinition} if you need on-demand loading.
1644
+ *
1645
+ * @param url - Canonical URL (with optional `|version`)
1646
+ * @returns The cached StructureDefinition, or `undefined` if not loaded
1647
+ */
1648
+ getStructureDefinition(url: string): StructureDefinition | undefined;
1649
+ /**
1650
+ * Check whether a StructureDefinition is present in the registry.
1651
+ *
1652
+ * @param url - Canonical URL (with optional `|version`)
1653
+ */
1654
+ hasStructureDefinition(url: string): boolean;
1655
+ /**
1656
+ * Resolve the full inheritance chain for a profile.
1657
+ *
1658
+ * Walks the `baseDefinition` links from the given URL up to the root
1659
+ * resource type (e.g., `Resource`). Each base is loaded on demand if
1660
+ * not already in the registry.
1661
+ *
1662
+ * @param url - Canonical URL of the starting profile
1663
+ * @returns Array of canonical URLs from child to root
1664
+ * (e.g., `[ChinesePatient, Patient, DomainResource, Resource]`)
1665
+ * @throws {@link CircularDependencyError} if a cycle is detected
1666
+ * @throws {@link ResourceNotFoundError} if a base definition cannot be found
1667
+ */
1668
+ resolveInheritanceChain(url: string): Promise<string[]>;
1669
+ /**
1670
+ * Register a StructureDefinition in the registry.
1671
+ *
1672
+ * This is used for:
1673
+ * - Manually adding definitions (e.g., custom profiles)
1674
+ * - Phase 4: caching generated snapshots back into the context
1675
+ *
1676
+ * If a definition with the same URL (and version) already exists,
1677
+ * it will be replaced and any cached inheritance chains invalidated.
1678
+ *
1679
+ * @param sd - The StructureDefinition to register
1680
+ * @throws {@link InvalidStructureDefinitionError} if `sd.url` is missing
1681
+ */
1682
+ registerStructureDefinition(sd: StructureDefinition): void;
1683
+ /**
1684
+ * Preload FHIR R4 core StructureDefinitions.
1685
+ *
1686
+ * Loads base resource types (Resource, DomainResource, Patient,
1687
+ * Observation, etc.) into the registry so they are available
1688
+ * synchronously via {@link getStructureDefinition}.
1689
+ *
1690
+ * Should be called once during application initialization.
1691
+ */
1692
+ preloadCoreDefinitions(): Promise<void>;
1693
+ /**
1694
+ * Return runtime statistics for monitoring and diagnostics.
1695
+ */
1696
+ getStatistics(): ContextStatistics;
1697
+ /**
1698
+ * Register a CanonicalProfile and its extracted InnerTypes.
1699
+ *
1700
+ * This is the primary method for making InnerTypes available for
1701
+ * downstream consumption (UI forms, recursive validation, etc.).
1702
+ * Typically called after snapshot generation + `extractInnerTypes()`.
1703
+ *
1704
+ * @param profile - The CanonicalProfile (with innerTypes populated)
1705
+ */
1706
+ registerCanonicalProfile(profile: CanonicalProfile): void;
1707
+ /**
1708
+ * Retrieve an InnerType schema by its generated type name.
1709
+ *
1710
+ * @param typeName - Generated type name (e.g., `'PatientContact'`)
1711
+ * @returns The InnerType CanonicalProfile, or `undefined` if not registered
1712
+ */
1713
+ getInnerType(typeName: string): CanonicalProfile | undefined;
1714
+ /**
1715
+ * Check whether an InnerType is registered.
1716
+ *
1717
+ * @param typeName - Generated type name (e.g., `'PatientContact'`)
1718
+ */
1719
+ hasInnerType(typeName: string): boolean;
1720
+ /**
1721
+ * Release all cached data and reset internal state.
1722
+ *
1723
+ * After calling `dispose()`, the context must be re-initialized
1724
+ * (e.g., by calling {@link preloadCoreDefinitions} again).
1725
+ */
1726
+ dispose(): void;
1727
+ }
1728
+
1729
+ /**
1730
+ * Concrete implementation of {@link FhirContext}.
1731
+ *
1732
+ * @example
1733
+ * ```typescript
1734
+ * const ctx = new FhirContextImpl({
1735
+ * loaders: [memoryLoader, fileLoader],
1736
+ * });
1737
+ * await ctx.preloadCoreDefinitions();
1738
+ *
1739
+ * const patient = await ctx.loadStructureDefinition(
1740
+ * 'http://hl7.org/fhir/StructureDefinition/Patient'
1741
+ * );
1742
+ * ```
1743
+ */
1744
+ export declare class FhirContextImpl implements FhirContext {
1745
+ private readonly _registry;
1746
+ private readonly _resolver;
1747
+ private readonly _loader;
1748
+ private readonly _options;
1749
+ private readonly _stats;
1750
+ private readonly _innerTypes;
1751
+ private readonly _canonicalProfiles;
1752
+ private _disposed;
1753
+ constructor(options: FhirContextOptions);
1754
+ loadStructureDefinition(url: string): Promise<StructureDefinition>;
1755
+ getStructureDefinition(url: string): StructureDefinition | undefined;
1756
+ hasStructureDefinition(url: string): boolean;
1757
+ resolveInheritanceChain(url: string): Promise<string[]>;
1758
+ registerStructureDefinition(sd: StructureDefinition): void;
1759
+ preloadCoreDefinitions(): Promise<void>;
1760
+ getStatistics(): ContextStatistics;
1761
+ registerCanonicalProfile(profile: CanonicalProfile): void;
1762
+ getInnerType(typeName: string): CanonicalProfile | undefined;
1763
+ hasInnerType(typeName: string): boolean;
1764
+ dispose(): void;
1765
+ /**
1766
+ * Validate that a StructureDefinition has the minimum required fields.
1767
+ */
1768
+ private _validateStructureDefinition;
1769
+ /**
1770
+ * Guard against use after dispose.
1771
+ */
1772
+ private _ensureNotDisposed;
1773
+ /**
1774
+ * Direct access to the internal registry (for diagnostics).
1775
+ */
1776
+ get registry(): StructureDefinitionRegistry;
1777
+ /**
1778
+ * Direct access to the internal resolver (for diagnostics).
1779
+ */
1780
+ get resolver(): InheritanceChainResolver;
1781
+ }
1782
+
1783
+ /**
1784
+ * Configuration options for creating a {@link FhirContext}.
1785
+ */
1786
+ export declare interface FhirContextOptions {
1787
+ /**
1788
+ * One or more loaders to use for resolving StructureDefinitions.
1789
+ *
1790
+ * When multiple loaders are provided, they are tried in order
1791
+ * (first match wins — chain of responsibility pattern).
1792
+ */
1793
+ loaders: StructureDefinitionLoader[];
1794
+ /**
1795
+ * Whether to automatically call {@link FhirContext.preloadCoreDefinitions}
1796
+ * during initialization.
1797
+ *
1798
+ * @defaultValue `true`
1799
+ */
1800
+ preloadCore?: boolean;
1801
+ /**
1802
+ * Path to the FHIR R4 specification directory.
1803
+ *
1804
+ * Used by the core definition preloader to locate `profiles-resources.json`
1805
+ * and `profiles-types.json`.
1806
+ *
1807
+ * @defaultValue `undefined` (uses bundled definitions)
1808
+ */
1809
+ specDirectory?: string;
1810
+ }
1811
+
1812
+ /**
1813
+ * FHIR date: a date or partial date (year, year-month, or year-month-day).
1814
+ * No timezone. No time.
1815
+ * Format: `YYYY(-MM(-DD)?)?`
1816
+ * Regex: `([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2][0-9]|3[0-1]))?)?`
1817
+ * @see https://hl7.org/fhir/R4/datatypes.html#date
1818
+ */
1819
+ export declare type FhirDate = Branded<string, 'FhirDate'>;
1820
+
1821
+ /**
1822
+ * FHIR dateTime: a date, date-time, or partial date with optional time and timezone.
1823
+ * Format: `YYYY(-MM(-DD(Thh:mm:ss(.sss)?(Z|(+|-)hh:mm))?)?)?`
1824
+ * @see https://hl7.org/fhir/R4/datatypes.html#dateTime
1825
+ */
1826
+ export declare type FhirDateTime = Branded<string, 'FhirDateTime'>;
1827
+
1828
+ /**
1829
+ * FHIR decimal: rational numbers with implicit precision.
1830
+ * Regex: `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`
1831
+ * Note: precision of the decimal value has significance
1832
+ * (e.g., 0.010 is regarded as different to 0.01).
1833
+ * @see https://hl7.org/fhir/R4/datatypes.html#decimal
1834
+ */
1835
+ export declare type FhirDecimal = Branded<number, 'FhirDecimal'>;
1836
+
1837
+ /**
1838
+ * FHIR id: any combination of upper- or lower-case ASCII letters,
1839
+ * numerals, '-', and '.', with a length limit of 64 characters.
1840
+ * Regex: `[A-Za-z0-9\-\.]{1,64}`
1841
+ * @see https://hl7.org/fhir/R4/datatypes.html#id
1842
+ */
1843
+ export declare type FhirId = Branded<string, 'FhirId'>;
1844
+
1845
+ /**
1846
+ * FHIR instant: an instant in time with at least second precision
1847
+ * and always includes a timezone.
1848
+ * Format: `YYYY-MM-DDThh:mm:ss.sss+zz:zz`
1849
+ * Regex: `([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))`
1850
+ * @see https://hl7.org/fhir/R4/datatypes.html#instant
1851
+ */
1852
+ export declare type FhirInstant = Branded<string, 'FhirInstant'>;
1853
+
1854
+ /**
1855
+ * FHIR integer: whole numbers in the range -2,147,483,648..2,147,483,647
1856
+ * Regex: `[0]|[-+]?[1-9][0-9]*`
1857
+ * @see https://hl7.org/fhir/R4/datatypes.html#integer
1858
+ */
1859
+ export declare type FhirInteger = Branded<number, 'FhirInteger'>;
1860
+
1861
+ /**
1862
+ * FHIR markdown: a FHIR string that may contain markdown syntax.
1863
+ * Systems are not required to have markdown support.
1864
+ * @see https://hl7.org/fhir/R4/datatypes.html#markdown
1865
+ */
1866
+ export declare type FhirMarkdown = Branded<string, 'FhirMarkdown'>;
1867
+
1868
+ /**
1869
+ * FHIR oid: an OID represented as a URI (RFC 3001).
1870
+ * Format: `urn:oid:[0-2](\.(0|[1-9][0-9]*))+`
1871
+ * @see https://hl7.org/fhir/R4/datatypes.html#oid
1872
+ */
1873
+ export declare type FhirOid = Branded<string, 'FhirOid'>;
1874
+
1875
+ /**
1876
+ * Root wrapper atom for a parsed FHIRPath expression.
1877
+ * Iterates over each input element, setting `$this` for each evaluation.
1878
+ */
1879
+ declare class FhirPathAtom implements Atom {
1880
+ readonly original: string;
1881
+ readonly child: Atom;
1882
+ constructor(original: string, child: Atom);
1883
+ eval(context: AtomContext, input: TypedValue[]): TypedValue[];
1884
+ toString(): string;
1885
+ }
1886
+
1887
+ /**
1888
+ * FHIR positiveInt: positive integer in the range 1..2,147,483,647.
1889
+ * Regex: `+?[1-9][0-9]*`
1890
+ * @see https://hl7.org/fhir/R4/datatypes.html#positiveInt
1891
+ */
1892
+ export declare type FhirPositiveInt = Branded<number, 'FhirPositiveInt'>;
1893
+
1894
+ /**
1895
+ * FHIR string: a sequence of Unicode characters.
1896
+ * Regex: `[ \r\n\t\S]+`
1897
+ * Note: strings SHOULD not contain Unicode character points below 32,
1898
+ * except for horizontal tab, carriage return, and line feed.
1899
+ * @see https://hl7.org/fhir/R4/datatypes.html#string
1900
+ */
1901
+ export declare type FhirString = Branded<string, 'FhirString'>;
1902
+
1903
+ /**
1904
+ * FHIR time: a time of day with no date and no timezone.
1905
+ * Format: `hh:mm:ss(.sss)?`
1906
+ * Regex: `([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\.[0-9]+)?`
1907
+ * @see https://hl7.org/fhir/R4/datatypes.html#time
1908
+ */
1909
+ export declare type FhirTime = Branded<string, 'FhirTime'>;
1910
+
1911
+ /**
1912
+ * FHIR unsignedInt: non-negative integer in the range 0..2,147,483,647.
1913
+ * Regex: `[0]|([1-9][0-9]*)`
1914
+ * @see https://hl7.org/fhir/R4/datatypes.html#unsignedInt
1915
+ */
1916
+ export declare type FhirUnsignedInt = Branded<number, 'FhirUnsignedInt'>;
1917
+
1918
+ /**
1919
+ * FHIR uri: a Uniform Resource Identifier.
1920
+ * Regex: `\S*`
1921
+ * @see https://hl7.org/fhir/R4/datatypes.html#uri
1922
+ */
1923
+ export declare type FhirUri = Branded<string, 'FhirUri'>;
1924
+
1925
+ /**
1926
+ * FHIR url: a Uniform Resource Locator (a subset of uri).
1927
+ * Must start with http:, https:, ftp:, mailto:, or mllp:.
1928
+ * @see https://hl7.org/fhir/R4/datatypes.html#url
1929
+ */
1930
+ export declare type FhirUrl = Branded<string, 'FhirUrl'>;
1931
+
1932
+ /**
1933
+ * FHIR uuid: a UUID expressed as a URI (RFC 4122).
1934
+ * Format: `urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`
1935
+ * @see https://hl7.org/fhir/R4/datatypes.html#uuid
1936
+ */
1937
+ export declare type FhirUuid = Branded<string, 'FhirUuid'>;
1938
+
1939
+ /**
1940
+ * FHIR version identifier.
1941
+ * @see https://hl7.org/fhir/R4/valueset-FHIR-version.html
1942
+ */
1943
+ export declare type FhirVersionCode = '0.01' | '0.05' | '0.06' | '0.11' | '0.0.80' | '0.0.81' | '0.0.82' | '0.4.0' | '0.5.0' | '1.0.0' | '1.0.1' | '1.0.2' | '1.1.0' | '1.4.0' | '1.6.0' | '1.8.0' | '3.0.0' | '3.0.1' | '3.0.2' | '3.3.0' | '3.5.0' | '4.0.0' | '4.0.1';
1944
+
1945
+ /**
1946
+ * FHIR xhtml: limited XHTML content as defined in the Narrative datatype.
1947
+ * @see https://hl7.org/fhir/R4/datatypes.html#xhtml
1948
+ * @see https://hl7.org/fhir/R4/narrative.html
1949
+ */
1950
+ export declare type FhirXhtml = Branded<string, 'FhirXhtml'>;
1951
+
1952
+ /**
1953
+ * A loader that resolves StructureDefinitions from local JSON files.
1954
+ *
1955
+ * @example
1956
+ * ```typescript
1957
+ * const loader = new FileSystemLoader('/path/to/definitions');
1958
+ * const sd = await loader.load('http://hl7.org/fhir/StructureDefinition/Patient');
1959
+ * // Reads /path/to/definitions/Patient.json
1960
+ * ```
1961
+ */
1962
+ export declare class FileSystemLoader implements StructureDefinitionLoader {
1963
+ private readonly _basePath;
1964
+ /**
1965
+ * @param basePath - Directory containing `{ResourceName}.json` files
1966
+ */
1967
+ constructor(basePath: string);
1968
+ load(url: string): Promise<StructureDefinition | null>;
1969
+ canLoad(url: string): boolean;
1970
+ getSourceType(): string;
1971
+ /**
1972
+ * The base directory this loader reads from.
1973
+ */
1974
+ get basePath(): string;
1975
+ }
1976
+
1977
+ /**
1978
+ * Find the index of a path in the base snapshot.
1979
+ *
1980
+ * Handles:
1981
+ * - Exact path match
1982
+ * - Choice type match (e.g., `valueString` matches `value[x]`)
1983
+ * - Slice paths (strips `:sliceName` from id to match by path)
1984
+ *
1985
+ * @param baseSnapshot - The base snapshot element list.
1986
+ * @param path - The path to find.
1987
+ * @param sliceName - Optional slice name for disambiguation.
1988
+ * @returns The index in baseSnapshot, or -1 if not found.
1989
+ */
1990
+ export declare function findBaseIndex(baseSnapshot: readonly ElementDefinition[], path: string, sliceName?: string): number;
1991
+
1992
+ /**
1993
+ * Resolve the absolute path to the `core-definitions/` directory.
1994
+ *
1995
+ * Works both in ESM (via `import.meta.url`) and when a custom
1996
+ * `specDirectory` is provided.
1997
+ *
1998
+ * @param specDirectory - Optional override directory path
1999
+ * @returns Absolute path to the core definitions directory
2000
+ */
2001
+ export declare function getCoreDefinitionsDir(specDirectory?: string): string;
2002
+
2003
+ /**
2004
+ * Get all sibling slices from a base snapshot starting after the slicing root.
2005
+ *
2006
+ * Corresponds to HAPI's `getSiblings()`. Collects all elements with the
2007
+ * same path as the slicing root that have a `sliceName`, plus their children.
2008
+ *
2009
+ * @param elements - The base snapshot element list.
2010
+ * @param slicingRootIndex - Index of the slicing root element.
2011
+ * @returns Array of slice elements (each with sliceName) and their children.
2012
+ */
2013
+ export declare function getSliceSiblings(elements: readonly ElementDefinition[], slicingRootIndex: number): ElementDefinition[];
2014
+
2015
+ /**
2016
+ * Handle Case B: Base is already sliced, differential modifies/extends slices.
2017
+ *
2018
+ * Steps:
2019
+ * 1. Copy base slicing root (merge diff slicing definition if present)
2020
+ * 2. Collect base slice siblings
2021
+ * 3. Align base slices with diff slices by sliceName
2022
+ * 4. Matched slices → merge constraints
2023
+ * 5. Unmatched base slices → copy as-is
2024
+ * 6. Remaining diff slices → append as new (only if open/openAtEnd)
2025
+ *
2026
+ * @param context - Shared merge state.
2027
+ * @param result - Mutable output array.
2028
+ * @param currentBase - The base slicing root element.
2029
+ * @param baseScope - Scope of the base element and its children.
2030
+ * @param diffMatches - Diff trackers that matched this base path.
2031
+ * @param diffTrackers - All diff trackers (for recursive calls).
2032
+ * @param diffStart - Start index in diffTrackers.
2033
+ * @param diffEnd - End index in diffTrackers.
2034
+ * @param contextPathSrc - Source path prefix for rewriting.
2035
+ * @param contextPathDst - Destination path prefix for rewriting.
2036
+ * @param cpath - The current (rewritten) path.
2037
+ */
2038
+ export declare function handleExistingSlicing(context: MergeContext, result: ElementDefinition[], currentBase: ElementDefinition, baseScope: TraversalScope, diffMatches: DiffElementTracker[], diffTrackers: readonly DiffElementTracker[], diffStart: number, diffEnd: number, contextPathSrc: string, contextPathDst: string, cpath: string): void;
2039
+
2040
+ /**
2041
+ * Handle Case A: Base is unsliced, differential introduces slicing.
2042
+ *
2043
+ * Steps:
2044
+ * 1. Create slicing root element (from diff slicing definition or synthesized extension slicing)
2045
+ * 2. Add slicing root to result
2046
+ * 3. For each diff slice, recursively process against the same base range
2047
+ *
2048
+ * @param context - Shared merge state.
2049
+ * @param result - Mutable output array.
2050
+ * @param currentBase - The base element being sliced.
2051
+ * @param baseScope - Scope of the base element and its children.
2052
+ * @param diffMatches - Diff trackers that matched this base path.
2053
+ * @param diffTrackers - All diff trackers (for recursive calls).
2054
+ * @param diffStart - Start index in diffTrackers.
2055
+ * @param diffEnd - End index in diffTrackers.
2056
+ * @param contextPathSrc - Source path prefix for rewriting.
2057
+ * @param contextPathDst - Destination path prefix for rewriting.
2058
+ * @param cpath - The current (rewritten) path.
2059
+ */
2060
+ export declare function handleNewSlicing(context: MergeContext, result: ElementDefinition[], currentBase: ElementDefinition, baseScope: TraversalScope, diffMatches: DiffElementTracker[], diffTrackers: readonly DiffElementTracker[], diffStart: number, diffEnd: number, contextPathSrc: string, contextPathDst: string, cpath: string): void;
2061
+
2062
+ /**
2063
+ * Check whether an issues array contains at least one error (not just warnings).
2064
+ *
2065
+ * Useful for determining whether to return success or failure after
2066
+ * collecting issues from sub-parsers.
2067
+ */
2068
+ export declare function hasErrors(issues: readonly ParseIssue[]): boolean;
2069
+
2070
+ /**
2071
+ * Check whether an element id contains a slice name (`:` separator).
2072
+ *
2073
+ * In FHIR, slice names appear in element ids, not in paths.
2074
+ * Format: `"ResourceType.path:sliceName"` or `"ResourceType.path:sliceName.child"`
2075
+ *
2076
+ * @example
2077
+ * hasSliceName('Patient.identifier:MRN') // true
2078
+ * hasSliceName('Patient.identifier:MRN.system') // true
2079
+ * hasSliceName('Patient.identifier') // false
2080
+ */
2081
+ export declare function hasSliceName(elementId: string): boolean;
2082
+
2083
+ /**
2084
+ * Check whether a validation result has any error-severity issues.
2085
+ *
2086
+ * @param issues - The issues to check.
2087
+ * @returns `true` if any issue has severity `'error'`.
2088
+ */
2089
+ export declare function hasValidationErrors(issues: readonly ValidationIssue[]): boolean;
2090
+
2091
+ /**
2092
+ * An identifier intended for computation (e.g., MRN, NPI).
2093
+ * @see https://hl7.org/fhir/R4/datatypes.html#Identifier
2094
+ */
2095
+ export declare interface Identifier extends Element {
2096
+ /** usual | official | temp | secondary | old (0..1) */
2097
+ use?: FhirCode;
2098
+ /** Description of identifier (0..1) */
2099
+ type?: CodeableConcept;
2100
+ /** The namespace for the identifier value (0..1) */
2101
+ system?: FhirUri;
2102
+ /** The value that is unique (0..1) */
2103
+ value?: FhirString;
2104
+ /** Time period when id is/was valid for use (0..1) */
2105
+ period?: Period;
2106
+ /** Organization that issued id (0..1) */
2107
+ assigner?: Reference;
2108
+ }
2109
+
2110
+ /**
2111
+ * Resolves profile inheritance chains by walking `baseDefinition` links.
2112
+ *
2113
+ * The resolver loads each StructureDefinition on demand via the provided
2114
+ * {@link DefinitionProvider}, detects circular dependencies, and caches
2115
+ * resolved chains for repeated lookups.
2116
+ *
2117
+ * @example
2118
+ * ```typescript
2119
+ * const resolver = new InheritanceChainResolver(provider);
2120
+ * const chain = await resolver.resolve(
2121
+ * 'http://hl7.org/fhir/StructureDefinition/Patient'
2122
+ * );
2123
+ * // → ['http://hl7.org/fhir/StructureDefinition/Patient',
2124
+ * // 'http://hl7.org/fhir/StructureDefinition/DomainResource',
2125
+ * // 'http://hl7.org/fhir/StructureDefinition/Resource']
2126
+ * ```
2127
+ */
2128
+ declare class InheritanceChainResolver {
2129
+ private readonly _provider;
2130
+ /** Cache of resolved chains: canonical URL → chain array */
2131
+ private readonly _cache;
2132
+ /** Statistics counter */
2133
+ private _resolutionCount;
2134
+ constructor(provider: DefinitionProvider);
2135
+ /**
2136
+ * Resolve the full inheritance chain for a profile.
2137
+ *
2138
+ * Returns an array of canonical URLs ordered from child to root:
2139
+ * `[startUrl, ..., parentUrl, rootUrl]`
2140
+ *
2141
+ * @param url - Canonical URL of the starting StructureDefinition
2142
+ * @returns Inheritance chain from child to root
2143
+ * @throws {@link CircularDependencyError} if a cycle is detected
2144
+ * @throws {@link ResourceNotFoundError} if a definition cannot be loaded
2145
+ */
2146
+ resolve(url: string): Promise<string[]>;
2147
+ /**
2148
+ * Invalidate the cached chain for a specific URL.
2149
+ *
2150
+ * Should be called when a StructureDefinition is re-registered,
2151
+ * as its `baseDefinition` may have changed.
2152
+ *
2153
+ * @param url - Canonical URL to invalidate
2154
+ */
2155
+ invalidate(url: string): void;
2156
+ /**
2157
+ * Clear all cached chains.
2158
+ */
2159
+ clearCache(): void;
2160
+ /**
2161
+ * Number of chains that have been resolved (not from cache).
2162
+ */
2163
+ get resolutionCount(): number;
2164
+ /**
2165
+ * Number of chains currently in the cache.
2166
+ */
2167
+ get cacheSize(): number;
2168
+ /**
2169
+ * Recursive resolution with circular dependency detection.
2170
+ *
2171
+ * @param url - Current URL to resolve
2172
+ * @param inFlight - Set of URLs currently being resolved (cycle detection)
2173
+ * @returns Chain from current URL to root
2174
+ */
2175
+ private _resolveRecursive;
2176
+ }
2177
+
2178
+ /**
2179
+ * Thrown when a loaded or registered StructureDefinition is missing
2180
+ * required fields or has invalid structure.
2181
+ *
2182
+ * Required fields for a valid StructureDefinition:
2183
+ * - `url` — canonical URL
2184
+ * - `name` — computer-friendly name
2185
+ * - `status` — publication status
2186
+ * - `kind` — resource | complex-type | primitive-type | logical
2187
+ *
2188
+ * @example
2189
+ * ```typescript
2190
+ * throw new InvalidStructureDefinitionError(
2191
+ * 'Missing required field: url',
2192
+ * 'http://example.org/MyProfile'
2193
+ * );
2194
+ * ```
2195
+ */
2196
+ export declare class InvalidStructureDefinitionError extends ContextError {
2197
+ readonly name = "InvalidStructureDefinitionError";
2198
+ /** The URL of the invalid definition (if available) */
2199
+ readonly url: string | undefined;
2200
+ constructor(reason: string, url?: string);
2201
+ }
2202
+
2203
+ /**
2204
+ * A resolved constraint (invariant) on a canonical element.
2205
+ *
2206
+ * Corresponds to a simplified version of `ElementDefinition.constraint`.
2207
+ */
2208
+ export declare interface Invariant {
2209
+ /** Unique key identifying this constraint. */
2210
+ key: string;
2211
+ /**
2212
+ * error | warning
2213
+ * @see https://hl7.org/fhir/R4/valueset-constraint-severity.html
2214
+ */
2215
+ severity: ConstraintSeverity;
2216
+ /** Human-readable description of the constraint. */
2217
+ human: string;
2218
+ /** FHIRPath expression that must evaluate to `true`. */
2219
+ expression?: string;
2220
+ /**
2221
+ * Canonical URL of the StructureDefinition where this constraint
2222
+ * was originally defined.
2223
+ */
2224
+ source?: string;
2225
+ }
2226
+
2227
+ /**
2228
+ * Check if an element defines a BackboneElement or Element inner type.
2229
+ *
2230
+ * An element is an inner type root if:
2231
+ * - Its `types` array contains a type with `code === 'BackboneElement'` or `code === 'Element'`
2232
+ * - It is not the root element of the profile (path has at least one dot)
2233
+ *
2234
+ * @param element - The canonical element to check
2235
+ * @returns `true` if this element defines an inner type
2236
+ */
2237
+ export declare function isBackboneElementType(element: CanonicalElement): boolean;
2238
+
2239
+ /**
2240
+ * Check whether a path ends with `[x]` (choice type wildcard).
2241
+ *
2242
+ * @example
2243
+ * isChoiceTypePath('Observation.value[x]') // true
2244
+ * isChoiceTypePath('Observation.valueString') // false
2245
+ * isChoiceTypePath('Observation.value') // false
2246
+ */
2247
+ export declare function isChoiceTypePath(path: string): boolean;
2248
+
2249
+ /**
2250
+ * Check whether `descendantPath` is a descendant of `ancestorPath`
2251
+ * (at any depth).
2252
+ *
2253
+ * @example
2254
+ * isDescendant('Patient.name', 'Patient.name.given') // true
2255
+ * isDescendant('Patient.name', 'Patient.name.given.value') // true
2256
+ * isDescendant('Patient.name', 'Patient.name') // false
2257
+ * isDescendant('Patient.name', 'Patient.identifier') // false
2258
+ */
2259
+ export declare function isDescendant(ancestorPath: string, descendantPath: string): boolean;
2260
+
2261
+ /**
2262
+ * Check whether `childPath` is a direct child of `parentPath`.
2263
+ *
2264
+ * A direct child has exactly one more segment than the parent.
2265
+ *
2266
+ * @example
2267
+ * isDirectChild('Patient.name', 'Patient.name.given') // true
2268
+ * isDirectChild('Patient.name', 'Patient.name.given.value') // false
2269
+ * isDirectChild('Patient.name', 'Patient.identifier') // false
2270
+ */
2271
+ export declare function isDirectChild(parentPath: string, childPath: string): boolean;
2272
+
2273
+ /**
2274
+ * Determine whether max value `a` is larger than max value `b`.
2275
+ *
2276
+ * FHIR max is either a non-negative integer string or `"*"` (unbounded).
2277
+ * `"*"` is treated as infinity.
2278
+ *
2279
+ * @example
2280
+ * isLargerMax('5', '3') // true
2281
+ * isLargerMax('*', '3') // true
2282
+ * isLargerMax('3', '*') // false
2283
+ * isLargerMax('3', '3') // false
2284
+ * isLargerMax('*', '*') // false
2285
+ */
2286
+ export declare function isLargerMax(a: string, b: string): boolean;
2287
+
2288
+ /**
2289
+ * Load all core definitions and return them as a Map.
2290
+ *
2291
+ * Loads in dependency order (base → primitives → complex → resources).
2292
+ *
2293
+ * @param specDirectory - Optional override directory path
2294
+ * @returns Map of canonical URL → StructureDefinition
2295
+ */
2296
+ export declare function loadAllCoreDefinitions(specDirectory?: string): Promise<Map<string, StructureDefinition>>;
2297
+
2298
+ /**
2299
+ * Load CanonicalProfiles from a FHIR Bundle JSON file.
2300
+ *
2301
+ * Reads the file synchronously (spec files are loaded once at startup),
2302
+ * parses the JSON, and delegates to `loadBundleFromObject`.
2303
+ *
2304
+ * @param filePath - Absolute path to a FHIR Bundle JSON file.
2305
+ * @param options - Optional filters to control which entries are loaded.
2306
+ * @returns BundleLoadResult with profiles, errors, and statistics.
2307
+ * @throws Error if the file cannot be read or is not valid JSON.
2308
+ */
2309
+ export declare function loadBundleFromFile(filePath: string, options?: BundleLoadOptions): BundleLoadResult;
2310
+
2311
+ /**
2312
+ * Load CanonicalProfiles from an already-parsed Bundle object.
2313
+ *
2314
+ * This is the core loading function. It:
2315
+ * 1. Extracts all StructureDefinition entries from the bundle
2316
+ * 2. Applies filter options (kind, abstract, type)
2317
+ * 3. Parses each SD through `parseStructureDefinition`
2318
+ * 4. Converts each parsed SD to `CanonicalProfile` via `buildCanonicalProfile`
2319
+ * 5. Collects errors without aborting (partial failure tolerance)
2320
+ *
2321
+ * @param bundle - A parsed FHIR Bundle object containing StructureDefinition entries.
2322
+ * @param options - Optional filters to control which entries are loaded.
2323
+ * @returns BundleLoadResult with profiles, errors, and statistics.
2324
+ */
2325
+ export declare function loadBundleFromObject(bundle: BundleShape, options?: BundleLoadOptions): BundleLoadResult;
2326
+
2327
+ /**
2328
+ * Load and merge multiple bundle files in order.
2329
+ *
2330
+ * Later bundles override earlier ones for the same canonical URL.
2331
+ * This supports the standard loading order:
2332
+ * 1. profiles-types.json — type system (no tables)
2333
+ * 2. profiles-resources.json — clinical resources
2334
+ * 3. profiles-others.json — conformance resources
2335
+ * 4. profiles-platform.json — platform resources (Phase 9)
2336
+ *
2337
+ * @param filePaths - Array of absolute paths to FHIR Bundle JSON files.
2338
+ * @param options - Optional filters applied to each bundle.
2339
+ * @returns Merged BundleLoadResult with deduplicated profiles.
2340
+ */
2341
+ export declare function loadBundlesFromFiles(filePaths: string[], options?: BundleLoadOptions): BundleLoadResult;
2342
+
2343
+ /**
2344
+ * Load a single core StructureDefinition by name (async).
2345
+ *
2346
+ * @param name - Definition name (e.g., `"Patient"`, `"string"`)
2347
+ * @param baseDir - Directory containing the JSON files
2348
+ * @returns Parsed StructureDefinition
2349
+ * @throws {@link LoaderError} if the file cannot be read or parsed
2350
+ */
2351
+ export declare function loadCoreDefinition(name: string, baseDir: string): Promise<StructureDefinition>;
2352
+
2353
+ /**
2354
+ * Load a single core StructureDefinition by name (synchronous).
2355
+ *
2356
+ * @param name - Definition name (e.g., `"Patient"`, `"string"`)
2357
+ * @param baseDir - Directory containing the JSON files
2358
+ * @returns Parsed StructureDefinition
2359
+ * @throws {@link LoaderError} if the file cannot be read or parsed
2360
+ */
2361
+ export declare function loadCoreDefinitionSync(name: string, baseDir: string): StructureDefinition;
2362
+
2363
+ /**
2364
+ * Thrown when a {@link StructureDefinitionLoader} encounters an I/O
2365
+ * or parse failure while loading a definition.
2366
+ *
2367
+ * The original error is preserved as `cause` for debugging.
2368
+ *
2369
+ * @example
2370
+ * ```typescript
2371
+ * throw new LoaderError(
2372
+ * 'http://hl7.org/fhir/StructureDefinition/Patient',
2373
+ * 'filesystem',
2374
+ * originalError
2375
+ * );
2376
+ * ```
2377
+ */
2378
+ export declare class LoaderError extends ContextError {
2379
+ readonly name = "LoaderError";
2380
+ /** The canonical URL being loaded when the error occurred */
2381
+ readonly url: string;
2382
+ /** The loader source type that failed */
2383
+ readonly sourceType: string;
2384
+ constructor(url: string, sourceType: string, cause?: Error);
2385
+ }
2386
+
2387
+ /**
2388
+ * Options for individual loader instances.
2389
+ */
2390
+ export declare interface LoaderOptions {
2391
+ /**
2392
+ * Base directory or URL prefix for resolving relative paths.
2393
+ */
2394
+ basePath?: string;
2395
+ /**
2396
+ * Request timeout in milliseconds (for future HTTP loaders).
2397
+ *
2398
+ * @defaultValue `30000`
2399
+ */
2400
+ timeout?: number;
2401
+ /**
2402
+ * Number of retry attempts on transient failures.
2403
+ *
2404
+ * @defaultValue `0`
2405
+ */
2406
+ retryCount?: number;
2407
+ }
2408
+
2409
+ /**
2410
+ * Generate the default slicing definition for extension elements.
2411
+ *
2412
+ * Corresponds to HAPI's `makeExtensionSlicing()`. Extension elements
2413
+ * are always sliced by `url` using the `value` discriminator type.
2414
+ *
2415
+ * @returns A new {@link ElementDefinitionSlicing} for extensions.
2416
+ */
2417
+ export declare function makeExtensionSlicing(): ElementDefinitionSlicing;
2418
+
2419
+ /**
2420
+ * Check whether `concretePath` matches a choice type `choicePath`.
2421
+ *
2422
+ * The concrete path must share the same prefix (minus `[x]`) and the
2423
+ * remaining suffix must start with an uppercase letter (the type name).
2424
+ *
2425
+ * @example
2426
+ * matchesChoiceType('Observation.value[x]', 'Observation.valueString') // true
2427
+ * matchesChoiceType('Observation.value[x]', 'Observation.valueQuantity') // true
2428
+ * matchesChoiceType('Observation.value[x]', 'Observation.code') // false
2429
+ * matchesChoiceType('Observation.value[x]', 'Observation.value') // false
2430
+ */
2431
+ export declare function matchesChoiceType(choicePath: string, concretePath: string): boolean;
2432
+
2433
+ /**
2434
+ * A loader that resolves StructureDefinitions from an in-memory Map.
2435
+ *
2436
+ * The map is keyed by canonical URL. Lookups are synchronous but the
2437
+ * interface returns a Promise for consistency with other loaders.
2438
+ *
2439
+ * @example
2440
+ * ```typescript
2441
+ * const definitions = new Map<string, StructureDefinition>();
2442
+ * definitions.set('http://hl7.org/fhir/StructureDefinition/Patient', patientSD);
2443
+ * const loader = new MemoryLoader(definitions);
2444
+ * ```
2445
+ */
2446
+ export declare class MemoryLoader implements StructureDefinitionLoader {
2447
+ private readonly _definitions;
2448
+ /**
2449
+ * @param definitions - Map of canonical URL → StructureDefinition.
2450
+ * The map is **not** copied; mutations to the
2451
+ * original map are visible to the loader.
2452
+ */
2453
+ constructor(definitions: Map<string, StructureDefinition>);
2454
+ load(url: string): Promise<StructureDefinition | null>;
2455
+ canLoad(url: string): boolean;
2456
+ getSourceType(): string;
2457
+ /**
2458
+ * Number of definitions currently held in the map.
2459
+ */
2460
+ get size(): number;
2461
+ }
2462
+
2463
+ /**
2464
+ * Merge binding constraints with strength validation.
2465
+ *
2466
+ * Rules:
2467
+ * - Cannot relax a REQUIRED binding (REQUIRED → anything else = error)
2468
+ * - Derived binding replaces base binding
2469
+ *
2470
+ * @returns The merged binding.
2471
+ */
2472
+ export declare function mergeBinding(baseBinding: ElementDefinitionBinding | undefined, diffBinding: ElementDefinitionBinding | undefined, issues: SnapshotIssue[], path: string): ElementDefinitionBinding | undefined;
2473
+
2474
+ /**
2475
+ * Merge cardinality constraints (min/max) with validation.
2476
+ *
2477
+ * Rules:
2478
+ * - `derived.min` must be >= `base.min` (except for slices)
2479
+ * - `derived.max` must be <= `base.max`
2480
+ *
2481
+ * @internal Exported for direct testing.
2482
+ */
2483
+ export declare function mergeCardinality(dest: ElementDefinition, source: ElementDefinition, issues: SnapshotIssue[], path?: string): void;
2484
+
2485
+ /**
2486
+ * Merge constraint (invariant) lists by appending derived constraints,
2487
+ * de-duplicating by `key`.
2488
+ *
2489
+ * Base constraints are kept; derived constraints with the same key
2490
+ * replace the base version.
2491
+ *
2492
+ * @returns The merged constraint array.
2493
+ */
2494
+ export declare function mergeConstraintList(baseConstraints: readonly ElementDefinitionConstraint[] | undefined, diffConstraints: readonly ElementDefinitionConstraint[] | undefined): ElementDefinitionConstraint[] | undefined;
2495
+
2496
+ /**
2497
+ * Apply differential constraints onto a snapshot element.
2498
+ *
2499
+ * Corresponds to HAPI `updateFromDefinition(dest, source, ...)`.
2500
+ * The `dest` element is mutated in place and also returned.
2501
+ *
2502
+ * @param dest - The working snapshot element (initially cloned from base).
2503
+ * @param source - The differential element to apply.
2504
+ * @param issues - Mutable array to collect issues.
2505
+ * @returns The mutated `dest` element.
2506
+ */
2507
+ export declare function mergeConstraints(dest: ElementDefinition, source: ElementDefinition, issues: SnapshotIssue[]): ElementDefinition;
2508
+
2509
+ /**
2510
+ * Shared state passed through all recursive `processPaths` calls.
2511
+ */
2512
+ export declare interface MergeContext {
2513
+ /** FhirContext for loading datatype definitions (async). `undefined` for sync-only tests. */
2514
+ readonly fhirContext?: FhirContext;
2515
+ /** Preloaded datatype snapshots cache (url → snapshot elements). */
2516
+ readonly datatypeCache: Map<string, readonly ElementDefinition[]>;
2517
+ /** Issue collector. */
2518
+ readonly issues: SnapshotIssue[];
2519
+ /** URL of the profile being generated. */
2520
+ readonly profileUrl: string;
2521
+ /** Current recursion depth. */
2522
+ depth: number;
2523
+ /** Maximum allowed recursion depth. */
2524
+ readonly maxDepth: number;
2525
+ }
2526
+
2527
+ /**
2528
+ * High-level convenience function: merge a base snapshot with a differential
2529
+ * to produce a new snapshot element list.
2530
+ *
2531
+ * This is the primary entry point for testing and for the SnapshotGenerator
2532
+ * orchestrator (Task 4.5).
2533
+ *
2534
+ * @param baseElements - The base profile's snapshot elements.
2535
+ * @param diffElements - The differential elements to apply.
2536
+ * @param context - Merge context (or auto-created if not provided).
2537
+ * @returns The merged snapshot element list.
2538
+ */
2539
+ export declare function mergeSnapshot(baseElements: readonly ElementDefinition[], diffElements: readonly ElementDefinition[], context?: MergeContext): {
2540
+ elements: ElementDefinition[];
2541
+ issues: SnapshotIssue[];
2542
+ };
2543
+
2544
+ /**
2545
+ * Merge type constraints with compatibility validation.
2546
+ *
2547
+ * Each derived type must be compatible with at least one base type.
2548
+ * Special allowances: Extension, Element, *, Resource/DomainResource.
2549
+ *
2550
+ * If valid, derived types replace base types entirely.
2551
+ *
2552
+ * @returns The merged type array (derived types if valid, base types if no diff).
2553
+ */
2554
+ export declare function mergeTypes(baseTypes: readonly ElementDefinitionType[] | undefined, diffTypes: readonly ElementDefinitionType[] | undefined, issues: SnapshotIssue[], path: string): ElementDefinitionType[] | undefined;
2555
+
2556
+ /**
2557
+ * The metadata about a resource. This is content in the resource that is
2558
+ * maintained by the infrastructure.
2559
+ * @see https://hl7.org/fhir/R4/resource.html#Meta
2560
+ */
2561
+ export declare interface Meta extends Element {
2562
+ /** Version specific identifier (0..1) */
2563
+ versionId?: FhirId;
2564
+ /** When the resource version last changed (0..1) */
2565
+ lastUpdated?: FhirInstant;
2566
+ /** Identifies where the resource comes from (0..1) */
2567
+ source?: FhirUri;
2568
+ /** Profiles this resource claims to conform to (0..*) */
2569
+ profile?: FhirCanonical[];
2570
+ /** Security Labels applied to this resource (0..*) */
2571
+ security?: Coding[];
2572
+ /** Tags applied to this resource (0..*) */
2573
+ tag?: Coding[];
2574
+ }
2575
+
2576
+ /**
2577
+ * A human-readable summary of the resource conveying the essential
2578
+ * clinical and business information.
2579
+ * @see https://hl7.org/fhir/R4/narrative.html#Narrative
2580
+ */
2581
+ export declare interface Narrative extends Element {
2582
+ /** generated | extensions | additional | empty (1..1) */
2583
+ status: NarrativeStatus;
2584
+ /** Limited xhtml content (1..1) */
2585
+ div: FhirXhtml;
2586
+ }
2587
+
2588
+ /**
2589
+ * The status of a narrative.
2590
+ * @see https://hl7.org/fhir/R4/valueset-narrative-status.html
2591
+ */
2592
+ export declare type NarrativeStatus = 'generated' | 'extensions' | 'additional' | 'empty';
2593
+
2594
+ /**
2595
+ * Get the parent path (everything before the last `.`).
2596
+ *
2597
+ * @example
2598
+ * parentPath('Patient.name.given') // 'Patient.name'
2599
+ * parentPath('Patient.name') // 'Patient'
2600
+ * parentPath('Patient') // undefined
2601
+ */
2602
+ export declare function parentPath(path: string): string | undefined;
2603
+
2604
+ /**
2605
+ * Parse an ElementDefinition JSON object.
2606
+ *
2607
+ * ElementDefinition is the most complex data type in FHIR,
2608
+ * with ~37 fields and 8 sub-types.
2609
+ */
2610
+ export declare function parseElementDefinition(obj: Record<string, unknown>, path: string): {
2611
+ result: ElementDefinition;
2612
+ issues: ParseIssue[];
2613
+ };
2614
+
2615
+ /**
2616
+ * Machine-readable error codes for parse issues.
2617
+ *
2618
+ * Each code corresponds to a specific category of parsing problem.
2619
+ * Consumers can switch on these codes for programmatic error handling.
2620
+ */
2621
+ export declare type ParseErrorCode =
2622
+ /** JSON syntax error (e.g., malformed JSON string) */
2623
+ 'INVALID_JSON'
2624
+ /** Missing required `resourceType` property */
2625
+ | 'MISSING_RESOURCE_TYPE'
2626
+ /** `resourceType` value is not a recognized FHIR resource type */
2627
+ | 'UNKNOWN_RESOURCE_TYPE'
2628
+ /** Primitive value has wrong JavaScript type (e.g., string where number expected) */
2629
+ | 'INVALID_PRIMITIVE'
2630
+ /** Object structure does not match expected shape (e.g., array where object expected) */
2631
+ | 'INVALID_STRUCTURE'
2632
+ /** Choice type `[x]` property name has an unrecognized type suffix */
2633
+ | 'INVALID_CHOICE_TYPE'
2634
+ /** Multiple variants of the same choice type field are present */
2635
+ | 'MULTIPLE_CHOICE_VALUES'
2636
+ /** `_element` array length does not match the corresponding value array */
2637
+ | 'ARRAY_MISMATCH'
2638
+ /** Unexpected `null` value in a non-nullable position */
2639
+ | 'UNEXPECTED_NULL'
2640
+ /** Property name not recognized for this type (severity: warning) */
2641
+ | 'UNEXPECTED_PROPERTY';
2642
+
2643
+ /**
2644
+ * Create a failed parse result.
2645
+ *
2646
+ * @param issues - The error(s) that caused the failure (must contain at least one error)
2647
+ */
2648
+ export declare function parseFailure<T>(issues: ParseIssue[]): ParseResult<T>;
2649
+
2650
+ /**
2651
+ * Parse a FHIR JSON string into a Resource object.
2652
+ *
2653
+ * This is the main entry point for the parser. It:
2654
+ * 1. Calls `JSON.parse()` with error capture
2655
+ * 2. Delegates to {@link parseFhirObject} for structural parsing
2656
+ *
2657
+ * Stage-1 supports dedicated parsing for `StructureDefinition` (Task 2.5).
2658
+ * All other resource types are parsed generically.
2659
+ *
2660
+ * @param json - A FHIR JSON string
2661
+ * @returns A `ParseResult` containing the parsed `Resource` or error details
2662
+ *
2663
+ * @example
2664
+ * ```typescript
2665
+ * const result = parseFhirJson('{"resourceType":"Patient","id":"123"}');
2666
+ * if (result.success) {
2667
+ * console.log(result.data.resourceType); // "Patient"
2668
+ * }
2669
+ * ```
2670
+ */
2671
+ export declare function parseFhirJson(json: string): ParseResult<Resource>;
2672
+
2673
+ /**
2674
+ * Parse an already-parsed JSON value into a Resource object.
2675
+ *
2676
+ * Use this when you already have a JavaScript object (e.g., from a database
2677
+ * or from `JSON.parse()` called externally).
2678
+ *
2679
+ * @param obj - An unknown value (expected to be a plain JSON object with `resourceType`)
2680
+ * @returns A `ParseResult` containing the parsed `Resource` or error details
2681
+ */
2682
+ export declare function parseFhirObject(obj: unknown): ParseResult<Resource>;
2683
+
2684
+ /**
2685
+ * A single issue encountered during parsing.
2686
+ *
2687
+ * Issues are collected throughout the parse process and returned in the
2688
+ * {@link ParseResult}. Both errors and warnings use this same structure.
2689
+ *
2690
+ * @example
2691
+ * ```typescript
2692
+ * const issue: ParseIssue = {
2693
+ * severity: 'error',
2694
+ * code: 'MISSING_RESOURCE_TYPE',
2695
+ * message: 'Object is missing the required "resourceType" property',
2696
+ * path: '$',
2697
+ * };
2698
+ * ```
2699
+ */
2700
+ export declare interface ParseIssue {
2701
+ /** Severity level — `error` blocks successful parsing, `warning` does not */
2702
+ readonly severity: ParseSeverity;
2703
+ /** Machine-readable error code for programmatic handling */
2704
+ readonly code: ParseErrorCode;
2705
+ /** Human-readable description of the issue */
2706
+ readonly message: string;
2707
+ /**
2708
+ * JSON path where the issue was detected.
2709
+ *
2710
+ * Uses dot notation with array indices:
2711
+ * - `"StructureDefinition"` — root level
2712
+ * - `"StructureDefinition.snapshot.element[0].type[1].code"` — nested
2713
+ * - `"$"` — before resourceType is known
2714
+ */
2715
+ readonly path: string;
2716
+ }
2717
+
2718
+ /**
2719
+ * Result of a parse operation.
2720
+ *
2721
+ * Uses a discriminated union on `success`:
2722
+ * - `success: true` — parsing succeeded; `data` contains the parsed value,
2723
+ * `issues` may contain warnings
2724
+ * - `success: false` — parsing failed; `data` is `undefined`,
2725
+ * `issues` contains at least one error
2726
+ *
2727
+ * @typeParam T - The expected output type (e.g., `StructureDefinition`)
2728
+ *
2729
+ * @example
2730
+ * ```typescript
2731
+ * const result = parseFhirJson(jsonString);
2732
+ * if (result.success) {
2733
+ * console.log(result.data.url); // T is available
2734
+ * } else {
2735
+ * for (const issue of result.issues) {
2736
+ * console.error(`[${issue.path}] ${issue.message}`);
2737
+ * }
2738
+ * }
2739
+ * ```
2740
+ */
2741
+ export declare type ParseResult<T> = {
2742
+ readonly success: true;
2743
+ readonly data: T;
2744
+ readonly issues: readonly ParseIssue[];
2745
+ } | {
2746
+ readonly success: false;
2747
+ readonly data: undefined;
2748
+ readonly issues: readonly ParseIssue[];
2749
+ };
2750
+
2751
+ /**
2752
+ * FHIR JSON Parse Error Types
2753
+ *
2754
+ * Structured error types for the fhir-parser module. Provides precise
2755
+ * error localization via JSON path tracking and supports collecting
2756
+ * multiple issues (errors + warnings) in a single parse pass.
2757
+ *
2758
+ * Design decisions:
2759
+ * - Result type over exceptions: allows multi-error collection
2760
+ * - Path tracking: every issue carries the JSON path for precise localization
2761
+ * - Warning support: non-fatal issues (e.g., unknown properties) reported
2762
+ * as warnings without blocking the parse
2763
+ *
2764
+ * @module fhir-parser
2765
+ */
2766
+ /**
2767
+ * Severity level of a parse issue.
2768
+ *
2769
+ * - `error` — the issue prevents correct interpretation of the data
2770
+ * - `warning` — the data can still be used, but something unexpected was found
2771
+ */
2772
+ export declare type ParseSeverity = 'error' | 'warning';
2773
+
2774
+ /**
2775
+ * Parse a StructureDefinition JSON object.
2776
+ *
2777
+ * This is the most important parse function in Stage-1. All downstream
2778
+ * modules (fhir-context, fhir-profile, fhir-validator) depend on
2779
+ * correctly parsed StructureDefinitions.
2780
+ *
2781
+ * @param obj - A parsed JSON object (already validated as having resourceType = "StructureDefinition")
2782
+ * @param path - Current JSON path (for error reporting)
2783
+ */
2784
+ export declare function parseStructureDefinition(obj: Record<string, unknown>, path: string): ParseResult<StructureDefinition>;
2785
+
2786
+ /**
2787
+ * Create a successful parse result.
2788
+ *
2789
+ * @param data - The parsed value
2790
+ * @param issues - Any warnings collected during parsing (default: none)
2791
+ */
2792
+ export declare function parseSuccess<T>(data: T, issues?: ParseIssue[]): ParseResult<T>;
2793
+
2794
+ /**
2795
+ * Get the depth (number of segments) of a path.
2796
+ *
2797
+ * @example
2798
+ * pathDepth('Patient') // 1
2799
+ * pathDepth('Patient.name') // 2
2800
+ * pathDepth('Patient.name.given') // 3
2801
+ */
2802
+ export declare function pathDepth(path: string): number;
2803
+
2804
+ /**
2805
+ * Check whether two paths match exactly.
2806
+ *
2807
+ * @example
2808
+ * pathMatches('Patient.name', 'Patient.name') // true
2809
+ * pathMatches('Patient.name', 'Patient.identifier') // false
2810
+ */
2811
+ export declare function pathMatches(basePath: string, diffPath: string): boolean;
2812
+
2813
+ /**
2814
+ * A time period defined by a start and end date/time.
2815
+ * @see https://hl7.org/fhir/R4/datatypes.html#Period
2816
+ */
2817
+ export declare interface Period extends Element {
2818
+ /** Starting time with inclusive boundary (0..1) */
2819
+ start?: FhirDateTime;
2820
+ /** End time with inclusive boundary, if not ongoing (0..1) */
2821
+ end?: FhirDateTime;
2822
+ }
2823
+
2824
+ /**
2825
+ * Primitive types — FHIR primitive data types.
2826
+ */
2827
+ export declare const PRIMITIVE_TYPES: readonly ["base64Binary", "boolean", "canonical", "code", "date", "dateTime", "decimal", "id", "instant", "integer", "markdown", "oid", "positiveInt", "string", "time", "unsignedInt", "uri", "url", "uuid", "xhtml"];
2828
+
2829
+ /**
2830
+ * Base-driven merge loop (corresponds to HAPI `processPaths`).
2831
+ *
2832
+ * Walks the base snapshot within `baseScope`, finds matching differential
2833
+ * entries within `[diffStart, diffEnd]`, and appends merged elements to `result`.
2834
+ *
2835
+ * @param context - Shared merge state.
2836
+ * @param result - Mutable output array to append merged elements to.
2837
+ * @param baseElements - The base snapshot element list.
2838
+ * @param baseCursor - Start index in baseElements (inclusive).
2839
+ * @param baseLimit - End index in baseElements (inclusive).
2840
+ * @param diffTrackers - The differential element trackers.
2841
+ * @param diffStart - Start index in diffTrackers (inclusive).
2842
+ * @param diffEnd - End index in diffTrackers (inclusive).
2843
+ * @param contextPathSrc - Source path prefix for rewriting (e.g., datatype name).
2844
+ * @param contextPathDst - Destination path prefix for rewriting.
2845
+ */
2846
+ export declare function processPaths(context: MergeContext, result: ElementDefinition[], baseElements: readonly ElementDefinition[], baseCursor: number, baseLimit: number, diffTrackers: readonly DiffElementTracker[], diffStart: number, diffEnd: number, contextPathSrc: string, contextPathDst: string): void;
2847
+
2848
+ /**
2849
+ * fhir-profile — Error Types
2850
+ *
2851
+ * Structured error hierarchy for the FHIR profile module.
2852
+ * All errors extend {@link ProfileError} so consumers can catch
2853
+ * profile-related failures with a single `catch` clause.
2854
+ *
2855
+ * Error hierarchy:
2856
+ * ```
2857
+ * ProfileError (base)
2858
+ * ├── SnapshotCircularDependencyError
2859
+ * ├── BaseNotFoundError
2860
+ * ├── ConstraintViolationError
2861
+ * └── UnconsumedDifferentialError
2862
+ * ```
2863
+ *
2864
+ * @module fhir-profile
2865
+ */
2866
+ /**
2867
+ * Base error class for all fhir-profile failures.
2868
+ *
2869
+ * Provides a stable `name` property and preserves the original `cause`
2870
+ * when wrapping lower-level errors.
2871
+ *
2872
+ * @example
2873
+ * ```typescript
2874
+ * try {
2875
+ * await generator.generate(sd);
2876
+ * } catch (err) {
2877
+ * if (err instanceof ProfileError) {
2878
+ * // Handle any profile-related error
2879
+ * }
2880
+ * }
2881
+ * ```
2882
+ */
2883
+ export declare class ProfileError extends Error {
2884
+ readonly name: string;
2885
+ constructor(message: string, options?: ErrorOptions);
2886
+ }
2887
+
2888
+ /**
2889
+ * Thrown when the profile required for validation cannot be found or loaded.
2890
+ *
2891
+ * This occurs when:
2892
+ * - The specified `profileUrl` does not exist in the FhirContext
2893
+ * - The profile exists but has no snapshot
2894
+ * - No profile URL is specified and none can be inferred from the resource
2895
+ *
2896
+ * @example
2897
+ * ```typescript
2898
+ * throw new ProfileNotFoundError(
2899
+ * 'http://example.org/StructureDefinition/UnknownProfile',
2900
+ * );
2901
+ * ```
2902
+ */
2903
+ export declare class ProfileNotFoundError extends ValidatorError {
2904
+ readonly name = "ProfileNotFoundError";
2905
+ /** The canonical URL of the profile that could not be found. */
2906
+ readonly profileUrl: string;
2907
+ constructor(profileUrl: string, cause?: Error);
2908
+ }
2909
+
2910
+ /**
2911
+ * How a property is represented when serialized.
2912
+ * @see https://hl7.org/fhir/R4/valueset-property-representation.html
2913
+ */
2914
+ export declare type PropertyRepresentation = 'xmlAttr' | 'xmlText' | 'typeAttr' | 'cdaText' | 'xhtml';
2915
+
2916
+ /**
2917
+ * Publication status of a FHIR conformance resource.
2918
+ * @see https://hl7.org/fhir/R4/valueset-publication-status.html
2919
+ */
2920
+ export declare type PublicationStatus = 'draft' | 'active' | 'retired' | 'unknown';
2921
+
2922
+ /**
2923
+ * A measured amount (or an amount that can potentially be measured).
2924
+ * @see https://hl7.org/fhir/R4/datatypes.html#Quantity
2925
+ */
2926
+ export declare interface Quantity extends Element {
2927
+ /** Numerical value (with implicit precision) (0..1) */
2928
+ value?: FhirDecimal;
2929
+ /** `<` | `<=` | `>=` | `>` — how to understand the value (0..1) */
2930
+ comparator?: FhirCode;
2931
+ /** Unit representation (0..1) */
2932
+ unit?: FhirString;
2933
+ /** System that defines coded unit form (0..1) */
2934
+ system?: FhirUri;
2935
+ /** Coded form of the unit (0..1) */
2936
+ code?: FhirCode;
2937
+ }
2938
+
2939
+ /**
2940
+ * A reference from one resource to another.
2941
+ * @see https://hl7.org/fhir/R4/references.html#Reference
2942
+ */
2943
+ export declare interface Reference extends Element {
2944
+ /** Literal reference, Relative, internal or absolute URL (0..1) */
2945
+ reference?: FhirString;
2946
+ /** Type the reference refers to (e.g., "Patient") (0..1) */
2947
+ type?: FhirUri;
2948
+ /** Logical reference, when literal reference is not known (0..1) */
2949
+ identifier?: Identifier;
2950
+ /** Text alternative for the resource (0..1) */
2951
+ display?: FhirString;
2952
+ }
2953
+
2954
+ /**
2955
+ * Whether all resource references need to be version-specific.
2956
+ * @see https://hl7.org/fhir/R4/valueset-reference-version-rules.html
2957
+ */
2958
+ export declare type ReferenceVersionRules = 'either' | 'independent' | 'specific';
2959
+
2960
+ /**
2961
+ * Resolve default validation options.
2962
+ *
2963
+ * Fills in missing fields with sensible defaults.
2964
+ *
2965
+ * @param options - User-provided options (may be partial).
2966
+ * @returns Fully resolved options with all fields populated.
2967
+ */
2968
+ export declare function resolveValidationOptions(options?: ValidationOptions): Required<ValidationOptions>;
2969
+
2970
+ /**
2971
+ * Abstract base for all FHIR resources.
2972
+ * @see https://hl7.org/fhir/R4/resource.html
2973
+ */
2974
+ export declare interface Resource {
2975
+ /**
2976
+ * The type of the resource (1..1)
2977
+ *
2978
+ * This is typed as `string` rather than `FhirString` because it serves
2979
+ * as a discriminator field that concrete resource interfaces narrow to
2980
+ * a string literal (e.g., `'StructureDefinition'`, `'Patient'`).
2981
+ * Branded types would prevent this narrowing.
2982
+ */
2983
+ resourceType: string;
2984
+ /** Logical id of this artifact (0..1) */
2985
+ id?: FhirId;
2986
+ /** Metadata about the resource (0..1) */
2987
+ meta?: Meta;
2988
+ /** A set of rules under which this content was created (0..1) */
2989
+ implicitRules?: FhirUri;
2990
+ /** Language of the resource content (0..1) */
2991
+ language?: FhirCode;
2992
+ }
2993
+
2994
+ /**
2995
+ * Thrown when a StructureDefinition cannot be resolved by any loader.
2996
+ *
2997
+ * @example
2998
+ * ```typescript
2999
+ * throw new ResourceNotFoundError(
3000
+ * 'http://hl7.org/fhir/StructureDefinition/UnknownType',
3001
+ * ['memory', 'filesystem']
3002
+ * );
3003
+ * ```
3004
+ */
3005
+ export declare class ResourceNotFoundError extends ContextError {
3006
+ readonly name = "ResourceNotFoundError";
3007
+ /** The canonical URL that could not be resolved */
3008
+ readonly url: string;
3009
+ /** Loader source types that were tried */
3010
+ readonly triedSources: readonly string[];
3011
+ constructor(url: string, triedSources?: string[]);
3012
+ }
3013
+
3014
+ /**
3015
+ * Serialize a Resource object to a FHIR JSON string.
3016
+ *
3017
+ * Output conforms to FHIR R4 JSON conventions:
3018
+ * - `resourceType` is the first property
3019
+ * - Remaining properties are in alphabetical order
3020
+ * - Choice type fields use their original JSON property names
3021
+ * - Empty values (`undefined`, `[]`, `{}`) are omitted
3022
+ *
3023
+ * @param resource - The Resource to serialize
3024
+ * @returns A FHIR JSON string (pretty-printed with 2-space indent)
3025
+ *
3026
+ * @example
3027
+ * ```typescript
3028
+ * const sd: StructureDefinition = { resourceType: 'StructureDefinition', ... };
3029
+ * const json = serializeToFhirJson(sd);
3030
+ * // '{\n "resourceType": "StructureDefinition",\n ...\n}'
3031
+ * ```
3032
+ */
3033
+ export declare function serializeToFhirJson(resource: Resource): string;
3034
+
3035
+ /**
3036
+ * Serialize a Resource object to a plain JavaScript object suitable
3037
+ * for FHIR JSON (without calling `JSON.stringify`).
3038
+ *
3039
+ * Use this when you need the object form (e.g., for storage or
3040
+ * further manipulation) rather than a string.
3041
+ *
3042
+ * @param resource - The Resource to serialize
3043
+ * @returns A plain object conforming to FHIR JSON conventions
3044
+ */
3045
+ export declare function serializeToFhirObject(resource: Resource): Record<string, unknown>;
3046
+
3047
+ /**
3048
+ * Populate `dest.base` with traceability information from the base element.
3049
+ *
3050
+ * Corresponds to HAPI `updateFromBase(derived, base)`.
3051
+ * If `base` already has a `.base`, we copy from `base.base` (preserving
3052
+ * original ancestry). Otherwise we copy from `base` directly.
3053
+ *
3054
+ * @param dest - The element to set base traceability on.
3055
+ * @param base - The base element to derive traceability from.
3056
+ */
3057
+ export declare function setBaseTraceability(dest: ElementDefinition, base: ElementDefinition): void;
3058
+
3059
+ /**
3060
+ * A resolved slicing definition on a canonical element.
3061
+ *
3062
+ * Corresponds to a simplified version of `ElementDefinition.slicing`.
3063
+ * Unlike the FHIR version, `ordered` is always a boolean (default `false`).
3064
+ */
3065
+ export declare interface SlicingDefinition {
3066
+ /** Discriminators used to match slices. */
3067
+ discriminators: SlicingDiscriminatorDef[];
3068
+ /**
3069
+ * closed | open | openAtEnd
3070
+ * @see https://hl7.org/fhir/R4/valueset-resource-slicing-rules.html
3071
+ */
3072
+ rules: SlicingRules;
3073
+ /**
3074
+ * Whether elements must appear in the same order as slices.
3075
+ *
3076
+ * Always has a value (default `false`), unlike the FHIR spec where
3077
+ * this is optional.
3078
+ */
3079
+ ordered: boolean;
3080
+ /** Human-readable description of the slicing. */
3081
+ description?: string;
3082
+ }
3083
+
3084
+ /**
3085
+ * Designates a discriminator to differentiate between slices.
3086
+ * @see https://hl7.org/fhir/R4/elementdefinition-definitions.html#ElementDefinition.slicing.discriminator
3087
+ */
3088
+ export declare interface SlicingDiscriminator extends Element {
3089
+ /**
3090
+ * value | exists | pattern | type | profile (1..1)
3091
+ * @see https://hl7.org/fhir/R4/valueset-discriminator-type.html
3092
+ */
3093
+ type: DiscriminatorType;
3094
+ /**
3095
+ * Path to element value (1..1)
3096
+ *
3097
+ * A FHIRPath expression that identifies the element within the
3098
+ * resource/type to be used as the discriminator.
3099
+ */
3100
+ path: FhirString;
3101
+ }
3102
+
3103
+ /**
3104
+ * A single discriminator within a slicing definition.
3105
+ *
3106
+ * Corresponds to `ElementDefinition.slicing.discriminator`.
3107
+ */
3108
+ export declare interface SlicingDiscriminatorDef {
3109
+ /**
3110
+ * value | exists | pattern | type | profile
3111
+ * @see https://hl7.org/fhir/R4/valueset-discriminator-type.html
3112
+ */
3113
+ type: DiscriminatorType;
3114
+ /**
3115
+ * FHIRPath expression identifying the discriminating element.
3116
+ */
3117
+ path: string;
3118
+ }
3119
+
3120
+ /**
3121
+ * How slices are interpreted when evaluating an instance.
3122
+ * @see https://hl7.org/fhir/R4/valueset-resource-slicing-rules.html
3123
+ */
3124
+ export declare type SlicingRules = 'closed' | 'open' | 'openAtEnd';
3125
+
3126
+ /**
3127
+ * Thrown when snapshot generation detects a circular dependency in the
3128
+ * profile chain.
3129
+ *
3130
+ * This occurs when profile A's base chain eventually references A again,
3131
+ * which would cause infinite recursion during snapshot generation.
3132
+ * HAPI detects this via a `snapshotStack` of URLs currently being generated.
3133
+ *
3134
+ * @example
3135
+ * ```typescript
3136
+ * throw new SnapshotCircularDependencyError(
3137
+ * 'http://example.org/ProfileA',
3138
+ * [
3139
+ * 'http://example.org/ProfileA',
3140
+ * 'http://example.org/ProfileB',
3141
+ * 'http://example.org/ProfileA', // cycle back
3142
+ * ]
3143
+ * );
3144
+ * ```
3145
+ */
3146
+ export declare class SnapshotCircularDependencyError extends ProfileError {
3147
+ readonly name = "SnapshotCircularDependencyError";
3148
+ /** The canonical URL of the profile that triggered the cycle. */
3149
+ readonly url: string;
3150
+ /** The full chain of URLs forming the cycle. */
3151
+ readonly chain: readonly string[];
3152
+ constructor(url: string, chain: string[]);
3153
+ }
3154
+
3155
+ /**
3156
+ * Snapshot Generator — top-level orchestrator for snapshot generation.
3157
+ *
3158
+ * Corresponds to HAPI's `ProfileUtilities.generateSnapshot()`.
3159
+ *
3160
+ * @example
3161
+ * ```typescript
3162
+ * const generator = new SnapshotGenerator(fhirContext, { throwOnError: false });
3163
+ * const result = await generator.generate(myProfile);
3164
+ * if (result.success) {
3165
+ * console.log('Snapshot generated with', result.structureDefinition.snapshot?.element.length, 'elements');
3166
+ * }
3167
+ * ```
3168
+ */
3169
+ export declare class SnapshotGenerator {
3170
+ private readonly context;
3171
+ private readonly options;
3172
+ /** URLs currently being generated — for circular dependency detection. */
3173
+ private readonly generationStack;
3174
+ constructor(context: FhirContext, options?: SnapshotGeneratorOptions);
3175
+ /**
3176
+ * Generate a snapshot for a StructureDefinition.
3177
+ *
3178
+ * @param sd - StructureDefinition with a differential to expand.
3179
+ * @returns SnapshotResult with the populated snapshot and any issues.
3180
+ * @throws {SnapshotCircularDependencyError} if circular reference detected
3181
+ * @throws {BaseNotFoundError} if base SD cannot be loaded
3182
+ * @throws {UnconsumedDifferentialError} if throwOnError and unconsumed diffs
3183
+ */
3184
+ generate(sd: StructureDefinition): Promise<SnapshotResult>;
3185
+ /**
3186
+ * Validate input StructureDefinition.
3187
+ * Returns true if there's a fatal validation error.
3188
+ */
3189
+ private validateInput;
3190
+ /**
3191
+ * Load the base StructureDefinition.
3192
+ */
3193
+ private loadBase;
3194
+ /**
3195
+ * Populate the datatype cache with snapshots of types referenced by
3196
+ * the differential's child paths.
3197
+ *
3198
+ * Scans both base elements and diff elements for type codes, then
3199
+ * pre-loads their StructureDefinitions into the merge context cache.
3200
+ */
3201
+ private populateDatatypeCache;
3202
+ /**
3203
+ * Build a SnapshotResult from the current state.
3204
+ */
3205
+ private buildResult;
3206
+ }
3207
+
3208
+ /**
3209
+ * Configuration options for snapshot generation.
3210
+ *
3211
+ * @example
3212
+ * ```typescript
3213
+ * const options: SnapshotGeneratorOptions = {
3214
+ * throwOnError: false,
3215
+ * maxRecursionDepth: 50,
3216
+ * generateCanonical: true,
3217
+ * };
3218
+ * ```
3219
+ */
3220
+ export declare interface SnapshotGeneratorOptions {
3221
+ /**
3222
+ * Whether to throw on the first error or collect all errors.
3223
+ *
3224
+ * When `true`, the generator throws immediately on the first error
3225
+ * (matching HAPI's "exception mode"). When `false` (default), errors
3226
+ * are collected in {@link SnapshotResult.issues} and generation
3227
+ * continues as far as possible.
3228
+ *
3229
+ * @default false
3230
+ */
3231
+ readonly throwOnError?: boolean;
3232
+ /**
3233
+ * Maximum recursion depth for nested snapshot generation.
3234
+ *
3235
+ * Snapshot generation can recursively trigger generation of other
3236
+ * profiles (e.g., when a base profile lacks a snapshot, or when
3237
+ * expanding into datatype definitions). This limit prevents runaway
3238
+ * recursion in pathological or circular profiles.
3239
+ *
3240
+ * @default 50
3241
+ */
3242
+ readonly maxRecursionDepth?: number;
3243
+ /**
3244
+ * Whether to generate a {@link CanonicalProfile} alongside the snapshot.
3245
+ *
3246
+ * When `true`, the result includes a `canonical` field containing
3247
+ * the MedXAI internal semantic model derived from the generated snapshot.
3248
+ *
3249
+ * @default false
3250
+ */
3251
+ readonly generateCanonical?: boolean;
3252
+ }
3253
+
3254
+ /**
3255
+ * An issue encountered during snapshot generation.
3256
+ *
3257
+ * Mirrors the concept of HAPI's `ValidationMessage` but scoped to
3258
+ * snapshot generation. Issues are collected during generation and
3259
+ * returned in {@link SnapshotResult.issues}.
3260
+ *
3261
+ * @example
3262
+ * ```typescript
3263
+ * const issue: SnapshotIssue = {
3264
+ * severity: 'error',
3265
+ * code: 'CARDINALITY_VIOLATION',
3266
+ * message: 'Derived min (0) is less than base min (1)',
3267
+ * path: 'Patient.identifier',
3268
+ * };
3269
+ * ```
3270
+ */
3271
+ export declare interface SnapshotIssue {
3272
+ /** Severity level of the issue. */
3273
+ readonly severity: 'error' | 'warning' | 'information';
3274
+ /** Machine-readable issue code. */
3275
+ readonly code: SnapshotIssueCode;
3276
+ /** Human-readable description of the issue. */
3277
+ readonly message: string;
3278
+ /** Element path where the issue occurred (e.g., `'Patient.identifier'`). */
3279
+ readonly path?: string;
3280
+ /** Additional details for debugging. */
3281
+ readonly details?: string;
3282
+ }
3283
+
3284
+ /**
3285
+ * Machine-readable issue codes for snapshot generation.
3286
+ *
3287
+ * Each code corresponds to a specific category of problem that can
3288
+ * occur during the snapshot generation process.
3289
+ */
3290
+ export declare type SnapshotIssueCode =
3291
+ /** Circular dependency detected in profile chain. */
3292
+ 'CIRCULAR_DEPENDENCY'
3293
+ /** Base StructureDefinition could not be loaded. */
3294
+ | 'BASE_NOT_FOUND'
3295
+ /** Base StructureDefinition exists but has no snapshot. */
3296
+ | 'BASE_MISSING_SNAPSHOT'
3297
+ /** Differential element was not consumed during generation. */
3298
+ | 'DIFFERENTIAL_NOT_CONSUMED'
3299
+ /** Cardinality constraint violation (min/max tightening rules). */
3300
+ | 'CARDINALITY_VIOLATION'
3301
+ /** Type constraint is incompatible with base types. */
3302
+ | 'TYPE_INCOMPATIBLE'
3303
+ /** Binding constraint violation (e.g., relaxing REQUIRED binding). */
3304
+ | 'BINDING_VIOLATION'
3305
+ /** Slicing-related error (compatibility, closed slicing, etc.). */
3306
+ | 'SLICING_ERROR'
3307
+ /** Differential path not found in base snapshot. */
3308
+ | 'PATH_NOT_FOUND'
3309
+ /** Generic invalid constraint (catch-all for other violations). */
3310
+ | 'INVALID_CONSTRAINT'
3311
+ /** Internal error in the generator (should not happen). */
3312
+ | 'INTERNAL_ERROR';
3313
+
3314
+ /**
3315
+ * Result of snapshot generation.
3316
+ *
3317
+ * Contains the StructureDefinition with its populated snapshot, any issues
3318
+ * encountered during generation, and optionally a {@link CanonicalProfile}.
3319
+ *
3320
+ * @example
3321
+ * ```typescript
3322
+ * const result = await generator.generate(sd);
3323
+ * if (result.success) {
3324
+ * console.log(`Generated ${result.structureDefinition.snapshot?.element.length} elements`);
3325
+ * } else {
3326
+ * console.error('Errors:', result.issues.filter(i => i.severity === 'error'));
3327
+ * }
3328
+ * ```
3329
+ */
3330
+ export declare interface SnapshotResult {
3331
+ /** The StructureDefinition with populated snapshot. */
3332
+ readonly structureDefinition: StructureDefinition;
3333
+ /**
3334
+ * Optional {@link CanonicalProfile} if
3335
+ * {@link SnapshotGeneratorOptions.generateCanonical} was `true`.
3336
+ */
3337
+ readonly canonical?: CanonicalProfile;
3338
+ /** Issues encountered during generation (warnings + errors). */
3339
+ readonly issues: readonly SnapshotIssue[];
3340
+ /**
3341
+ * Whether generation completed successfully.
3342
+ *
3343
+ * `true` when no error-severity issues were recorded.
3344
+ * Warnings and informational issues do not affect this flag.
3345
+ */
3346
+ readonly success: boolean;
3347
+ }
3348
+
3349
+ /**
3350
+ * Sort differential elements according to base snapshot order.
3351
+ *
3352
+ * Corresponds to HAPI's `sortDifferential()`. The algorithm:
3353
+ * 1. Build a tree from the differential elements (parent-child by path)
3354
+ * 2. Assign each node a base index via {@link findBaseIndex}
3355
+ * 3. Sort children at each level by base index
3356
+ * 4. Flatten the tree back to a linear list
3357
+ *
3358
+ * Elements not found in the base are placed at the end of their level
3359
+ * and an issue is recorded.
3360
+ *
3361
+ * @param differential - The differential elements to sort (not mutated).
3362
+ * @param baseSnapshot - The base snapshot providing the authoritative order.
3363
+ * @param issues - Issue collector for recording problems.
3364
+ * @returns A new array of elements in sorted order.
3365
+ */
3366
+ export declare function sortDifferential(differential: readonly ElementDefinition[], baseSnapshot: readonly ElementDefinition[], issues: SnapshotIssue[]): ElementDefinition[];
3367
+
3368
+ /**
3369
+ * A definition of a FHIR structure — a resource, data type, or extension.
3370
+ *
3371
+ * StructureDefinition is the central metadata resource in FHIR. It defines:
3372
+ * - The shape of resources and data types (via snapshot/differential)
3373
+ * - Profile constraints (via derivation = 'constraint')
3374
+ * - Extension definitions (via kind = 'resource', type = 'Extension')
3375
+ *
3376
+ * This interface extends DomainResource and includes all fields defined
3377
+ * in the FHIR R4 specification.
3378
+ *
3379
+ * @see https://hl7.org/fhir/R4/structuredefinition.html
3380
+ */
3381
+ export declare interface StructureDefinition extends DomainResource {
3382
+ /** Resource type discriminator (1..1) */
3383
+ resourceType: 'StructureDefinition';
3384
+ /**
3385
+ * Canonical identifier for this structure definition, represented as a URI
3386
+ * (globally unique) (1..1)
3387
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.url
3388
+ */
3389
+ url: FhirUri;
3390
+ /**
3391
+ * Additional identifier for the structure definition (0..*)
3392
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.identifier
3393
+ */
3394
+ identifier?: Identifier[];
3395
+ /**
3396
+ * Business version of the structure definition (0..1)
3397
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.version
3398
+ */
3399
+ version?: FhirString;
3400
+ /**
3401
+ * Computer-readable name of the structure definition (1..1)
3402
+ *
3403
+ * Name should be usable as an identifier for the module by machine
3404
+ * processing applications such as code generation.
3405
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.name
3406
+ */
3407
+ name: FhirString;
3408
+ /**
3409
+ * Human-readable name for the structure definition (0..1)
3410
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.title
3411
+ */
3412
+ title?: FhirString;
3413
+ /**
3414
+ * Publication status: draft | active | retired | unknown (1..1)
3415
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.status
3416
+ */
3417
+ status: PublicationStatus;
3418
+ /**
3419
+ * For testing purposes, not real usage (0..1)
3420
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.experimental
3421
+ */
3422
+ experimental?: FhirBoolean;
3423
+ /**
3424
+ * Date last changed (0..1)
3425
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.date
3426
+ */
3427
+ date?: FhirDateTime;
3428
+ /**
3429
+ * Name of the publisher (organization or individual) (0..1)
3430
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.publisher
3431
+ */
3432
+ publisher?: FhirString;
3433
+ /**
3434
+ * Contact details for the publisher (0..*)
3435
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.contact
3436
+ */
3437
+ contact?: ContactDetail[];
3438
+ /**
3439
+ * Natural language description of the structure definition (0..1)
3440
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.description
3441
+ */
3442
+ description?: FhirMarkdown;
3443
+ /**
3444
+ * The context that the content is intended to support (0..*)
3445
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.useContext
3446
+ */
3447
+ useContext?: UsageContext[];
3448
+ /**
3449
+ * Intended jurisdiction for structure definition (0..*)
3450
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.jurisdiction
3451
+ */
3452
+ jurisdiction?: CodeableConcept[];
3453
+ /**
3454
+ * Why this structure definition is defined (0..1)
3455
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.purpose
3456
+ */
3457
+ purpose?: FhirMarkdown;
3458
+ /**
3459
+ * Use and/or publishing restrictions (0..1)
3460
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.copyright
3461
+ */
3462
+ copyright?: FhirMarkdown;
3463
+ /**
3464
+ * Assist with indexing and finding (0..*)
3465
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.keyword
3466
+ */
3467
+ keyword?: Coding[];
3468
+ /**
3469
+ * FHIR Version this StructureDefinition targets (0..1)
3470
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.fhirVersion
3471
+ */
3472
+ fhirVersion?: FhirVersionCode;
3473
+ /**
3474
+ * External specification that the content is mapped to (0..*)
3475
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.mapping
3476
+ */
3477
+ mapping?: StructureDefinitionMapping[];
3478
+ /**
3479
+ * The kind of structure: primitive-type | complex-type | resource | logical (1..1)
3480
+ *
3481
+ * Determines the fundamental nature of the structure being defined.
3482
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.kind
3483
+ */
3484
+ kind: StructureDefinitionKind;
3485
+ /**
3486
+ * Whether the structure is abstract (1..1)
3487
+ *
3488
+ * Abstract types cannot be instantiated directly. For example,
3489
+ * `DomainResource` is abstract — you cannot create a resource
3490
+ * with `resourceType: "DomainResource"`.
3491
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.abstract
3492
+ */
3493
+ abstract: FhirBoolean;
3494
+ /**
3495
+ * If an extension, where it can be used in instances (0..*)
3496
+ *
3497
+ * Only meaningful when kind = 'resource' and type = 'Extension'.
3498
+ * Defines the contexts in which the extension can appear.
3499
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.context
3500
+ */
3501
+ context?: StructureDefinitionContext[];
3502
+ /**
3503
+ * FHIRPath invariants — conditions that must be true for the
3504
+ * extension to be valid in a given context (0..*)
3505
+ *
3506
+ * Only meaningful when kind = 'resource' and type = 'Extension'.
3507
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.contextInvariant
3508
+ */
3509
+ contextInvariant?: FhirString[];
3510
+ /**
3511
+ * Type defined or constrained by this structure (1..1)
3512
+ *
3513
+ * For base definitions (derivation = 'specialization'), this is the
3514
+ * type being defined (e.g., 'Patient', 'Observation').
3515
+ * For profiles (derivation = 'constraint'), this is the type being
3516
+ * constrained (must match the type of the base definition).
3517
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.type
3518
+ */
3519
+ type: FhirUri;
3520
+ /**
3521
+ * Definition that this type is constrained/specialized from (0..1)
3522
+ *
3523
+ * The canonical URL of the base StructureDefinition. This forms the
3524
+ * inheritance chain used in snapshot generation.
3525
+ * - For specializations: points to the parent type
3526
+ * - For constraints: points to the profile being constrained
3527
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.baseDefinition
3528
+ */
3529
+ baseDefinition?: FhirCanonical;
3530
+ /**
3531
+ * specialization | constraint (0..1)
3532
+ *
3533
+ * - `specialization`: defines a new type (e.g., Patient specializes DomainResource)
3534
+ * - `constraint`: constrains an existing type (e.g., USCorePatient constrains Patient)
3535
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.derivation
3536
+ */
3537
+ derivation?: TypeDerivationRule;
3538
+ /**
3539
+ * Snapshot view of the structure (0..1)
3540
+ *
3541
+ * Contains the complete, flattened element tree with all constraints
3542
+ * from the inheritance chain resolved. Generated by the snapshot
3543
+ * generation algorithm (fhir-profile module).
3544
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.snapshot
3545
+ */
3546
+ snapshot?: StructureDefinitionSnapshot;
3547
+ /**
3548
+ * Differential constraints of the structure (0..1)
3549
+ *
3550
+ * Contains only the constraints that differ from the base definition.
3551
+ * This is the authoring format — profiles are typically written as
3552
+ * differentials to avoid repeating base constraints.
3553
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.differential
3554
+ */
3555
+ differential?: StructureDefinitionDifferential;
3556
+ }
3557
+
3558
+ /**
3559
+ * Identifies the types of resource or data type elements to which the
3560
+ * extension can be applied. Only relevant when kind = 'resource' and
3561
+ * type = 'Extension'.
3562
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.context
3563
+ */
3564
+ export declare interface StructureDefinitionContext extends BackboneElement {
3565
+ /** fhirpath | element | extension (1..1) */
3566
+ type: ExtensionContextType;
3567
+ /** Where the extension can be used in instances (1..1) */
3568
+ expression: FhirString;
3569
+ }
3570
+
3571
+ /**
3572
+ * A differential view of the structure, containing only the constraints
3573
+ * that differ from the base definition. This is the compact authoring
3574
+ * format used when creating profiles.
3575
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.differential
3576
+ */
3577
+ export declare interface StructureDefinitionDifferential extends BackboneElement {
3578
+ /**
3579
+ * Definition of elements in the resource (if no StructureDefinition) (1..*)
3580
+ *
3581
+ * The differential contains only the constraints that differ from the base
3582
+ * profile. It MUST NOT be used directly for semantic interpretation — it
3583
+ * must first be expanded into a snapshot via snapshot generation.
3584
+ */
3585
+ element: ElementDefinition[];
3586
+ }
3587
+
3588
+ /**
3589
+ * The kind of structure being defined by a StructureDefinition.
3590
+ * @see https://hl7.org/fhir/R4/valueset-structure-definition-kind.html
3591
+ */
3592
+ export declare type StructureDefinitionKind = 'primitive-type' | 'complex-type' | 'resource' | 'logical';
3593
+
3594
+ /**
3595
+ * Pluggable strategy for loading StructureDefinitions from an external source.
3596
+ *
3597
+ * Implementations include:
3598
+ * - `MemoryLoader` — loads from an in-memory map (for testing / preloaded data)
3599
+ * - `FileSystemLoader` — loads from local JSON files
3600
+ * - `CompositeLoader` — chains multiple loaders (fallback pattern)
3601
+ *
3602
+ * Conceptually equivalent to HAPI's `IValidationSupport` implementations.
3603
+ */
3604
+ export declare interface StructureDefinitionLoader {
3605
+ /**
3606
+ * Attempt to load a StructureDefinition by canonical URL.
3607
+ *
3608
+ * @param url - Canonical URL (without `|version` — version is stripped
3609
+ * by the caller before delegation)
3610
+ * @returns The loaded StructureDefinition, or `null` if this loader
3611
+ * cannot resolve the URL (allows fallback to next loader)
3612
+ * @throws {@link LoaderError} on I/O or parse failures
3613
+ */
3614
+ load(url: string): Promise<StructureDefinition | null>;
3615
+ /**
3616
+ * Quick check whether this loader is likely able to resolve the URL.
3617
+ *
3618
+ * This is a hint — returning `true` does not guarantee `load()` will
3619
+ * succeed. Returning `false` allows the composite loader to skip this
3620
+ * source entirely.
3621
+ *
3622
+ * @param url - Canonical URL to check
3623
+ */
3624
+ canLoad(url: string): boolean;
3625
+ /**
3626
+ * Human-readable identifier for the loader source.
3627
+ *
3628
+ * Used in error messages and diagnostics.
3629
+ *
3630
+ * @returns Source type label (e.g., `'memory'`, `'filesystem'`, `'http'`)
3631
+ */
3632
+ getSourceType(): string;
3633
+ }
3634
+
3635
+ /**
3636
+ * A mapping to an external specification that the structure conforms to.
3637
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.mapping
3638
+ */
3639
+ export declare interface StructureDefinitionMapping extends BackboneElement {
3640
+ /** Internal id when this mapping is used (1..1) */
3641
+ identity: FhirId;
3642
+ /** Identifies what this mapping refers to (0..1) */
3643
+ uri?: FhirUri;
3644
+ /** Names what this mapping refers to (0..1) */
3645
+ name?: FhirString;
3646
+ /** Versions, issues, scope limitations, etc. (0..1) */
3647
+ comment?: FhirString;
3648
+ }
3649
+
3650
+ /**
3651
+ * In-memory registry for StructureDefinitions.
3652
+ *
3653
+ * Storage strategy:
3654
+ * - **Primary map**: keyed by `url|version` (exact match)
3655
+ * - **Latest map**: keyed by bare `url` → points to the most recently
3656
+ * registered version (for unversioned lookups)
3657
+ *
3658
+ * When a lookup uses a bare URL (no `|version`), the latest map is consulted.
3659
+ * When a lookup uses `url|version`, the primary map is used for exact match.
3660
+ */
3661
+ declare class StructureDefinitionRegistry {
3662
+ /** Primary storage: `url|version` → StructureDefinition */
3663
+ private readonly _entries;
3664
+ /** Latest-version index: bare `url` → `url|version` key in _entries */
3665
+ private readonly _latestIndex;
3666
+ /** Statistics counters */
3667
+ private _queryCount;
3668
+ private _hitCount;
3669
+ /**
3670
+ * Register a StructureDefinition.
3671
+ *
3672
+ * Validates that the definition has a `url` field. If a definition with
3673
+ * the same URL (and version) already exists, it is silently replaced.
3674
+ *
3675
+ * @param sd - The StructureDefinition to register
3676
+ * @throws {@link InvalidStructureDefinitionError} if `sd.url` is missing
3677
+ */
3678
+ register(sd: StructureDefinition): void;
3679
+ /**
3680
+ * Remove a StructureDefinition by canonical URL.
3681
+ *
3682
+ * @param urlWithVersion - Canonical URL (with optional `|version`)
3683
+ * @returns `true` if a definition was removed, `false` if not found
3684
+ */
3685
+ delete(urlWithVersion: string): boolean;
3686
+ /**
3687
+ * Remove all entries and reset statistics.
3688
+ */
3689
+ clear(): void;
3690
+ /**
3691
+ * Retrieve a StructureDefinition by canonical URL.
3692
+ *
3693
+ * - If `urlWithVersion` contains `|version`, performs exact match.
3694
+ * - If no version, returns the latest registered version.
3695
+ *
3696
+ * @param urlWithVersion - Canonical URL (with optional `|version`)
3697
+ * @returns The StructureDefinition, or `undefined` if not found
3698
+ */
3699
+ get(urlWithVersion: string): StructureDefinition | undefined;
3700
+ /**
3701
+ * Check whether a StructureDefinition is registered.
3702
+ *
3703
+ * @param urlWithVersion - Canonical URL (with optional `|version`)
3704
+ */
3705
+ has(urlWithVersion: string): boolean;
3706
+ /**
3707
+ * Total number of registered StructureDefinitions.
3708
+ */
3709
+ get size(): number;
3710
+ /**
3711
+ * Return all registered canonical URLs (including version suffixes).
3712
+ */
3713
+ getAllKeys(): string[];
3714
+ /**
3715
+ * Return all registered bare URLs (without version suffixes).
3716
+ */
3717
+ getAllUrls(): string[];
3718
+ /**
3719
+ * Total number of `get()` calls.
3720
+ */
3721
+ get queryCount(): number;
3722
+ /**
3723
+ * Number of `get()` calls that returned a result (cache hits).
3724
+ */
3725
+ get hitCount(): number;
3726
+ /**
3727
+ * Number of `get()` calls that returned `undefined` (cache misses).
3728
+ */
3729
+ get missCount(): number;
3730
+ /**
3731
+ * Cache hit ratio (0–1). Returns 0 if no queries have been made.
3732
+ */
3733
+ get hitRate(): number;
3734
+ }
3735
+
3736
+ /**
3737
+ * A snapshot view of the structure, containing all element definitions
3738
+ * with their complete constraint information resolved from the
3739
+ * inheritance chain.
3740
+ * @see https://hl7.org/fhir/R4/structuredefinition-definitions.html#StructureDefinition.snapshot
3741
+ */
3742
+ export declare interface StructureDefinitionSnapshot extends BackboneElement {
3743
+ /**
3744
+ * Definition of elements in the resource (if no StructureDefinition) (1..*)
3745
+ *
3746
+ * The snapshot contains the complete, flattened list of all ElementDefinition
3747
+ * entries with all constraints from the inheritance chain fully resolved.
3748
+ * This is the "semantic truth" used for validation and interpretation.
3749
+ */
3750
+ element: ElementDefinition[];
3751
+ }
3752
+
3753
+ /**
3754
+ * Main validator class for structural validation of FHIR resources.
3755
+ *
3756
+ * Validates a resource instance against a {@link CanonicalProfile} by
3757
+ * orchestrating all individual validation rules (cardinality, type,
3758
+ * fixed/pattern, reference, slicing).
3759
+ *
3760
+ * @example
3761
+ * ```typescript
3762
+ * const validator = new StructureValidator();
3763
+ *
3764
+ * // Validate with an explicit profile
3765
+ * const result = validator.validate(patient, patientProfile);
3766
+ *
3767
+ * if (!result.valid) {
3768
+ * for (const issue of result.issues) {
3769
+ * console.error(`${issue.severity}: ${issue.message}`);
3770
+ * }
3771
+ * }
3772
+ * ```
3773
+ */
3774
+ export declare class StructureValidator {
3775
+ private readonly options;
3776
+ constructor(options?: ValidationOptions);
3777
+ /**
3778
+ * Validate a resource instance against a CanonicalProfile.
3779
+ *
3780
+ * @param resource - The FHIR resource to validate.
3781
+ * @param profile - The CanonicalProfile to validate against.
3782
+ * @param options - Optional per-call overrides for validation options.
3783
+ * @returns The validation result with all issues.
3784
+ * @throws {@link ProfileNotFoundError} if profile is undefined.
3785
+ * @throws {@link ValidationFailedError} if failFast is enabled and an error is found.
3786
+ */
3787
+ validate(resource: Resource, profile: CanonicalProfile, options?: ValidationOptions): ValidationResult;
3788
+ /**
3789
+ * Check that the resource type matches the profile type.
3790
+ */
3791
+ private validateResourceType;
3792
+ /**
3793
+ * Validate all elements in the profile against the resource.
3794
+ */
3795
+ private validateElements;
3796
+ /**
3797
+ * Get all named slice elements for a slicing root path.
3798
+ */
3799
+ private getSliceElements;
3800
+ /**
3801
+ * Check if failFast is enabled and there are errors; if so, throw.
3802
+ */
3803
+ private checkFailFast;
3804
+ }
3805
+
3806
+ /**
3807
+ * Get the last segment (tail) of a path.
3808
+ *
3809
+ * @example
3810
+ * tailSegment('Patient.name.given') // 'given'
3811
+ * tailSegment('Patient') // 'Patient'
3812
+ */
3813
+ export declare function tailSegment(path: string): string;
3814
+
3815
+ /**
3816
+ * Cursor-based scope for base-driven traversal.
3817
+ *
3818
+ * Used by the element merger (`processPaths` equivalent) to define
3819
+ * the current working range within a list of ElementDefinitions.
3820
+ * Both `start` and `end` are inclusive indices.
3821
+ *
3822
+ * This mirrors HAPI's `baseCursor/baseLimit` and `diffCursor/diffLimit`
3823
+ * parameter pairs in `processPaths()`.
3824
+ *
3825
+ * @example
3826
+ * ```typescript
3827
+ * // Scope covering elements[2] through elements[5]
3828
+ * const scope: TraversalScope = {
3829
+ * elements: baseSnapshot.element,
3830
+ * start: 2,
3831
+ * end: 5,
3832
+ * };
3833
+ * ```
3834
+ *
3835
+ * @internal Used by {@link ElementMerger}.
3836
+ */
3837
+ export declare interface TraversalScope {
3838
+ /** The element list being traversed. */
3839
+ readonly elements: readonly ElementDefinition[];
3840
+ /** Start index (inclusive). */
3841
+ readonly start: number;
3842
+ /** End index (inclusive). */
3843
+ readonly end: number;
3844
+ }
3845
+
3846
+ /**
3847
+ * A resolved type constraint on a canonical element.
3848
+ *
3849
+ * Corresponds to a simplified, pre-validated version of
3850
+ * `ElementDefinition.type` from the FHIR spec.
3851
+ */
3852
+ export declare interface TypeConstraint {
3853
+ /**
3854
+ * The data type or resource name (e.g., `string`, `Reference`, `Patient`).
3855
+ *
3856
+ * Unlike `ElementDefinitionType.code` (which is a URI), this is the
3857
+ * resolved short name used for runtime dispatch.
3858
+ */
3859
+ code: string;
3860
+ /**
3861
+ * Profiles that the type must conform to (resolved canonical URLs).
3862
+ *
3863
+ * Corresponds to `ElementDefinitionType.profile`.
3864
+ */
3865
+ profiles?: string[];
3866
+ /**
3867
+ * For Reference/canonical types, profiles that the target must conform to.
3868
+ *
3869
+ * Corresponds to `ElementDefinitionType.targetProfile`.
3870
+ */
3871
+ targetProfiles?: string[];
3872
+ }
3873
+
3874
+ /**
3875
+ * Whether a StructureDefinition is a specialization or a constraint.
3876
+ * - `specialization`: defines a new type (e.g., Patient specializes DomainResource)
3877
+ * - `constraint`: constrains an existing type (e.g., USCorePatient constrains Patient)
3878
+ * @see https://hl7.org/fhir/R4/valueset-type-derivation-rule.html
3879
+ */
3880
+ export declare type TypeDerivationRule = 'specialization' | 'constraint';
3881
+
3882
+ /**
3883
+ * A value paired with its FHIR type identifier.
3884
+ * This is the fundamental unit of data flowing through the FHIRPath engine.
3885
+ *
3886
+ * @example
3887
+ * ```ts
3888
+ * const tv: TypedValue = { type: PropertyType.string, value: 'hello' };
3889
+ * ```
3890
+ */
3891
+ declare interface TypedValue {
3892
+ readonly type: string;
3893
+ readonly value: unknown;
3894
+ }
3895
+
3896
+ /**
3897
+ * Thrown when differential elements remain unconsumed after snapshot
3898
+ * generation completes.
3899
+ *
3900
+ * This indicates that the algorithm could not find a matching base
3901
+ * element for one or more differential entries. Common causes:
3902
+ * - Incorrect path in differential
3903
+ * - Slicing mismatch
3904
+ * - Unsupported constraint pattern
3905
+ *
3906
+ * HAPI detects this via the `GENERATED_IN_SNAPSHOT` marker pattern.
3907
+ *
3908
+ * Only thrown when {@link SnapshotGeneratorOptions.throwOnError} is `true`.
3909
+ * Otherwise, each unconsumed element is recorded as an issue.
3910
+ *
3911
+ * @example
3912
+ * ```typescript
3913
+ * throw new UnconsumedDifferentialError([
3914
+ * 'Patient.nonExistentField',
3915
+ * 'Patient.identifier:BadSlice',
3916
+ * ]);
3917
+ * ```
3918
+ */
3919
+ export declare class UnconsumedDifferentialError extends ProfileError {
3920
+ readonly name = "UnconsumedDifferentialError";
3921
+ /** Paths of the unconsumed differential elements. */
3922
+ readonly unconsumedPaths: readonly string[];
3923
+ constructor(unconsumedPaths: string[]);
3924
+ }
3925
+
3926
+ /**
3927
+ * Specifies clinical/business/etc. context in which a conformance
3928
+ * artifact is applicable.
3929
+ * @see https://hl7.org/fhir/R4/metadatatypes.html#UsageContext
3930
+ */
3931
+ export declare interface UsageContext extends Element {
3932
+ /** Type of context being specified (1..1) */
3933
+ code: Coding;
3934
+ /**
3935
+ * Value that defines the context (1..1).
3936
+ *
3937
+ * Choice type [x] — the actual property name in JSON will be
3938
+ * `valueCodeableConcept`, `valueQuantity`, `valueRange`, or `valueReference`.
3939
+ * Allows: CodeableConcept | Quantity | Range | Reference.
3940
+ *
3941
+ * Stage-1: represented as `unknown`; fhir-parser will handle
3942
+ * concrete dispatch in Phase 2.
3943
+ * @see https://hl7.org/fhir/R4/metadatatypes-definitions.html#UsageContext.value_x_
3944
+ */
3945
+ value?: unknown;
3946
+ }
3947
+
3948
+ /**
3949
+ * Validate that snapshot elements are in correct order.
3950
+ *
3951
+ * Rules:
3952
+ * - Parent elements must appear before their children
3953
+ * - Slice elements must appear after their slicing root
3954
+ * - No duplicate paths (unless sliced)
3955
+ *
3956
+ * @param snapshot - The snapshot elements to validate.
3957
+ * @param issues - Issue collector for recording problems.
3958
+ * @returns `true` if order is valid, `false` if any violations found.
3959
+ */
3960
+ export declare function validateElementOrder(snapshot: readonly ElementDefinition[], issues: SnapshotIssue[]): boolean;
3961
+
3962
+ /**
3963
+ * Validate that a differential slicing definition is compatible with
3964
+ * the base slicing definition.
3965
+ *
3966
+ * Rules:
3967
+ * - Discriminators must match (same type and path, in same order)
3968
+ * - `ordered` cannot change from `true` to `false`
3969
+ * - `rules` cannot relax from `closed` to `open`/`openAtEnd`
3970
+ *
3971
+ * @param baseSlicing - The base element's slicing definition.
3972
+ * @param diffSlicing - The differential element's slicing definition.
3973
+ * @param issues - Issue collector for recording incompatibilities.
3974
+ * @param path - Element path for issue reporting.
3975
+ * @returns `true` if compatible, `false` if incompatible.
3976
+ */
3977
+ export declare function validateSlicingCompatibility(baseSlicing: ElementDefinitionSlicing, diffSlicing: ElementDefinitionSlicing, issues: SnapshotIssue[], path: string): boolean;
3978
+
3979
+ /**
3980
+ * Thrown when validation fails and {@link ValidationOptions.failFast} is enabled.
3981
+ *
3982
+ * Contains the issues accumulated up to the point of failure. This allows
3983
+ * callers to inspect the first error(s) that triggered the failure.
3984
+ *
3985
+ * @example
3986
+ * ```typescript
3987
+ * try {
3988
+ * await validator.validate(resource, { failFast: true });
3989
+ * } catch (err) {
3990
+ * if (err instanceof ValidationFailedError) {
3991
+ * console.error('First error:', err.issues[0].message);
3992
+ * }
3993
+ * }
3994
+ * ```
3995
+ */
3996
+ export declare class ValidationFailedError extends ValidatorError {
3997
+ readonly name = "ValidationFailedError";
3998
+ /** The validation issues accumulated before failure. */
3999
+ readonly issues: readonly ValidationIssue[];
4000
+ constructor(message: string, issues: readonly ValidationIssue[], cause?: Error);
4001
+ }
4002
+
4003
+ /**
4004
+ * A single issue encountered during validation.
4005
+ *
4006
+ * Mirrors the concept of FHIR OperationOutcome.issue but scoped to
4007
+ * structural validation. Issues are collected during validation and
4008
+ * returned in {@link ValidationResult.issues}.
4009
+ *
4010
+ * @example
4011
+ * ```typescript
4012
+ * const issue: ValidationIssue = {
4013
+ * severity: 'error',
4014
+ * code: 'CARDINALITY_MIN_VIOLATION',
4015
+ * message: "Element 'Patient.name' requires at least 1 value(s), but found 0",
4016
+ * path: 'Patient.name',
4017
+ * expression: 'Patient.name',
4018
+ * };
4019
+ * ```
4020
+ */
4021
+ export declare interface ValidationIssue {
4022
+ /** Severity level of the issue. */
4023
+ readonly severity: 'error' | 'warning' | 'information';
4024
+ /** Machine-readable issue code. */
4025
+ readonly code: ValidationIssueCode;
4026
+ /** Human-readable description of the issue. */
4027
+ readonly message: string;
4028
+ /**
4029
+ * Element path where the issue occurred (dot-notation).
4030
+ *
4031
+ * @example `'Patient.name'`, `'Observation.value[x]'`
4032
+ */
4033
+ readonly path?: string;
4034
+ /**
4035
+ * FHIRPath expression pointing to the problematic element.
4036
+ *
4037
+ * Typically identical to `path` for structural validation, but may
4038
+ * differ for sliced elements or choice types.
4039
+ *
4040
+ * @example `'Patient.identifier.where(system="urn:oid:1.2.3")'`
4041
+ */
4042
+ readonly expression?: string;
4043
+ /** Additional diagnostic information for debugging. */
4044
+ readonly diagnostics?: string;
4045
+ }
4046
+
4047
+ /**
4048
+ * Machine-readable issue codes for structural validation.
4049
+ *
4050
+ * Each code corresponds to a specific category of validation failure.
4051
+ * Codes are designed to be stable across versions for programmatic
4052
+ * consumption.
4053
+ */
4054
+ export declare type ValidationIssueCode =
4055
+ /** Element has fewer values than the minimum cardinality. */
4056
+ 'CARDINALITY_MIN_VIOLATION'
4057
+ /** Element has more values than the maximum cardinality. */
4058
+ | 'CARDINALITY_MAX_VIOLATION'
4059
+ /** Value type does not match any of the allowed types. */
4060
+ | 'TYPE_MISMATCH'
4061
+ /** Choice type field uses an unsupported type suffix. */
4062
+ | 'INVALID_CHOICE_TYPE'
4063
+ /** A required element (min ≥ 1) is missing from the resource. */
4064
+ | 'REQUIRED_ELEMENT_MISSING'
4065
+ /** Value does not match the fixed value constraint. */
4066
+ | 'FIXED_VALUE_MISMATCH'
4067
+ /** Value does not match the pattern value constraint (partial match). */
4068
+ | 'PATTERN_VALUE_MISMATCH'
4069
+ /** Value does not match any slice discriminator in a closed slicing. */
4070
+ | 'SLICING_NO_MATCH'
4071
+ /** Slice cardinality violation (too few or too many values in a slice). */
4072
+ | 'SLICING_CARDINALITY_VIOLATION'
4073
+ /** Ordered slicing constraint violated (values out of order). */
4074
+ | 'SLICING_ORDER_VIOLATION'
4075
+ /** Reference target does not match any of the allowed target profiles. */
4076
+ | 'REFERENCE_TARGET_MISMATCH'
4077
+ /** The specified profile could not be found or loaded. */
4078
+ | 'PROFILE_NOT_FOUND'
4079
+ /** Resource type does not match the profile's type. */
4080
+ | 'RESOURCE_TYPE_MISMATCH'
4081
+ /** Resource contains an element not defined in the profile. */
4082
+ | 'UNKNOWN_ELEMENT'
4083
+ /** FHIRPath invariant evaluation is not yet supported (skipped). */
4084
+ | 'INVARIANT_NOT_EVALUATED'
4085
+ /** FHIRPath invariant constraint evaluated to false. */
4086
+ | 'INVARIANT_VIOLATION'
4087
+ /** FHIRPath invariant expression failed to evaluate (runtime error). */
4088
+ | 'INVARIANT_EVALUATION_ERROR'
4089
+ /** Internal validator error (should not happen). */
4090
+ | 'INTERNAL_ERROR';
4091
+
4092
+ /**
4093
+ * Configuration options for structural validation.
4094
+ *
4095
+ * @example
4096
+ * ```typescript
4097
+ * const options: ValidationOptions = {
4098
+ * profileUrl: 'http://hl7.org/fhir/StructureDefinition/Patient',
4099
+ * validateSlicing: true,
4100
+ * validateFixed: true,
4101
+ * failFast: false,
4102
+ * };
4103
+ * ```
4104
+ */
4105
+ export declare interface ValidationOptions {
4106
+ /**
4107
+ * Profile URL to validate against.
4108
+ *
4109
+ * If not specified, the validator will attempt to extract the profile
4110
+ * from `resource.meta.profile[0]`. If neither is available, the
4111
+ * validator falls back to the base resource type
4112
+ * (e.g., `http://hl7.org/fhir/StructureDefinition/{resourceType}`).
4113
+ */
4114
+ readonly profileUrl?: string;
4115
+ /**
4116
+ * Whether to validate slicing constraints.
4117
+ *
4118
+ * When `true` (default), the validator checks that array elements
4119
+ * match their declared slices and that closed slicing rules are
4120
+ * respected.
4121
+ *
4122
+ * @default true
4123
+ */
4124
+ readonly validateSlicing?: boolean;
4125
+ /**
4126
+ * Whether to validate fixed and pattern value constraints.
4127
+ *
4128
+ * When `true` (default), the validator checks that element values
4129
+ * match any `fixed[x]` or `pattern[x]` constraints declared in
4130
+ * the profile.
4131
+ *
4132
+ * @default true
4133
+ */
4134
+ readonly validateFixed?: boolean;
4135
+ /**
4136
+ * Maximum depth for nested validation.
4137
+ *
4138
+ * Prevents runaway recursion in deeply nested or pathological
4139
+ * resource structures.
4140
+ *
4141
+ * @default 50
4142
+ */
4143
+ readonly maxDepth?: number;
4144
+ /**
4145
+ * Whether to stop on the first error or collect all issues.
4146
+ *
4147
+ * When `true`, the validator throws a {@link ValidationFailedError}
4148
+ * on the first error-severity issue. When `false` (default), all
4149
+ * issues are collected and returned in the result.
4150
+ *
4151
+ * @default false
4152
+ */
4153
+ readonly failFast?: boolean;
4154
+ /**
4155
+ * Whether to skip FHIRPath invariant validation.
4156
+ *
4157
+ * When `true`, constraint expressions from the profile are not
4158
+ * evaluated. Useful for performance or when FHIRPath evaluation
4159
+ * is not needed.
4160
+ *
4161
+ * @default false
4162
+ */
4163
+ readonly skipInvariants?: boolean;
4164
+ }
4165
+
4166
+ /**
4167
+ * Result of structural validation.
4168
+ *
4169
+ * Contains the overall validity status, the validated resource, and
4170
+ * all issues encountered during validation.
4171
+ *
4172
+ * @example
4173
+ * ```typescript
4174
+ * const result = await validator.validate(patient);
4175
+ * if (result.valid) {
4176
+ * console.log('Resource is valid');
4177
+ * } else {
4178
+ * for (const issue of result.issues) {
4179
+ * console.error(`${issue.severity}: ${issue.message} (at ${issue.path})`);
4180
+ * }
4181
+ * }
4182
+ * ```
4183
+ */
4184
+ export declare interface ValidationResult {
4185
+ /**
4186
+ * Whether the resource is valid.
4187
+ *
4188
+ * `true` when no error-severity issues were recorded.
4189
+ * Warnings and informational issues do not affect this flag.
4190
+ */
4191
+ readonly valid: boolean;
4192
+ /** The resource that was validated. */
4193
+ readonly resource: Resource;
4194
+ /** The profile that was validated against. */
4195
+ readonly profileUrl: string;
4196
+ /** The resolved CanonicalProfile used for validation. */
4197
+ readonly profile: CanonicalProfile;
4198
+ /** Issues encountered during validation (errors + warnings + info). */
4199
+ readonly issues: readonly ValidationIssue[];
4200
+ }
4201
+
4202
+ /**
4203
+ * Base error class for all fhir-validator failures.
4204
+ *
4205
+ * Provides a stable `name` property and preserves the original `cause`
4206
+ * when wrapping lower-level errors.
4207
+ *
4208
+ * @example
4209
+ * ```typescript
4210
+ * try {
4211
+ * await validator.validate(resource);
4212
+ * } catch (err) {
4213
+ * if (err instanceof ValidatorError) {
4214
+ * // Handle any validator-related error
4215
+ * }
4216
+ * }
4217
+ * ```
4218
+ */
4219
+ declare class ValidatorError extends Error {
4220
+ readonly name: string;
4221
+ constructor(message: string, options?: ErrorOptions);
4222
+ }
4223
+
4224
+ export { }