@aehrc/ecl-core 1.1.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -8,6 +8,14 @@ declare interface ASTNode {
8
8
  range: Range;
9
9
  }
10
10
 
11
+ /** An attribute group — `{ ... }`, optionally preceded by a cardinality like `[1..2]`. */
12
+ export declare interface AttributeGroupNode extends ASTNode {
13
+ type: NodeType.AttributeGroup;
14
+ /** Raw cardinality text including brackets, e.g. `[0..1]`. */
15
+ cardinality?: string;
16
+ content: RefinementMemberNode;
17
+ }
18
+
11
19
  declare interface AttributeInfo {
12
20
  nameEcl: string;
13
21
  nameRange: Range;
@@ -30,6 +38,31 @@ export declare interface AttributeNode extends ASTNode {
30
38
  name: AttributeNameNode;
31
39
  value: AttributeValueNode;
32
40
  reversed?: boolean;
41
+ /** Raw cardinality text including brackets, e.g. `[0..1]`. */
42
+ cardinality?: string;
43
+ }
44
+
45
+ /**
46
+ * A conjunction (`,` or `AND`) or disjunction (`OR`) of refinement members.
47
+ *
48
+ * The ECL grammar forbids mixing conjunction and disjunction at the same level,
49
+ * so every set is homogeneous; mixed expressions nest sets inside one another
50
+ * via parentheses.
51
+ */
52
+ export declare interface AttributeSetNode extends ASTNode {
53
+ type: NodeType.AttributeSet;
54
+ operator: 'AND' | 'OR';
55
+ /** How a conjunction was written in the source. Always ',' for disjunctions. */
56
+ conjunctionStyle: ',' | 'AND';
57
+ /**
58
+ * True when the source wrote this set inside `( )`.
59
+ *
60
+ * The grammar nests attribute sets inside refinements even without
61
+ * parentheses, so this distinguishes real source parentheses from the
62
+ * implicit nesting a parser introduces.
63
+ */
64
+ parenthesized?: boolean;
65
+ members: RefinementMemberNode[];
33
66
  }
34
67
 
35
68
  declare interface AttributeValueNode extends ASTNode {
@@ -258,6 +291,16 @@ declare interface DottedExpressionNode extends ASTNode {
258
291
  attributes: DottedAttributeNode[];
259
292
  }
260
293
 
294
+ /**
295
+ * How {@link FhirTerminologyService.evaluateEcl} carries the ECL to the terminology server.
296
+ *
297
+ * - `'auto'` (default) — try the implicit ValueSet URL `GET` first and fall back to
298
+ * `POST ValueSet/$expand` when the server shows it cannot serve implicit ValueSets.
299
+ * - `'implicit-url'` — only ever use the implicit ValueSet URL `GET`.
300
+ * - `'post'` — always `POST ValueSet/$expand` with a `constraint` filter.
301
+ */
302
+ export declare type EclEvaluationStrategy = 'auto' | 'implicit-url' | 'post';
303
+
261
304
  /**
262
305
  * ECL snippet completions for common expression patterns.
263
306
  * These are offered when the cursor is between expressions or at the
@@ -393,8 +436,24 @@ export declare class FhirTerminologyService implements ITerminologyService {
393
436
  private readonly searchTimeout;
394
437
  private readonly searchCacheTTL;
395
438
  private readonly snomedVersion;
439
+ private readonly evaluationStrategy;
396
440
  private readonly onResolvedVersion;
397
441
  private resolvedVersion;
442
+ /**
443
+ * Latched once a POST `ValueSet/$expand` fallback has succeeded in `'auto'` mode: the
444
+ * server has demonstrated it cannot serve the implicit ValueSet URL form, so subsequent
445
+ * evaluations skip the wasted round-trip for the lifetime of this instance.
446
+ */
447
+ private usePostExpand;
448
+ /**
449
+ * Latched once a bulk `ValueSet/$expand` has been rejected with a 4xx: the server does
450
+ * not accept a POSTed ValueSet enumerating concepts in `compose.include.concept`, and
451
+ * the request shape never varies, so retrying it on every validation pass only costs a
452
+ * wasted round-trip and a console warning (issue #55). 5xx responses are treated as
453
+ * transient and do not latch.
454
+ */
455
+ private bulkExpandUnsupported;
456
+ private readonly queue;
398
457
  constructor(options?: FhirTerminologyServiceOptions);
399
458
  /** The SNOMED CT system URL base for implicit ValueSet URLs. */
400
459
  private get snomedSystemUrl();
@@ -419,17 +478,112 @@ export declare class FhirTerminologyService implements ITerminologyService {
419
478
  */
420
479
  private parseSnomedVersionValue;
421
480
  private fetchWithTimeout;
481
+ /**
482
+ * Perform a request, translating any network-level failure (connection
483
+ * refused, DNS failure, timeout/abort) into a {@link TerminologyTransportError}
484
+ * so callers can tell "server unreachable" from "server said no".
485
+ */
486
+ private request;
487
+ /** Read the body of an error response, extracting a FHIR OperationOutcome if present. */
488
+ private static readErrorBody;
489
+ /** Issue codes a FHIR server uses to say "this code is not in the code system". */
490
+ private static readonly UNKNOWN_CODE_ISSUE_CODES;
491
+ /** Phrases servers use in OperationOutcome prose when a code is unknown. */
492
+ private static readonly UNKNOWN_CODE_PHRASES;
493
+ /**
494
+ * True when an error response is the server's well-formed way of saying
495
+ * "I do not know this code" — the one case that maps to `null` rather than
496
+ * an exception.
497
+ *
498
+ * A 404 is only accepted as such when the body is a real FHIR
499
+ * OperationOutcome; a bare 404 (wrong base URL, proxy page) is a fault.
500
+ */
501
+ private static isUnknownCodeResponse;
502
+ /**
503
+ * Look up a single concept.
504
+ *
505
+ * @returns the concept, or `null` when the terminology server gave a
506
+ * well-formed answer saying the code is unknown to it.
507
+ * @throws {TerminologyTransportError} when the server could not be reached,
508
+ * the request timed out, or the response body was unusable.
509
+ * @throws {TerminologyHttpError} when the server answered with an error
510
+ * status that is not an "unknown code" response.
511
+ */
512
+ private fetchWithRetry;
513
+ private fetchQueued;
422
514
  getConceptInfo(conceptId: string): Promise<ConceptInfo | null>;
423
515
  /** Map of SNOMED CT historical association reference set IDs to association types. */
424
516
  private static readonly ASSOCIATION_REFSETS;
425
517
  getHistoricalAssociations(conceptId: string): Promise<HistoricalAssociation[]>;
426
518
  /** Query a single implicit ConceptMap for historical association targets. */
427
519
  private translateAssociation;
520
+ /**
521
+ * Validate a batch of concepts.
522
+ *
523
+ * A `null` map value means the terminology server positively reported the
524
+ * code as unknown. Failures are never reported as `null` — they reject.
525
+ *
526
+ * @throws {TerminologyTransportError} when the server could not be reached.
527
+ * @throws {TerminologyHttpError} when the server answered with an error status.
528
+ */
428
529
  validateConcepts(conceptIds: string[]): Promise<Map<string, ConceptInfo | null>>;
530
+ /**
531
+ * Move concepts found in a bulk expansion into `results` (and the cache),
532
+ * returning the IDs that were absent and still need an individual lookup.
533
+ */
534
+ private mergeExpandResults;
535
+ /**
536
+ * Move already-cached concepts into `results`, returning the IDs still to fetch.
537
+ */
538
+ private partitionCached;
539
+ /** Look each concept up individually, recording the result (or `null` if absent). */
540
+ private lookupEach;
429
541
  private bulkExpand;
542
+ /**
543
+ * Search for concepts by text or SCTID.
544
+ *
545
+ * An empty result set means the server found no matches.
546
+ *
547
+ * @throws {TerminologyTransportError} when the server could not be reached.
548
+ * @throws {TerminologyHttpError} when the server answered with an error status.
549
+ */
430
550
  searchConcepts(query: string): Promise<SearchResponse>;
431
551
  private lookupById;
432
552
  evaluateEcl(expression: string, limit?: number): Promise<EvaluationResponse>;
553
+ /**
554
+ * Transport selection for {@link evaluateEcl}.
555
+ *
556
+ * A forced `'post'` strategy — or a latched successful POST fallback — goes straight to
557
+ * `POST ValueSet/$expand`. Otherwise the implicit ValueSet URL GET runs first, and in
558
+ * `'auto'` mode a failure whose *shape* says the server cannot serve implicit ValueSets
559
+ * (issue #55) is retried over POST.
560
+ */
561
+ private runEvaluationStrategy;
562
+ /** `GET ValueSet/$expand?url=<canonical implicit ECL ValueSet>` — see {@link encodeEclForCanonicalUrl}. */
563
+ private buildImplicitEvaluationUrl;
564
+ /**
565
+ * `POST ValueSet/$expand` carrying the ECL in `compose.include.filter` with
566
+ * `property: "constraint"` — the form requested in issue #55. The expression travels in a
567
+ * JSON body, so it needs no escaping at all.
568
+ */
569
+ private evaluateViaPostExpand;
570
+ /**
571
+ * True when an implicit-URL failure indicates the implicit ValueSet *form* is unsupported
572
+ * rather than the expression being invalid.
573
+ *
574
+ * Deliberately excludes a bare HTTP 422: that is also how a genuine ECL syntax error
575
+ * presents, and retrying those over POST would only turn one clear error into two requests
576
+ * and a muddled message. The `'not-found'` OperationOutcome code is still honoured on any
577
+ * status, which covers servers that report a missing implicit ValueSet as 422.
578
+ */
579
+ private shouldFallbackToPostExpand;
580
+ /** Remaining milliseconds in the shared evaluation budget; throws once it is spent. */
581
+ private remainingTimeout;
582
+ /** The machine-readable code and human-readable text of a FHIR error response. */
583
+ private readOperationOutcome;
584
+ /** Shared expansion mapping for both the implicit-URL and POST evaluation transports. */
585
+ private parseEvaluationResponse;
586
+ private createEvaluationError;
433
587
  private searchByFilter;
434
588
  /** Fetch available SNOMED CT editions and versions from the FHIR server. */
435
589
  getSnomedEditions(): Promise<SnomedEdition[]>;
@@ -440,7 +594,10 @@ export declare interface FhirTerminologyServiceOptions {
440
594
  timeout?: number;
441
595
  userAgent?: string;
442
596
  snomedVersion?: string;
597
+ /** ECL evaluation transport; defaults to `'auto'`. See {@link EclEvaluationStrategy}. */
598
+ evaluationStrategy?: EclEvaluationStrategy;
443
599
  onResolvedVersion?: (versionUri: string) => void;
600
+ maxConcurrency?: number;
444
601
  }
445
602
 
446
603
  export declare interface FilterConstraintNode extends ASTNode {
@@ -473,6 +630,15 @@ export declare function formatRangeExpressions(expressions: {
473
630
  export declare interface FormattingOptions {
474
631
  indentSize: number;
475
632
  indentStyle: 'space' | 'tab';
633
+ /**
634
+ * Accepted for backwards compatibility, but has no effect.
635
+ *
636
+ * It only ever applied to the AND, OR and MINUS keywords, and the ECL grammar
637
+ * requires mandatory whitespace around those. Setting it to `false` produced
638
+ * output that no longer parsed (`< 404684003AND< 19829001`), so keyword
639
+ * operators now always keep their spaces. Constraint operators (`<`, `<<`,
640
+ * `^`) were never affected by this option.
641
+ */
476
642
  spaceAroundOperators: boolean;
477
643
  maxLineLength: number;
478
644
  alignTerms: boolean;
@@ -642,6 +808,23 @@ export declare interface HistorySupplementNode extends ASTNode {
642
808
  */
643
809
  export declare function isConceptPositionValid(line: string, cursorPosition: number): boolean;
644
810
 
811
+ /** Type guard for {@link EclEvaluationStrategy} (unknown values degrade to `'auto'`). */
812
+ export declare function isEclEvaluationStrategy(value: unknown): value is EclEvaluationStrategy;
813
+
814
+ /**
815
+ * True when `value` is a terminology failure.
816
+ *
817
+ * Checks structurally as well as by `instanceof`, so it still works when a dual
818
+ * CJS/ESM build loads two copies of this module.
819
+ */
820
+ export declare function isTerminologyError(value: unknown): value is TerminologyError;
821
+
822
+ /** True when `value` is an HTTP error response from the terminology server. */
823
+ export declare function isTerminologyHttpError(value: unknown): value is TerminologyHttpError;
824
+
825
+ /** True when `value` is a transport failure — the server was not reached. */
826
+ export declare function isTerminologyTransportError(value: unknown): value is TerminologyTransportError;
827
+
645
828
  /**
646
829
  * Validates that a SNOMED CT identifier is a concept ID.
647
830
  *
@@ -675,11 +858,49 @@ export declare function isValidDescriptionId(sctid: string): boolean;
675
858
  */
676
859
  export declare function isValidSnomedId(conceptId: string): boolean;
677
860
 
861
+ /**
862
+ * A source of SNOMED CT terminology facts.
863
+ *
864
+ * **Failure contract.** Implementations MUST distinguish "the server told me
865
+ * this concept does not exist" from "I could not ask the server". A `null`
866
+ * result is a factual claim about SNOMED CT content and is only permitted for
867
+ * the former; every failure — connection refused, DNS failure, timeout, HTTP
868
+ * error status, unreadable body — MUST reject with a `TerminologyError`
869
+ * (`TerminologyTransportError` or `TerminologyHttpError`), so that callers can
870
+ * classify it structurally via its `kind` discriminant and `status`, rather
871
+ * than rendering an outage as "concept not found".
872
+ */
678
873
  export declare interface ITerminologyService {
874
+ /**
875
+ * Look up a single concept.
876
+ *
877
+ * @returns the concept, or `null` ONLY when the terminology server gave a
878
+ * well-formed answer saying the code is unknown to it.
879
+ * @throws `TerminologyTransportError` when the server could not be reached,
880
+ * the request timed out, or the response was unusable.
881
+ * @throws `TerminologyHttpError` when the server answered with an error status.
882
+ */
679
883
  getConceptInfo(conceptId: string): Promise<ConceptInfo | null>;
884
+ /**
885
+ * Validate a batch of concepts.
886
+ *
887
+ * @returns a map from concept ID to its info, or to `null` ONLY when the
888
+ * server positively reported that code as unknown.
889
+ * @throws `TerminologyTransportError` / `TerminologyHttpError` on failure —
890
+ * never a map full of `null`s.
891
+ */
680
892
  validateConcepts(conceptIds: string[]): Promise<Map<string, ConceptInfo | null>>;
893
+ /**
894
+ * Search for concepts by text or SCTID.
895
+ *
896
+ * @returns matches; an empty result set means the server found none.
897
+ * @throws `TerminologyTransportError` / `TerminologyHttpError` on failure —
898
+ * never an empty result set, and never an opaque generic `Error`.
899
+ */
681
900
  searchConcepts(query: string): Promise<SearchResponse>;
901
+ /** Expand an ECL expression. Throws on failure. */
682
902
  evaluateEcl(expression: string, limit?: number): Promise<EvaluationResponse>;
903
+ /** Historical associations for an inactive concept, if the source supports them. */
683
904
  getHistoricalAssociations?(conceptId: string): Promise<HistoricalAssociation[]>;
684
905
  }
685
906
 
@@ -738,6 +959,8 @@ declare enum NodeType {
738
959
  ConstraintOperator = "ConstraintOperator",
739
960
  LogicalOperator = "LogicalOperator",
740
961
  Refinement = "Refinement",
962
+ AttributeSet = "AttributeSet",
963
+ AttributeGroup = "AttributeGroup",
741
964
  Attribute = "Attribute",
742
965
  AttributeName = "AttributeName",
743
966
  AttributeValue = "AttributeValue",
@@ -858,9 +1081,28 @@ declare interface RefinementInfo {
858
1081
  attributes: AttributeInfo[];
859
1082
  }
860
1083
 
861
- declare interface RefinementNode extends ASTNode {
1084
+ /**
1085
+ * A member of a refinement tree: a single attribute, a `{ }` attribute group,
1086
+ * or a conjunction/disjunction set of members.
1087
+ */
1088
+ export declare type RefinementMemberNode = AttributeNode | AttributeGroupNode | AttributeSetNode;
1089
+
1090
+ export declare interface RefinementNode extends ASTNode {
862
1091
  type: NodeType.Refinement;
1092
+ /**
1093
+ * Every attribute in the refinement, in source order.
1094
+ *
1095
+ * This is a flattened convenience view that carries NO operator or grouping
1096
+ * information — use `content` when the distinction between `,`/`AND`
1097
+ * (conjunction) and `OR` (disjunction) matters, e.g. when printing.
1098
+ */
863
1099
  attributes: AttributeNode[];
1100
+ /**
1101
+ * The refinement tree, preserving the conjunction/disjunction operators and
1102
+ * the grouping (parentheses and `{ }` attribute groups) written in the source.
1103
+ * `null` only when the refinement contains no attributes at all.
1104
+ */
1105
+ content: RefinementMemberNode | null;
864
1106
  }
865
1107
 
866
1108
  declare interface RefinementWarning {
@@ -940,12 +1182,128 @@ export declare interface SubExpressionNode extends ASTNode {
940
1182
  historySupplement?: HistorySupplementNode;
941
1183
  }
942
1184
 
1185
+ /**
1186
+ * Base class for terminology server failures.
1187
+ *
1188
+ * Never thrown directly — use {@link TerminologyTransportError} or
1189
+ * {@link TerminologyHttpError}, and discriminate on {@link kind}.
1190
+ */
1191
+ export declare abstract class TerminologyError extends Error {
1192
+ /** Discriminant identifying the class of failure. */
1193
+ abstract readonly kind: TerminologyErrorKind;
1194
+ /**
1195
+ * The underlying failure.
1196
+ *
1197
+ * Declared explicitly (rather than relying on `Error.cause`) so it is part of
1198
+ * the emitted type declarations and is present on every runtime.
1199
+ */
1200
+ readonly cause: unknown;
1201
+ /** The request URL, when known. */
1202
+ readonly url: string | undefined;
1203
+ /** The HTTP status, present only on {@link TerminologyHttpError}. */
1204
+ readonly status: number | undefined;
1205
+ protected constructor(message: string, options?: TerminologyErrorOptions & {
1206
+ status?: number;
1207
+ });
1208
+ }
1209
+
1210
+ /**
1211
+ * Typed errors for terminology server failures.
1212
+ *
1213
+ * A failure to reach a terminology server is NOT a statement about SNOMED CT.
1214
+ * These types let callers tell the two apart structurally — by the `kind`
1215
+ * discriminant and the HTTP `status` — instead of parsing prose, so a socket
1216
+ * error is never rendered to a user (or an LLM) as "concept not found".
1217
+ */
1218
+ /**
1219
+ * What went wrong.
1220
+ *
1221
+ * - `transport` — the request never produced an HTTP response: connection
1222
+ * refused, DNS failure, TLS failure, timeout/abort, or an unreadable body.
1223
+ * - `http` — the server answered, but with an error status.
1224
+ */
1225
+ export declare type TerminologyErrorKind = 'transport' | 'http';
1226
+
1227
+ /** Options common to all terminology errors. */
1228
+ export declare interface TerminologyErrorOptions {
1229
+ /** The underlying failure (network error, abort error, parse error). */
1230
+ cause?: unknown;
1231
+ /** The request URL, when known. */
1232
+ url?: string;
1233
+ }
1234
+
1235
+ /**
1236
+ * The terminology server answered with an error status.
1237
+ *
1238
+ * An error status is a statement about the request or the server, not about
1239
+ * SNOMED CT content — with the sole exception of a well-formed "unknown code"
1240
+ * response, which the service converts into `null` rather than an error.
1241
+ */
1242
+ export declare class TerminologyHttpError extends TerminologyError {
1243
+ readonly kind: "http";
1244
+ /** The HTTP status returned by the server. Always present. */
1245
+ readonly status: number;
1246
+ /** The HTTP reason phrase, when the client exposes one. */
1247
+ readonly statusText: string | undefined;
1248
+ constructor(message: string, options: TerminologyHttpErrorOptions);
1249
+ }
1250
+
1251
+ /** Options for {@link TerminologyHttpError}. */
1252
+ export declare interface TerminologyHttpErrorOptions extends TerminologyErrorOptions {
1253
+ /** The HTTP status returned by the terminology server. */
1254
+ status: number;
1255
+ /** The HTTP reason phrase, when the client exposes one. */
1256
+ statusText?: string;
1257
+ }
1258
+
1259
+ /**
1260
+ * The terminology server could not be reached, or produced no usable response.
1261
+ *
1262
+ * There is no HTTP status: the request never completed. Callers must treat this
1263
+ * as "unknown" — never as evidence that a concept is absent.
1264
+ */
1265
+ export declare class TerminologyTransportError extends TerminologyError {
1266
+ readonly kind: "transport";
1267
+ /** True when the failure was a client-side timeout rather than a hard failure. */
1268
+ readonly timedOut: boolean;
1269
+ constructor(message: string, options?: TerminologyTransportErrorOptions);
1270
+ }
1271
+
1272
+ /** Options for {@link TerminologyTransportError}. */
1273
+ export declare interface TerminologyTransportErrorOptions extends TerminologyErrorOptions {
1274
+ /** True when the request was aborted because it exceeded its timeout. */
1275
+ timedOut?: boolean;
1276
+ }
1277
+
1278
+ /**
1279
+ * Build a {@link TerminologyHttpError} for an error response, keeping any
1280
+ * detail the server supplied (e.g. an OperationOutcome diagnostic).
1281
+ */
1282
+ export declare function toHttpError(options: {
1283
+ status: number;
1284
+ statusText?: string;
1285
+ url?: string;
1286
+ operation: string;
1287
+ detail?: string;
1288
+ cause?: unknown;
1289
+ }): TerminologyHttpError;
1290
+
943
1291
  declare interface TokenInfo {
944
1292
  type: number;
945
1293
  text: string;
946
1294
  range: Range;
947
1295
  }
948
1296
 
1297
+ /**
1298
+ * Wrap a network-level failure as a {@link TerminologyTransportError},
1299
+ * preserving the original as `cause`.
1300
+ */
1301
+ export declare function toTransportError(error: unknown, options: {
1302
+ url?: string;
1303
+ operation: string;
1304
+ timeoutMs?: number;
1305
+ }): TerminologyTransportError;
1306
+
949
1307
  export declare function validateBoolean(value: unknown, defaultValue: boolean): boolean;
950
1308
 
951
1309
  export declare function validateIndentSize(value: unknown): number;