@aehrc/ecl-core 1.1.1 → 1.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.
package/dist/index.mjs CHANGED
@@ -25674,6 +25674,7 @@ function requireAntlr4ts() {
25674
25674
  return antlr4ts;
25675
25675
  }
25676
25676
  var antlr4tsExports = requireAntlr4ts();
25677
+ var PredictionModeExports = requirePredictionMode();
25677
25678
  var ATNDeserializerExports = requireATNDeserializer();
25678
25679
  var LexerExports = requireLexer();
25679
25680
  var LexerATNSimulatorExports = requireLexerATNSimulator();
@@ -50915,6 +50916,8 @@ var NodeType = /* @__PURE__ */ ((NodeType2) => {
50915
50916
  NodeType2["ConstraintOperator"] = "ConstraintOperator";
50916
50917
  NodeType2["LogicalOperator"] = "LogicalOperator";
50917
50918
  NodeType2["Refinement"] = "Refinement";
50919
+ NodeType2["AttributeSet"] = "AttributeSet";
50920
+ NodeType2["AttributeGroup"] = "AttributeGroup";
50918
50921
  NodeType2["Attribute"] = "Attribute";
50919
50922
  NodeType2["AttributeName"] = "AttributeName";
50920
50923
  NodeType2["AttributeValue"] = "AttributeValue";
@@ -51109,76 +51112,106 @@ class ECLASTVisitor extends AbstractParseTreeVisitorExports.AbstractParseTreeVis
51109
51112
  };
51110
51113
  }
51111
51114
  visitEclrefinement(ctx) {
51115
+ const content = this.buildRefinement(ctx);
51112
51116
  const attributes = [];
51113
- this.collectAttributesFromSubrefinement(ctx.subrefinement(), attributes);
51117
+ collectAttributes$1(content, attributes);
51118
+ return {
51119
+ type: NodeType.Refinement,
51120
+ range: this.getRange(ctx),
51121
+ attributes,
51122
+ content
51123
+ };
51124
+ }
51125
+ /**
51126
+ * eclrefinement : subrefinement ws (conjunctionrefinementset | disjunctionrefinementset)?
51127
+ *
51128
+ * The grammar forbids mixing conjunction and disjunction at the same level, so
51129
+ * at most one of the two sets is present and the resulting set is homogeneous.
51130
+ */
51131
+ buildRefinement(ctx) {
51132
+ const first = this.buildSubrefinement(ctx.subrefinement());
51114
51133
  const conjSet = ctx.conjunctionrefinementset();
51115
51134
  if (conjSet) {
51116
- const subs = conjSet.subrefinement();
51117
- for (const sub of subs) {
51118
- this.collectAttributesFromSubrefinement(sub, attributes);
51119
- }
51135
+ const rest = conjSet.subrefinement().map((sub) => this.buildSubrefinement(sub));
51136
+ return this.makeSet(ctx, "AND", conjunctionStyle(conjSet.conjunction()), [first, ...rest]);
51120
51137
  }
51121
51138
  const disjSet = ctx.disjunctionrefinementset();
51122
51139
  if (disjSet) {
51123
- const subs = disjSet.subrefinement();
51124
- for (const sub of subs) {
51125
- this.collectAttributesFromSubrefinement(sub, attributes);
51126
- }
51140
+ const rest = disjSet.subrefinement().map((sub) => this.buildSubrefinement(sub));
51141
+ return this.makeSet(ctx, "OR", ",", [first, ...rest]);
51127
51142
  }
51128
- return {
51129
- type: NodeType.Refinement,
51130
- range: this.getRange(ctx),
51131
- attributes
51132
- };
51143
+ return first;
51133
51144
  }
51134
- collectAttributesFromSubrefinement(ctx, attributes) {
51145
+ /** subrefinement : eclattributeset | eclattributegroup | ( eclrefinement ) */
51146
+ buildSubrefinement(ctx) {
51135
51147
  const attrSet = ctx.eclattributeset();
51136
51148
  if (attrSet) {
51137
- this.collectAttributesFromAttributeSet(attrSet, attributes);
51138
- return;
51149
+ return this.buildAttributeSet(attrSet);
51139
51150
  }
51140
51151
  const attrGroup = ctx.eclattributegroup();
51141
51152
  if (attrGroup) {
51142
- const groupAttrSet = attrGroup.eclattributeset();
51143
- this.collectAttributesFromAttributeSet(groupAttrSet, attributes);
51144
- return;
51153
+ const content = this.buildAttributeSet(attrGroup.eclattributeset());
51154
+ if (!content) {
51155
+ return null;
51156
+ }
51157
+ const cardinality = attrGroup.cardinality();
51158
+ const group = {
51159
+ type: NodeType.AttributeGroup,
51160
+ range: this.getRange(ctx),
51161
+ content
51162
+ };
51163
+ if (cardinality) {
51164
+ group.cardinality = "[" + cardinality.text + "]";
51165
+ }
51166
+ return group;
51145
51167
  }
51146
51168
  const nestedRef = ctx.eclrefinement();
51147
- if (nestedRef) {
51148
- const nested = this.visitEclrefinement(nestedRef);
51149
- attributes.push(...nested.attributes);
51150
- }
51169
+ return nestedRef ? markParenthesized(this.buildRefinement(nestedRef)) : null;
51151
51170
  }
51152
- collectAttributesFromAttributeSet(ctx, attributes) {
51153
- this.collectAttributeFromSubattributeset(ctx.subattributeset(), attributes);
51171
+ /** eclattributeset : subattributeset ws (conjunctionattributeset | disjunctionattributeset)? */
51172
+ buildAttributeSet(ctx) {
51173
+ const first = this.buildSubattributeSet(ctx.subattributeset());
51154
51174
  const conjSet = ctx.conjunctionattributeset();
51155
51175
  if (conjSet) {
51156
- const subs = conjSet.subattributeset();
51157
- for (const sub of subs) {
51158
- this.collectAttributeFromSubattributeset(sub, attributes);
51159
- }
51176
+ const rest = conjSet.subattributeset().map((sub) => this.buildSubattributeSet(sub));
51177
+ return this.makeSet(ctx, "AND", conjunctionStyle(conjSet.conjunction()), [first, ...rest]);
51160
51178
  }
51161
51179
  const disjSet = ctx.disjunctionattributeset();
51162
51180
  if (disjSet) {
51163
- const subs = disjSet.subattributeset();
51164
- for (const sub of subs) {
51165
- this.collectAttributeFromSubattributeset(sub, attributes);
51166
- }
51181
+ const rest = disjSet.subattributeset().map((sub) => this.buildSubattributeSet(sub));
51182
+ return this.makeSet(ctx, "OR", ",", [first, ...rest]);
51167
51183
  }
51184
+ return first;
51168
51185
  }
51169
- collectAttributeFromSubattributeset(ctx, attributes) {
51186
+ /** subattributeset : eclattribute | ( eclattributeset ) */
51187
+ buildSubattributeSet(ctx) {
51170
51188
  const attr = ctx.eclattribute();
51171
51189
  if (attr) {
51172
- const attrNode = this.visitEclattribute(attr);
51173
- if (attrNode) {
51174
- attributes.push(attrNode);
51175
- }
51176
- return;
51190
+ return this.visitEclattribute(attr);
51177
51191
  }
51178
51192
  const nestedSet = ctx.eclattributeset();
51179
- if (nestedSet) {
51180
- this.collectAttributesFromAttributeSet(nestedSet, attributes);
51193
+ return nestedSet ? markParenthesized(this.buildAttributeSet(nestedSet)) : null;
51194
+ }
51195
+ /**
51196
+ * Build a set node from its members, dropping members that failed to parse.
51197
+ * Collapses to the single member when only one survives, so a set node always
51198
+ * represents a real operator in the source.
51199
+ */
51200
+ makeSet(ctx, operator, style, members) {
51201
+ const present = members.filter((m) => m !== null);
51202
+ if (present.length === 0) {
51203
+ return null;
51181
51204
  }
51205
+ if (present.length === 1) {
51206
+ return present[0];
51207
+ }
51208
+ return {
51209
+ type: NodeType.AttributeSet,
51210
+ range: this.getRange(ctx),
51211
+ operator,
51212
+ conjunctionStyle: operator === "AND" ? style : ",",
51213
+ members: present
51214
+ };
51182
51215
  }
51183
51216
  // eslint-disable-next-line sonarjs/cognitive-complexity -- ANTLR visitor with multiple grammar rule branches
51184
51217
  visitEclattribute(ctx) {
@@ -51241,12 +51274,14 @@ class ECLASTVisitor extends AbstractParseTreeVisitorExports.AbstractParseTreeVis
51241
51274
  rawValue: ctx.text
51242
51275
  };
51243
51276
  }
51277
+ const cardinalityCtx = ctx.cardinality();
51244
51278
  return {
51245
51279
  type: NodeType.Attribute,
51246
51280
  range: this.getRange(ctx),
51247
51281
  name: attrName,
51248
51282
  value,
51249
- reversed
51283
+ reversed,
51284
+ cardinality: cardinalityCtx ? "[" + cardinalityCtx.text + "]" : void 0
51250
51285
  };
51251
51286
  }
51252
51287
  // Dotted expressions
@@ -51449,6 +51484,28 @@ class ECLASTVisitor extends AbstractParseTreeVisitorExports.AbstractParseTreeVis
51449
51484
  }
51450
51485
  }
51451
51486
  }
51487
+ function conjunctionStyle(conjunctions) {
51488
+ return conjunctions.some((c) => !c.text.trimStart().startsWith(",")) ? "AND" : ",";
51489
+ }
51490
+ function collectAttributes$1(node, out) {
51491
+ if (!node) return;
51492
+ switch (node.type) {
51493
+ case NodeType.Attribute:
51494
+ out.push(node);
51495
+ break;
51496
+ case NodeType.AttributeGroup:
51497
+ collectAttributes$1(node.content, out);
51498
+ break;
51499
+ case NodeType.AttributeSet:
51500
+ for (const member of node.members) {
51501
+ collectAttributes$1(member, out);
51502
+ }
51503
+ break;
51504
+ }
51505
+ }
51506
+ function markParenthesized(node) {
51507
+ return (node == null ? void 0 : node.type) === NodeType.AttributeSet ? { ...node, parenthesized: true } : node;
51508
+ }
51452
51509
  class ECLErrorListener {
51453
51510
  constructor() {
51454
51511
  __publicField(this, "errors", []);
@@ -51814,34 +51871,12 @@ function computeColumn(text, i, baseColumn) {
51814
51871
  }
51815
51872
  let lastInput = null;
51816
51873
  let lastResult = null;
51817
- function parseECL(input) {
51818
- if (input === lastInput && lastResult !== null) {
51819
- return lastResult;
51820
- }
51874
+ function runParseAttempt(input, predictionMode) {
51821
51875
  const inputStream = new antlr4tsExports.ANTLRInputStream(input);
51822
51876
  const lexer = new ECLLexer(inputStream);
51823
51877
  const tokenStream = new antlr4tsExports.CommonTokenStream(lexer);
51824
- tokenStream.fill();
51825
- const tokens = tokenStream.getTokens().map((token) => {
51826
- var _a;
51827
- return {
51828
- type: token.type,
51829
- text: token.text ?? "",
51830
- range: {
51831
- start: {
51832
- line: token.line,
51833
- column: token.charPositionInLine,
51834
- offset: token.startIndex
51835
- },
51836
- end: {
51837
- line: token.line,
51838
- column: token.charPositionInLine + (((_a = token.text) == null ? void 0 : _a.length) ?? 0),
51839
- offset: token.stopIndex + 1
51840
- }
51841
- }
51842
- };
51843
- });
51844
51878
  const parser = new ECLParser(tokenStream);
51879
+ parser.interpreter.setPredictionMode(predictionMode);
51845
51880
  const errorListener = new ECLErrorListener();
51846
51881
  parser.removeErrorListeners();
51847
51882
  parser.addErrorListener(errorListener);
@@ -51866,7 +51901,44 @@ function parseECL(input) {
51866
51901
  }
51867
51902
  } catch {
51868
51903
  }
51869
- const existingErrors = errorListener.getErrors();
51904
+ return { ast, errors: errorListener.getErrors() };
51905
+ }
51906
+ function parseWithFallback(input) {
51907
+ const sll = runParseAttempt(input, PredictionModeExports.PredictionMode.SLL);
51908
+ if (sll.ast !== null && sll.errors.length === 0) {
51909
+ return sll;
51910
+ }
51911
+ return runParseAttempt(input, PredictionModeExports.PredictionMode.LL);
51912
+ }
51913
+ function parseECL(input) {
51914
+ if (input === lastInput && lastResult !== null) {
51915
+ return lastResult;
51916
+ }
51917
+ const tokenInputStream = new antlr4tsExports.ANTLRInputStream(input);
51918
+ const tokenLexer = new ECLLexer(tokenInputStream);
51919
+ const tokenStream = new antlr4tsExports.CommonTokenStream(tokenLexer);
51920
+ tokenStream.fill();
51921
+ const tokens = tokenStream.getTokens().map((token) => {
51922
+ var _a;
51923
+ return {
51924
+ type: token.type,
51925
+ text: token.text ?? "",
51926
+ range: {
51927
+ start: {
51928
+ line: token.line,
51929
+ column: token.charPositionInLine,
51930
+ offset: token.startIndex
51931
+ },
51932
+ end: {
51933
+ line: token.line,
51934
+ column: token.charPositionInLine + (((_a = token.text) == null ? void 0 : _a.length) ?? 0),
51935
+ offset: token.stopIndex + 1
51936
+ }
51937
+ }
51938
+ };
51939
+ });
51940
+ const { ast, errors: parseErrors } = parseWithFallback(input);
51941
+ const existingErrors = parseErrors;
51870
51942
  if (existingErrors.length > 0) {
51871
51943
  const issues = analyzeExpression(input);
51872
51944
  if (issues.mixedOperator) {
@@ -51953,7 +52025,7 @@ function parseECL(input) {
51953
52025
  const warnings = ast ? checkMixedRefinementOperators(ast, input) : [];
51954
52026
  const result = {
51955
52027
  ast,
51956
- errors: errorListener.getErrors(),
52028
+ errors: parseErrors,
51957
52029
  warnings,
51958
52030
  tokens
51959
52031
  };
@@ -51966,6 +52038,7 @@ function extractConceptIds(ast, options) {
51966
52038
  const deduplicate = (options == null ? void 0 : options.deduplicate) ?? true;
51967
52039
  const seenIds = /* @__PURE__ */ new Set();
51968
52040
  function visitNode(node) {
52041
+ if (!node) return;
51969
52042
  switch (node.type) {
51970
52043
  case NodeType.ConceptReference:
51971
52044
  if (!deduplicate || !seenIds.has(node.conceptId)) {
@@ -51991,7 +52064,7 @@ function extractConceptIds(ast, options) {
51991
52064
  }
51992
52065
  break;
51993
52066
  case NodeType.ExpressionConstraint:
51994
- if (node.expression) visitNode(node.expression);
52067
+ visitNode(node.expression);
51995
52068
  break;
51996
52069
  case NodeType.SubExpressionConstraint:
51997
52070
  visitNode(node.focus);
@@ -52269,8 +52342,141 @@ function isValidDescriptionId(sctid) {
52269
52342
  const partitionId = sctid.substring(sctid.length - 3, sctid.length - 1);
52270
52343
  return partitionId === "01" || partitionId === "11";
52271
52344
  }
52345
+ class TerminologyError extends Error {
52346
+ constructor(message, options = {}) {
52347
+ super(message);
52348
+ /**
52349
+ * The underlying failure.
52350
+ *
52351
+ * Declared explicitly (rather than relying on `Error.cause`) so it is part of
52352
+ * the emitted type declarations and is present on every runtime.
52353
+ */
52354
+ __publicField(this, "cause");
52355
+ /** The request URL, when known. */
52356
+ __publicField(this, "url");
52357
+ /** The HTTP status, present only on {@link TerminologyHttpError}. */
52358
+ __publicField(this, "status");
52359
+ this.name = "TerminologyError";
52360
+ this.cause = options.cause;
52361
+ this.url = options.url;
52362
+ this.status = options.status;
52363
+ }
52364
+ }
52365
+ class TerminologyTransportError extends TerminologyError {
52366
+ constructor(message, options = {}) {
52367
+ super(message, options);
52368
+ __publicField(this, "kind", "transport");
52369
+ /** True when the failure was a client-side timeout rather than a hard failure. */
52370
+ __publicField(this, "timedOut");
52371
+ this.name = "TerminologyTransportError";
52372
+ this.timedOut = options.timedOut ?? false;
52373
+ }
52374
+ }
52375
+ class TerminologyHttpError extends TerminologyError {
52376
+ constructor(message, options) {
52377
+ super(message, options);
52378
+ __publicField(this, "kind", "http");
52379
+ /** The HTTP reason phrase, when the client exposes one. */
52380
+ __publicField(this, "statusText");
52381
+ this.name = "TerminologyHttpError";
52382
+ this.statusText = options.statusText;
52383
+ }
52384
+ }
52385
+ function isTerminologyError(value) {
52386
+ if (value instanceof TerminologyError) return true;
52387
+ if (!(value instanceof Error)) return false;
52388
+ const kind = value.kind;
52389
+ return value.name === "TerminologyTransportError" && kind === "transport" || value.name === "TerminologyHttpError" && kind === "http";
52390
+ }
52391
+ function isTerminologyTransportError(value) {
52392
+ return isTerminologyError(value) && value.kind === "transport";
52393
+ }
52394
+ function isTerminologyHttpError(value) {
52395
+ return isTerminologyError(value) && value.kind === "http";
52396
+ }
52397
+ function isAbortLike(error) {
52398
+ if (typeof error !== "object" || error === null) return false;
52399
+ const name = error.name;
52400
+ return name === "AbortError" || name === "TimeoutError";
52401
+ }
52402
+ function describe(error) {
52403
+ if (error instanceof Error) return error.message;
52404
+ return String(error);
52405
+ }
52406
+ function toTransportError(error, options) {
52407
+ if (isTerminologyTransportError(error)) return error;
52408
+ const timedOut = isAbortLike(error);
52409
+ const after = options.timeoutMs === void 0 ? "" : ` after ${options.timeoutMs}ms`;
52410
+ const reason = timedOut ? `timed out${after}` : `failed: ${describe(error)}`;
52411
+ return new TerminologyTransportError(`Could not reach the terminology server — ${options.operation} ${reason}`, {
52412
+ cause: error,
52413
+ url: options.url,
52414
+ timedOut
52415
+ });
52416
+ }
52417
+ function toHttpError(options) {
52418
+ const suffix = options.detail ? `: ${options.detail}` : "";
52419
+ return new TerminologyHttpError(
52420
+ `Terminology server returned HTTP ${options.status} for ${options.operation}${suffix}`,
52421
+ options
52422
+ );
52423
+ }
52272
52424
  const DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
52273
52425
  const IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
52426
+ function isEclEvaluationStrategy(value) {
52427
+ return value === "auto" || value === "implicit-url" || value === "post";
52428
+ }
52429
+ class ConcurrencyQueue {
52430
+ constructor(max2) {
52431
+ __publicField(this, "running", 0);
52432
+ __publicField(this, "waiters", []);
52433
+ this.max = max2;
52434
+ }
52435
+ run(fn) {
52436
+ return new Promise((resolve, reject) => {
52437
+ const attempt = () => {
52438
+ this.running++;
52439
+ fn().then(resolve, reject).finally(() => {
52440
+ this.running--;
52441
+ const next = this.waiters.shift();
52442
+ if (next) next();
52443
+ });
52444
+ };
52445
+ if (this.running < this.max) attempt();
52446
+ else this.waiters.push(attempt);
52447
+ });
52448
+ }
52449
+ }
52450
+ const RETRY_BASE_DELAY_MS = 500;
52451
+ const RETRY_MAX_DELAY_MS = 1e4;
52452
+ const RETRY_MAX_ATTEMPTS = 3;
52453
+ const RETRY_JITTER_MS = 200;
52454
+ const CANONICAL_URL_RESERVED = [
52455
+ ["|", "%7C"],
52456
+ // FHIR canonical `system|version` delimiter — the issue #68 corruption
52457
+ ["#", "%23"],
52458
+ // URL fragment delimiter; also introduces ECL concrete values such as `#20`
52459
+ ["&", "%26"],
52460
+ // separates parameters within the canonical URL's own query string
52461
+ ["+", "%2B"],
52462
+ // read as a space by form-style query decoders
52463
+ ["?", "%3F"]
52464
+ // query string introducer
52465
+ ];
52466
+ function encodeEclForCanonicalUrl(expression) {
52467
+ let encoded = expression.replaceAll("%", "%25");
52468
+ for (const [character, escape] of CANONICAL_URL_RESERVED) {
52469
+ encoded = encoded.replaceAll(character, escape);
52470
+ }
52471
+ return encoded;
52472
+ }
52473
+ const VALUE_SET_NOT_FOUND = /value\s*sets?\s*not\s*found/i;
52474
+ const IMPLICIT_VALUE_SET_UNSUPPORTED = [
52475
+ /implicit[^.]*value\s*sets?[^.]*not\s*supported/i,
52476
+ /not\s*supported[^.]*implicit[^.]*value\s*sets?/i
52477
+ ];
52478
+ class EvaluationIssueError extends Error {
52479
+ }
52274
52480
  const _FhirTerminologyService = class _FhirTerminologyService {
52275
52481
  constructor(options = {}) {
52276
52482
  __publicField(this, "cache", /* @__PURE__ */ new Map());
@@ -52283,9 +52489,28 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52283
52489
  __publicField(this, "searchCacheTTL");
52284
52490
  // milliseconds
52285
52491
  __publicField(this, "snomedVersion");
52492
+ __publicField(this, "evaluationStrategy");
52286
52493
  __publicField(this, "onResolvedVersion");
52287
52494
  __publicField(this, "resolvedVersion", null);
52495
+ /**
52496
+ * Latched once a POST `ValueSet/$expand` fallback has succeeded in `'auto'` mode: the
52497
+ * server has demonstrated it cannot serve the implicit ValueSet URL form, so subsequent
52498
+ * evaluations skip the wasted round-trip for the lifetime of this instance.
52499
+ */
52500
+ __publicField(this, "usePostExpand", false);
52501
+ /**
52502
+ * Latched once a bulk `ValueSet/$expand` has been rejected with a 4xx: the server does
52503
+ * not accept a POSTed ValueSet enumerating concepts in `compose.include.concept`, and
52504
+ * the request shape never varies, so retrying it on every validation pass only costs a
52505
+ * wasted round-trip and a console warning (issue #55). 5xx responses are treated as
52506
+ * transient and do not latch.
52507
+ */
52508
+ __publicField(this, "bulkExpandUnsupported", false);
52509
+ __publicField(this, "queue");
52288
52510
  var _a;
52511
+ const maxConcurrency = options.maxConcurrency ?? 25;
52512
+ if (maxConcurrency <= 0) throw new Error(`maxConcurrency must be > 0, got ${maxConcurrency}`);
52513
+ this.queue = new ConcurrencyQueue(maxConcurrency);
52289
52514
  this.baseUrl = options.baseUrl ?? "https://tx.ontoserver.csiro.au/fhir";
52290
52515
  this.timeout = options.timeout ?? 2e3;
52291
52516
  this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
@@ -52293,6 +52518,7 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52293
52518
  this.searchTimeout = 5e3;
52294
52519
  this.searchCacheTTL = 5 * 60 * 1e3;
52295
52520
  this.snomedVersion = ((_a = options.snomedVersion) == null ? void 0 : _a.trim()) ? options.snomedVersion.trim() : void 0;
52521
+ this.evaluationStrategy = isEclEvaluationStrategy(options.evaluationStrategy) ? options.evaluationStrategy : "auto";
52296
52522
  this.onResolvedVersion = options.onResolvedVersion;
52297
52523
  }
52298
52524
  /** The SNOMED CT system URL base for implicit ValueSet URLs. */
@@ -52379,53 +52605,150 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52379
52605
  clearTimeout(timeoutId);
52380
52606
  }
52381
52607
  }
52608
+ /**
52609
+ * Perform a request, translating any network-level failure (connection
52610
+ * refused, DNS failure, timeout/abort) into a {@link TerminologyTransportError}
52611
+ * so callers can tell "server unreachable" from "server said no".
52612
+ */
52613
+ async request(url, timeoutMs, operation, init) {
52614
+ try {
52615
+ return await this.fetchQueued(url, timeoutMs, init);
52616
+ } catch (error) {
52617
+ throw toTransportError(error, { url, operation, timeoutMs });
52618
+ }
52619
+ }
52620
+ /** Read the body of an error response, extracting a FHIR OperationOutcome if present. */
52621
+ static async readErrorBody(response) {
52622
+ var _a, _b;
52623
+ let text;
52624
+ try {
52625
+ text = await response.text();
52626
+ } catch {
52627
+ return { outcome: null, detail: void 0 };
52628
+ }
52629
+ let parsed;
52630
+ try {
52631
+ parsed = JSON.parse(text);
52632
+ } catch {
52633
+ const trimmed = text.trim();
52634
+ return { outcome: null, detail: trimmed ? trimmed.slice(0, 200) : void 0 };
52635
+ }
52636
+ const outcome = typeof parsed === "object" && parsed !== null && parsed.resourceType === "OperationOutcome" ? parsed : null;
52637
+ const issue = (_a = outcome == null ? void 0 : outcome.issue) == null ? void 0 : _a[0];
52638
+ const detail = (issue == null ? void 0 : issue.diagnostics) ?? ((_b = issue == null ? void 0 : issue.details) == null ? void 0 : _b.text);
52639
+ return { outcome, detail };
52640
+ }
52641
+ /**
52642
+ * True when an error response is the server's well-formed way of saying
52643
+ * "I do not know this code" — the one case that maps to `null` rather than
52644
+ * an exception.
52645
+ *
52646
+ * A 404 is only accepted as such when the body is a real FHIR
52647
+ * OperationOutcome; a bare 404 (wrong base URL, proxy page) is a fault.
52648
+ */
52649
+ static isUnknownCodeResponse(status, outcome) {
52650
+ if (!outcome) return false;
52651
+ if (status === 404) return true;
52652
+ if (status !== 400 && status !== 422) return false;
52653
+ return (outcome.issue ?? []).some((issue) => {
52654
+ var _a;
52655
+ if (issue.code && _FhirTerminologyService.UNKNOWN_CODE_ISSUE_CODES.has(issue.code.toLowerCase())) {
52656
+ return true;
52657
+ }
52658
+ const prose = `${issue.diagnostics ?? ""} ${((_a = issue.details) == null ? void 0 : _a.text) ?? ""}`.toLowerCase();
52659
+ return _FhirTerminologyService.UNKNOWN_CODE_PHRASES.some((phrase) => prose.includes(phrase));
52660
+ });
52661
+ }
52662
+ /**
52663
+ * Look up a single concept.
52664
+ *
52665
+ * @returns the concept, or `null` when the terminology server gave a
52666
+ * well-formed answer saying the code is unknown to it.
52667
+ * @throws {TerminologyTransportError} when the server could not be reached,
52668
+ * the request timed out, or the response body was unusable.
52669
+ * @throws {TerminologyHttpError} when the server answered with an error
52670
+ * status that is not an "unknown code" response.
52671
+ */
52672
+ async fetchWithRetry(url, timeoutMs, init) {
52673
+ for (let attempt = 0; attempt < RETRY_MAX_ATTEMPTS; attempt++) {
52674
+ const response = await this.fetchWithTimeout(url, timeoutMs, init);
52675
+ if (response.status !== 429) return response;
52676
+ if (attempt === RETRY_MAX_ATTEMPTS - 1) {
52677
+ throw new Error(`FHIR request rate-limited after ${RETRY_MAX_ATTEMPTS} attempts`);
52678
+ }
52679
+ const retryAfterHeader = response.headers.get("Retry-After");
52680
+ const retryAfterMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1e3 : 0;
52681
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * Math.pow(2, attempt), RETRY_MAX_DELAY_MS);
52682
+ const jitter = Math.random() * RETRY_JITTER_MS;
52683
+ const waitMs = Math.max(retryAfterMs, backoff + jitter);
52684
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
52685
+ }
52686
+ throw new Error("Unreachable");
52687
+ }
52688
+ fetchQueued(url, timeoutMs, init) {
52689
+ return this.queue.run(() => this.fetchWithRetry(url, timeoutMs, init));
52690
+ }
52382
52691
  async getConceptInfo(conceptId) {
52383
52692
  var _a;
52384
52693
  const cached = this.cache.get(conceptId);
52385
52694
  if (cached) {
52386
52695
  return cached;
52387
52696
  }
52388
- try {
52389
- let url = `${this.baseUrl}/CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(conceptId)}`;
52390
- if (this.snomedVersion) {
52391
- url += `&version=${encodeURIComponent(this.snomedVersion)}`;
52392
- }
52393
- const response = await this.fetchWithTimeout(url, this.timeout);
52394
- if (!response.ok) {
52697
+ let url = `${this.baseUrl}/CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(conceptId)}`;
52698
+ if (this.snomedVersion) {
52699
+ url += `&version=${encodeURIComponent(this.snomedVersion)}`;
52700
+ }
52701
+ const operation = `$lookup of concept ${conceptId}`;
52702
+ const response = await this.request(url, this.timeout, operation);
52703
+ if (!response.ok) {
52704
+ const { outcome, detail } = await _FhirTerminologyService.readErrorBody(response);
52705
+ if (_FhirTerminologyService.isUnknownCodeResponse(response.status, outcome)) {
52395
52706
  return null;
52396
52707
  }
52397
- const data = await response.json();
52398
- const params = data.parameter ?? [];
52399
- this.captureResolvedVersionFromLookup(params);
52400
- const display = ((_a = params.find((p) => p.name === "display")) == null ? void 0 : _a.valueString) ?? "";
52401
- const properties = params.filter((p) => p.name === "property");
52402
- const inactiveProperty = properties.find((prop) => {
52403
- const parts = prop.part ?? [];
52404
- const codePart = parts.find((p) => p.name === "code" && p.valueCode === "inactive");
52405
- return codePart !== void 0;
52708
+ throw toHttpError({
52709
+ status: response.status,
52710
+ statusText: response.statusText,
52711
+ url,
52712
+ operation,
52713
+ detail
52406
52714
  });
52407
- let active = true;
52408
- if (inactiveProperty) {
52409
- const valuePart = (inactiveProperty.part ?? []).find((p) => p.name === "value");
52410
- if ((valuePart == null ? void 0 : valuePart.valueBoolean) === true) {
52411
- active = false;
52412
- }
52413
- }
52414
- const conceptInfo = {
52415
- id: conceptId,
52416
- fsn: display,
52417
- pt: display,
52418
- // Simplified - would need to parse designations
52419
- active
52420
- };
52421
- if (this.cache.size < 1e4) {
52422
- this.cache.set(conceptId, conceptInfo);
52423
- }
52424
- return conceptInfo;
52715
+ }
52716
+ let data;
52717
+ try {
52718
+ data = await response.json();
52425
52719
  } catch (error) {
52426
- console.warn(`Failed to fetch concept ${conceptId}:`, error);
52427
- return null;
52720
+ throw new TerminologyTransportError(`Terminology server returned an unreadable response for ${operation}`, {
52721
+ cause: error,
52722
+ url
52723
+ });
52724
+ }
52725
+ const params = data.parameter ?? [];
52726
+ this.captureResolvedVersionFromLookup(params);
52727
+ const display = ((_a = params.find((p) => p.name === "display")) == null ? void 0 : _a.valueString) ?? "";
52728
+ const properties = params.filter((p) => p.name === "property");
52729
+ const inactiveProperty = properties.find((prop) => {
52730
+ const parts = prop.part ?? [];
52731
+ const codePart = parts.find((p) => p.name === "code" && p.valueCode === "inactive");
52732
+ return codePart !== void 0;
52733
+ });
52734
+ let active = true;
52735
+ if (inactiveProperty) {
52736
+ const valuePart = (inactiveProperty.part ?? []).find((p) => p.name === "value");
52737
+ if ((valuePart == null ? void 0 : valuePart.valueBoolean) === true) {
52738
+ active = false;
52739
+ }
52740
+ }
52741
+ const conceptInfo = {
52742
+ id: conceptId,
52743
+ fsn: display,
52744
+ pt: display,
52745
+ // Simplified - would need to parse designations
52746
+ active
52747
+ };
52748
+ if (this.cache.size < 1e4) {
52749
+ this.cache.set(conceptId, conceptInfo);
52428
52750
  }
52751
+ return conceptInfo;
52429
52752
  }
52430
52753
  async getHistoricalAssociations(conceptId) {
52431
52754
  const entries = Object.entries(_FhirTerminologyService.ASSOCIATION_REFSETS);
@@ -52444,7 +52767,7 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52444
52767
  const cmUrl = `${this.snomedSystemUrl}?fhir_cm=${refsetId}`;
52445
52768
  const targetUrl = "http://snomed.info/sct?fhir_vs";
52446
52769
  const url = `${this.baseUrl}/ConceptMap/$translate?code=${encodeURIComponent(conceptId)}&system=${encodeURIComponent("http://snomed.info/sct")}&target=${encodeURIComponent(targetUrl)}&url=${encodeURIComponent(cmUrl)}`;
52447
- const response = await this.fetchWithTimeout(url, this.timeout, {
52770
+ const response = await this.fetchQueued(url, this.timeout, {
52448
52771
  headers: { Accept: "application/fhir+json" }
52449
52772
  });
52450
52773
  if (!response.ok) return [];
@@ -52467,11 +52790,65 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52467
52790
  return [];
52468
52791
  }
52469
52792
  }
52793
+ /**
52794
+ * Validate a batch of concepts.
52795
+ *
52796
+ * A `null` map value means the terminology server positively reported the
52797
+ * code as unknown. Failures are never reported as `null` — they reject.
52798
+ *
52799
+ * @throws {TerminologyTransportError} when the server could not be reached.
52800
+ * @throws {TerminologyHttpError} when the server answered with an error status.
52801
+ */
52470
52802
  async validateConcepts(conceptIds) {
52471
52803
  const results = /* @__PURE__ */ new Map();
52472
52804
  if (conceptIds.length === 0) {
52473
52805
  return results;
52474
52806
  }
52807
+ const uncachedIds = this.partitionCached(conceptIds, results);
52808
+ if (uncachedIds.length === 0) {
52809
+ return results;
52810
+ }
52811
+ if (this.bulkExpandUnsupported) {
52812
+ await this.lookupEach(uncachedIds, results);
52813
+ return results;
52814
+ }
52815
+ try {
52816
+ const expandResults = await this.bulkExpand(uncachedIds);
52817
+ const missingIds = this.mergeExpandResults(uncachedIds, expandResults, results);
52818
+ await this.lookupEach(missingIds, results);
52819
+ return results;
52820
+ } catch (error) {
52821
+ if (isTerminologyTransportError(error)) throw error;
52822
+ if (isTerminologyHttpError(error) && error.status >= 400 && error.status < 500) {
52823
+ this.bulkExpandUnsupported = true;
52824
+ }
52825
+ await this.lookupEach(uncachedIds, results);
52826
+ return results;
52827
+ }
52828
+ }
52829
+ /**
52830
+ * Move concepts found in a bulk expansion into `results` (and the cache),
52831
+ * returning the IDs that were absent and still need an individual lookup.
52832
+ */
52833
+ mergeExpandResults(uncachedIds, expandResults, results) {
52834
+ const missingIds = [];
52835
+ for (const id of uncachedIds) {
52836
+ const info = expandResults.get(id);
52837
+ if (info) {
52838
+ results.set(id, info);
52839
+ if (this.cache.size < 1e4) {
52840
+ this.cache.set(id, info);
52841
+ }
52842
+ } else {
52843
+ missingIds.push(id);
52844
+ }
52845
+ }
52846
+ return missingIds;
52847
+ }
52848
+ /**
52849
+ * Move already-cached concepts into `results`, returning the IDs still to fetch.
52850
+ */
52851
+ partitionCached(conceptIds, results) {
52475
52852
  const uncachedIds = [];
52476
52853
  for (const id of conceptIds) {
52477
52854
  const cachedInfo = this.cache.get(id);
@@ -52481,40 +52858,17 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52481
52858
  uncachedIds.push(id);
52482
52859
  }
52483
52860
  }
52484
- if (uncachedIds.length === 0) {
52485
- return results;
52486
- }
52487
- try {
52488
- const expandResults = await this.bulkExpand(uncachedIds);
52489
- const missingIds = [];
52490
- for (const id of uncachedIds) {
52491
- const info = expandResults.get(id);
52492
- if (info) {
52493
- results.set(id, info);
52494
- if (this.cache.size < 1e4) {
52495
- this.cache.set(id, info);
52496
- }
52497
- } else {
52498
- missingIds.push(id);
52499
- }
52500
- }
52501
- if (missingIds.length > 0) {
52502
- const lookups = missingIds.map(async (id) => {
52503
- const info = await this.getConceptInfo(id);
52504
- results.set(id, info);
52505
- });
52506
- await Promise.all(lookups);
52507
- }
52508
- return results;
52509
- } catch (error) {
52510
- console.warn("Bulk concept validation failed, falling back to individual lookups:", error);
52511
- const lookups = uncachedIds.map(async (id) => {
52861
+ return uncachedIds;
52862
+ }
52863
+ /** Look each concept up individually, recording the result (or `null` if absent). */
52864
+ async lookupEach(conceptIds, results) {
52865
+ if (conceptIds.length === 0) return;
52866
+ await Promise.all(
52867
+ conceptIds.map(async (id) => {
52512
52868
  const info = await this.getConceptInfo(id);
52513
52869
  results.set(id, info);
52514
- });
52515
- await Promise.all(lookups);
52516
- return results;
52517
- }
52870
+ })
52871
+ );
52518
52872
  }
52519
52873
  async bulkExpand(conceptIds) {
52520
52874
  var _a, _b;
@@ -52531,13 +52885,21 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52531
52885
  resourceType: "ValueSet",
52532
52886
  compose: { include: [include] }
52533
52887
  };
52534
- const response = await this.fetchWithTimeout(url, this.timeout, {
52888
+ const operation = `bulk $expand of ${conceptIds.length} concept(s)`;
52889
+ const response = await this.request(url, this.timeout, operation, {
52535
52890
  method: "POST",
52536
52891
  headers: { "Content-Type": "application/fhir+json" },
52537
52892
  body: JSON.stringify(valueSet)
52538
52893
  });
52539
52894
  if (!response.ok) {
52540
- throw new Error(`Bulk expand failed: HTTP ${response.status}`);
52895
+ const { detail } = await _FhirTerminologyService.readErrorBody(response);
52896
+ throw toHttpError({
52897
+ status: response.status,
52898
+ statusText: response.statusText,
52899
+ url,
52900
+ operation,
52901
+ detail
52902
+ });
52541
52903
  }
52542
52904
  const data = await response.json();
52543
52905
  this.captureResolvedVersion((_a = data.expansion) == null ? void 0 : _a.parameter);
@@ -52566,6 +52928,14 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52566
52928
  }
52567
52929
  return results;
52568
52930
  }
52931
+ /**
52932
+ * Search for concepts by text or SCTID.
52933
+ *
52934
+ * An empty result set means the server found no matches.
52935
+ *
52936
+ * @throws {TerminologyTransportError} when the server could not be reached.
52937
+ * @throws {TerminologyHttpError} when the server answered with an error status.
52938
+ */
52569
52939
  // eslint-disable-next-line sonarjs/cognitive-complexity -- FHIR response parser with nested property traversal
52570
52940
  async searchConcepts(query) {
52571
52941
  if (!query || query.trim().length === 0) {
@@ -52592,22 +52962,17 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52592
52962
  }
52593
52963
  entriesToDelete.forEach((key) => this.searchCache.delete(key));
52594
52964
  }
52595
- try {
52596
- let response;
52597
- if (/^\d+$/.test(trimmedQuery) && isValidSnomedId(trimmedQuery)) {
52598
- response = await this.lookupById(trimmedQuery);
52599
- } else {
52600
- response = await this.searchByFilter(trimmedQuery);
52601
- }
52602
- this.searchCache.set(trimmedQuery, {
52603
- data: response,
52604
- timestamp: Date.now()
52605
- });
52606
- return response;
52607
- } catch (error) {
52608
- console.warn(`Search failed for query "${trimmedQuery}":`, error);
52609
- throw new Error("Terminology server unavailable");
52965
+ let response;
52966
+ if (/^\d+$/.test(trimmedQuery) && isValidSnomedId(trimmedQuery)) {
52967
+ response = await this.lookupById(trimmedQuery);
52968
+ } else {
52969
+ response = await this.searchByFilter(trimmedQuery);
52610
52970
  }
52971
+ this.searchCache.set(trimmedQuery, {
52972
+ data: response,
52973
+ timestamp: Date.now()
52974
+ });
52975
+ return response;
52611
52976
  }
52612
52977
  async lookupById(conceptId) {
52613
52978
  const info = await this.getConceptInfo(conceptId);
@@ -52626,50 +52991,160 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52626
52991
  };
52627
52992
  }
52628
52993
  async evaluateEcl(expression, limit = 200) {
52629
- var _a, _b, _c, _d, _e;
52630
52994
  if (!expression || expression.trim().length === 0) {
52631
52995
  return { total: 0, concepts: [], truncated: false };
52632
52996
  }
52633
- const implicitVsUrl = `${this.snomedSystemUrl}?fhir_vs=ecl/${expression.trim()}`;
52634
- const url = `${this.baseUrl}/ValueSet/$expand?url=${encodeURIComponent(implicitVsUrl)}&count=${limit}`;
52635
- const response = await this.fetchWithTimeout(url, this.evaluationTimeout);
52636
- if (!response.ok) {
52637
- const data2 = await response.json().catch(() => null);
52638
- const issue = ((_b = (_a = data2 == null ? void 0 : data2.issue) == null ? void 0 : _a[0]) == null ? void 0 : _b.diagnostics) ?? ((_e = (_d = (_c = data2 == null ? void 0 : data2.issue) == null ? void 0 : _c[0]) == null ? void 0 : _d.details) == null ? void 0 : _e.text) ?? `HTTP ${response.status}`;
52639
- if (expression.includes("{{") && /no viable alternative/i.test(issue)) {
52640
- const cleaned = issue.replace(/^\[[0-9a-f-]+\]:\s*/i, "");
52641
- throw new Error(
52642
- `FHIR evaluation failed: ${cleaned}
52643
- Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by this terminology server.`
52644
- );
52645
- }
52646
- throw new Error(`FHIR evaluation failed: ${issue}`);
52997
+ const trimmed = expression.trim();
52998
+ const deadline = Date.now() + this.evaluationTimeout;
52999
+ try {
53000
+ return await this.runEvaluationStrategy(trimmed, limit, deadline);
53001
+ } catch (error) {
53002
+ if (!(error instanceof EvaluationIssueError)) throw error;
53003
+ throw this.createEvaluationError(trimmed, error);
52647
53004
  }
52648
- const data = await response.json();
52649
- const expansion = data.expansion ?? {};
52650
- this.captureResolvedVersion(expansion.parameter);
52651
- const total = typeof expansion.total === "number" ? expansion.total : 0;
52652
- const contains = expansion.contains ?? [];
52653
- const concepts = contains.map((item) => ({
52654
- code: item.code ?? "",
52655
- display: item.display ?? ""
52656
- }));
52657
- return {
52658
- total,
52659
- concepts,
52660
- truncated: total > concepts.length
52661
- };
52662
53005
  }
52663
- async searchByFilter(filter) {
52664
- const url = `${this.baseUrl}/ValueSet/$expand?url=${this.snomedSystemUrl}?fhir_vs&filter=${encodeURIComponent(filter)}&count=21&includeDesignations=true&activeOnly=true`;
52665
- const response = await this.fetchWithTimeout(url, this.searchTimeout);
52666
- if (!response.ok) {
52667
- throw new Error(`FHIR request failed: ${response.status}`);
53006
+ /**
53007
+ * Transport selection for {@link evaluateEcl}.
53008
+ *
53009
+ * A forced `'post'` strategy — or a latched successful POST fallback — goes straight to
53010
+ * `POST ValueSet/$expand`. Otherwise the implicit ValueSet URL GET runs first, and in
53011
+ * `'auto'` mode a failure whose *shape* says the server cannot serve implicit ValueSets
53012
+ * (issue #55) is retried over POST.
53013
+ */
53014
+ async runEvaluationStrategy(expression, limit, deadline) {
53015
+ if (this.evaluationStrategy === "post" || this.usePostExpand) {
53016
+ return await this.evaluateViaPostExpand(expression, limit, deadline);
52668
53017
  }
52669
- const data = await response.json();
52670
- const expansion = data.expansion ?? {};
52671
- this.captureResolvedVersion(expansion.parameter);
52672
- const contains = expansion.contains ?? [];
53018
+ const response = await this.fetchQueued(
53019
+ this.buildImplicitEvaluationUrl(expression, limit),
53020
+ this.remainingTimeout(deadline)
53021
+ );
53022
+ if (response.ok) {
53023
+ return this.parseEvaluationResponse(await response.json());
53024
+ }
53025
+ const outcome = await this.readOperationOutcome(response);
53026
+ if (this.evaluationStrategy === "implicit-url" || !this.shouldFallbackToPostExpand(response.status, outcome)) {
53027
+ throw new EvaluationIssueError(outcome.issue);
53028
+ }
53029
+ try {
53030
+ const result = await this.evaluateViaPostExpand(expression, limit, deadline);
53031
+ this.usePostExpand = true;
53032
+ return result;
53033
+ } catch (error) {
53034
+ if (!(error instanceof EvaluationIssueError)) throw error;
53035
+ throw new EvaluationIssueError(
53036
+ `${error.message} (POST ValueSet/$expand fallback; the implicit ValueSet URL also failed: ${outcome.issue})`,
53037
+ { cause: error }
53038
+ );
53039
+ }
53040
+ }
53041
+ /** `GET ValueSet/$expand?url=<canonical implicit ECL ValueSet>` — see {@link encodeEclForCanonicalUrl}. */
53042
+ buildImplicitEvaluationUrl(expression, limit) {
53043
+ const implicitVsUrl = `${this.snomedSystemUrl}?fhir_vs=ecl/${encodeEclForCanonicalUrl(expression)}`;
53044
+ return `${this.baseUrl}/ValueSet/$expand?url=${encodeURIComponent(implicitVsUrl)}&count=${limit}`;
53045
+ }
53046
+ /**
53047
+ * `POST ValueSet/$expand` carrying the ECL in `compose.include.filter` with
53048
+ * `property: "constraint"` — the form requested in issue #55. The expression travels in a
53049
+ * JSON body, so it needs no escaping at all.
53050
+ */
53051
+ async evaluateViaPostExpand(expression, limit, deadline) {
53052
+ const include = {
53053
+ system: "http://snomed.info/sct",
53054
+ // eslint-disable-line sonarjs/no-clear-text-protocols -- FHIR system URI, not a network URL
53055
+ ...this.snomedVersion ? { version: this.snomedVersion } : {},
53056
+ filter: [{ property: "constraint", op: "=", value: expression }]
53057
+ };
53058
+ const response = await this.fetchQueued(
53059
+ `${this.baseUrl}/ValueSet/$expand?count=${limit}`,
53060
+ this.remainingTimeout(deadline),
53061
+ {
53062
+ method: "POST",
53063
+ headers: { "Content-Type": "application/fhir+json", Accept: "application/fhir+json" },
53064
+ body: JSON.stringify({ resourceType: "ValueSet", compose: { include: [include] } })
53065
+ }
53066
+ );
53067
+ if (!response.ok) {
53068
+ throw new EvaluationIssueError((await this.readOperationOutcome(response)).issue);
53069
+ }
53070
+ return this.parseEvaluationResponse(await response.json());
53071
+ }
53072
+ /**
53073
+ * True when an implicit-URL failure indicates the implicit ValueSet *form* is unsupported
53074
+ * rather than the expression being invalid.
53075
+ *
53076
+ * Deliberately excludes a bare HTTP 422: that is also how a genuine ECL syntax error
53077
+ * presents, and retrying those over POST would only turn one clear error into two requests
53078
+ * and a muddled message. The `'not-found'` OperationOutcome code is still honoured on any
53079
+ * status, which covers servers that report a missing implicit ValueSet as 422.
53080
+ */
53081
+ shouldFallbackToPostExpand(status, outcome) {
53082
+ return status === 404 || status === 414 || outcome.code === "not-found" || VALUE_SET_NOT_FOUND.test(outcome.issue) || IMPLICIT_VALUE_SET_UNSUPPORTED.some((pattern) => pattern.test(outcome.issue));
53083
+ }
53084
+ /** Remaining milliseconds in the shared evaluation budget; throws once it is spent. */
53085
+ remainingTimeout(deadline) {
53086
+ const remaining = deadline - Date.now();
53087
+ if (remaining <= 0) {
53088
+ throw new EvaluationIssueError("evaluation timed out");
53089
+ }
53090
+ return remaining;
53091
+ }
53092
+ /** The machine-readable code and human-readable text of a FHIR error response. */
53093
+ async readOperationOutcome(response) {
53094
+ var _a, _b;
53095
+ const data = await response.json().catch(() => null);
53096
+ const first = (_a = data == null ? void 0 : data.issue) == null ? void 0 : _a[0];
53097
+ return {
53098
+ code: first == null ? void 0 : first.code,
53099
+ issue: (first == null ? void 0 : first.diagnostics) ?? ((_b = first == null ? void 0 : first.details) == null ? void 0 : _b.text) ?? `HTTP ${response.status}`
53100
+ };
53101
+ }
53102
+ /** Shared expansion mapping for both the implicit-URL and POST evaluation transports. */
53103
+ parseEvaluationResponse(data) {
53104
+ const expansion = data.expansion ?? {};
53105
+ this.captureResolvedVersion(expansion.parameter);
53106
+ const total = typeof expansion.total === "number" ? expansion.total : 0;
53107
+ const contains = expansion.contains ?? [];
53108
+ const concepts = contains.map((item) => ({
53109
+ code: item.code ?? "",
53110
+ display: item.display ?? ""
53111
+ }));
53112
+ return {
53113
+ total,
53114
+ concepts,
53115
+ truncated: total > concepts.length
53116
+ };
53117
+ }
53118
+ createEvaluationError(expression, error) {
53119
+ const issue = error.message;
53120
+ if (expression.includes("{{") && /no viable alternative/i.test(issue)) {
53121
+ const cleaned = issue.replace(/^\[[0-9a-f-]+\]:\s*/i, "");
53122
+ return new Error(
53123
+ `FHIR evaluation failed: ${cleaned}
53124
+ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by this terminology server.`,
53125
+ { cause: error }
53126
+ );
53127
+ }
53128
+ return new Error(`FHIR evaluation failed: ${issue}`, { cause: error });
53129
+ }
53130
+ async searchByFilter(filter) {
53131
+ const url = `${this.baseUrl}/ValueSet/$expand?url=${this.snomedSystemUrl}?fhir_vs&filter=${encodeURIComponent(filter)}&count=21&includeDesignations=true&activeOnly=true`;
53132
+ const operation = `concept search for "${filter}"`;
53133
+ const response = await this.request(url, this.searchTimeout, operation);
53134
+ if (!response.ok) {
53135
+ const { detail } = await _FhirTerminologyService.readErrorBody(response);
53136
+ throw toHttpError({
53137
+ status: response.status,
53138
+ statusText: response.statusText,
53139
+ url,
53140
+ operation,
53141
+ detail
53142
+ });
53143
+ }
53144
+ const data = await response.json();
53145
+ const expansion = data.expansion ?? {};
53146
+ this.captureResolvedVersion(expansion.parameter);
53147
+ const contains = expansion.contains ?? [];
52673
53148
  const hasMore = contains.length > 20;
52674
53149
  const results = contains.slice(0, 20).map((item) => {
52675
53150
  var _a;
@@ -52690,9 +53165,17 @@ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by
52690
53165
  async getSnomedEditions() {
52691
53166
  var _a;
52692
53167
  const url = `${this.baseUrl}/CodeSystem?url=http://snomed.info/sct`;
52693
- const response = await this.fetchWithTimeout(url, this.searchTimeout);
53168
+ const operation = "SNOMED CT edition discovery";
53169
+ const response = await this.request(url, this.searchTimeout, operation);
52694
53170
  if (!response.ok) {
52695
- throw new Error(`Failed to fetch SNOMED editions: HTTP ${response.status}`);
53171
+ const { detail } = await _FhirTerminologyService.readErrorBody(response);
53172
+ throw toHttpError({
53173
+ status: response.status,
53174
+ statusText: response.statusText,
53175
+ url,
53176
+ operation,
53177
+ detail
53178
+ });
52696
53179
  }
52697
53180
  const data = await response.json();
52698
53181
  const editionMap = /* @__PURE__ */ new Map();
@@ -52717,6 +53200,10 @@ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by
52717
53200
  return editions;
52718
53201
  }
52719
53202
  };
53203
+ /** Issue codes a FHIR server uses to say "this code is not in the code system". */
53204
+ __publicField(_FhirTerminologyService, "UNKNOWN_CODE_ISSUE_CODES", /* @__PURE__ */ new Set(["not-found", "code-invalid", "invalid-code"]));
53205
+ /** Phrases servers use in OperationOutcome prose when a code is unknown. */
53206
+ __publicField(_FhirTerminologyService, "UNKNOWN_CODE_PHRASES", ["unknown code", "not found", "invalid code", "unable to find"]);
52720
53207
  /** Map of SNOMED CT historical association reference set IDs to association types. */
52721
53208
  __publicField(_FhirTerminologyService, "ASSOCIATION_REFSETS", {
52722
53209
  "900000000000527005": "same-as",
@@ -53192,13 +53679,13 @@ function printAst(ast, sourceText, options) {
53192
53679
  if (!ast) {
53193
53680
  return "";
53194
53681
  }
53195
- return printExpression$1(ast, 0, 0, options, sourceText);
53682
+ return printExpression$1(ast, 0, 0, options, sourceText, true);
53196
53683
  }
53197
- function printExpression$1(node, depth, column, opts, src) {
53684
+ function printExpression$1(node, depth, column, opts, src, isRoot = false) {
53198
53685
  const inner = node.expression;
53199
53686
  switch (inner.type) {
53200
53687
  case NodeType.SubExpressionConstraint:
53201
- return printSubExpression$1(inner, depth, column, opts, src);
53688
+ return printSubExpression$1(inner, depth, column, opts, src, isRoot);
53202
53689
  case NodeType.CompoundExpression:
53203
53690
  return printCompoundExpression$1(inner, depth, column, opts, src);
53204
53691
  case NodeType.RefinedExpression:
@@ -53211,7 +53698,7 @@ function printExpression$1(node, depth, column, opts, src) {
53211
53698
  }
53212
53699
  }
53213
53700
  }
53214
- function printSubExpression$1(node, depth, column, opts, src) {
53701
+ function printSubExpression$1(node, depth, column, opts, src, isRoot = false) {
53215
53702
  let result = "";
53216
53703
  if (node.operator) {
53217
53704
  result += node.operator.operator + " ";
@@ -53228,10 +53715,11 @@ function printSubExpression$1(node, depth, column, opts, src) {
53228
53715
  break;
53229
53716
  case NodeType.ExpressionConstraint: {
53230
53717
  const innerExpr = node.focus;
53231
- if (opts.removeRedundantParentheses && !node.operator && !node.memberOf) {
53718
+ if (opts.removeRedundantParentheses && !node.operator && !node.memberOf && !node.filters && !node.historySupplement) {
53232
53719
  const inner = innerExpr.expression;
53233
- if (inner.type !== NodeType.CompoundExpression) {
53234
- result += printExpression$1(innerExpr, depth, column + result.length, opts, src);
53720
+ const needsParens = !isRoot && (inner.type === NodeType.RefinedExpression || inner.type === NodeType.DottedExpression);
53721
+ if (inner.type !== NodeType.CompoundExpression && !needsParens) {
53722
+ result += printExpression$1(innerExpr, depth, column + result.length, opts, src, isRoot);
53235
53723
  break;
53236
53724
  }
53237
53725
  }
@@ -53263,7 +53751,7 @@ function printSubExpression$1(node, depth, column, opts, src) {
53263
53751
  }
53264
53752
  function printCompoundExpression$1(node, depth, column, opts, src) {
53265
53753
  const op = node.operator.operator;
53266
- const opSep = opts.spaceAroundOperators ? ` ${op} ` : op;
53754
+ const opSep = ` ${op} `;
53267
53755
  let operands = node.operands;
53268
53756
  if (opts.removeRedundantParentheses && (op === "AND" || op === "OR")) {
53269
53757
  operands = flattenSameOperatorOperands(operands, op);
@@ -53326,42 +53814,84 @@ function printRefinedExpression$1(node, depth, column, opts, src) {
53326
53814
  }
53327
53815
  const focusIsMultilineParen = focus.includes("\n") && node.expression.focus.type === NodeType.ExpressionConstraint;
53328
53816
  const attrDepth = focusIsMultilineParen ? depth + 2 : depth + 1;
53329
- const ind = getIndentString(attrDepth, opts);
53330
- const refSrc = src.slice(node.refinement.range.start.offset, node.refinement.range.end.offset).trim();
53331
- const wholeBraces = refSrc.startsWith("{");
53332
- if (wholeBraces) {
53333
- const innerInd = getIndentString(attrDepth + 1, opts);
53334
- const attrs = node.refinement.attributes.map((a) => printAttribute$1(a, attrDepth + 1, innerInd.length, opts, src));
53335
- return focus + ":\n" + ind + "{\n" + attrs.map((a) => innerInd + a).join(",\n") + "\n" + ind + "}";
53336
- }
53337
- const attrParts = [];
53338
- let prevEnd = node.refinement.range.start.offset;
53339
- for (const attr of node.refinement.attributes) {
53340
- const printed = printAttribute$1(attr, attrDepth, ind.length, opts, src);
53341
- const inBraces = isAttrInBraceGroup$1(attr, prevEnd, src);
53342
- attrParts.push(ind + (inBraces ? "{ " + printed + " }" : printed));
53343
- prevEnd = attr.range.end.offset;
53344
- }
53345
- return focus + ":\n" + attrParts.join(",\n");
53346
- }
53347
- function isAttrInBraceGroup$1(attr, prevEnd, src) {
53348
- const gap = src.slice(prevEnd, attr.range.start.offset);
53349
- return gap.includes("{");
53817
+ const content = node.refinement.content;
53818
+ if (!content) {
53819
+ return focus + ":";
53820
+ }
53821
+ return focus + ":\n" + printMemberBlock(content, attrDepth, opts, src);
53350
53822
  }
53351
- function printRefinement$1(node, depth, opts, src) {
53352
- const parts = [];
53353
- let prevEnd = node.range.start.offset;
53354
- for (const attr of node.attributes) {
53355
- const printed = printAttribute$1(attr, depth, 0, opts, src);
53356
- const inBraces = isAttrInBraceGroup$1(attr, prevEnd, src);
53357
- parts.push(inBraces ? "{ " + printed + " }" : printed);
53358
- prevEnd = attr.range.end.offset;
53823
+ function setSeparator(node) {
53824
+ if (node.operator === "OR") return " OR ";
53825
+ return node.conjunctionStyle === "AND" ? " AND " : ", ";
53826
+ }
53827
+ function flattenSameOperatorMembers$1(node, opts) {
53828
+ const result = [];
53829
+ for (const member of node.members) {
53830
+ const redundant = member.type === NodeType.AttributeSet && member.operator === node.operator && (!member.parenthesized || opts.removeRedundantParentheses);
53831
+ if (redundant) {
53832
+ result.push(...flattenSameOperatorMembers$1(member, opts));
53833
+ } else {
53834
+ result.push(member);
53835
+ }
53836
+ }
53837
+ return result;
53838
+ }
53839
+ function printRefinementMember$1(node, depth, column, opts, src) {
53840
+ switch (node.type) {
53841
+ case NodeType.Attribute:
53842
+ return printAttribute$1(node, depth, column, opts, src);
53843
+ case NodeType.AttributeGroup: {
53844
+ const prefix = (node.cardinality ? node.cardinality + " " : "") + "{ ";
53845
+ return prefix + printRefinementMember$1(node.content, depth, column + prefix.length, opts, src) + " }";
53846
+ }
53847
+ case NodeType.AttributeSet: {
53848
+ const members = flattenSameOperatorMembers$1(node, opts);
53849
+ const sep = setSeparator(node);
53850
+ const parts = [];
53851
+ let col = column;
53852
+ for (const member of members) {
53853
+ const text = printNestedMember(member, depth, col, opts, src);
53854
+ parts.push(text);
53855
+ col += text.length + sep.length;
53856
+ }
53857
+ return parts.join(sep);
53858
+ }
53859
+ }
53860
+ }
53861
+ function printNestedMember(node, depth, column, opts, src) {
53862
+ if (node.type === NodeType.AttributeSet) {
53863
+ return "(" + printRefinementMember$1(node, depth, column + 1, opts, src) + ")";
53864
+ }
53865
+ return printRefinementMember$1(node, depth, column, opts, src);
53866
+ }
53867
+ function printMemberBlock(node, depth, opts, src) {
53868
+ const ind = getIndentString(depth, opts);
53869
+ if (node.type === NodeType.AttributeGroup) {
53870
+ const card = node.cardinality ? node.cardinality + " " : "";
53871
+ return ind + card + "{\n" + printMemberBlock(node.content, depth + 1, opts, src) + "\n" + ind + "}";
53872
+ }
53873
+ if (node.type === NodeType.AttributeSet) {
53874
+ const members = flattenSameOperatorMembers$1(node, opts);
53875
+ const rendered = members.map((member) => {
53876
+ const line = ind + printNestedMember(member, depth, ind.length, opts, src);
53877
+ if (member.type === NodeType.AttributeGroup && opts.maxLineLength > 0 && line.length > opts.maxLineLength) {
53878
+ return printMemberBlock(member, depth, opts, src);
53879
+ }
53880
+ return line;
53881
+ });
53882
+ if (node.operator === "AND" && node.conjunctionStyle === ",") {
53883
+ return rendered.join(",\n");
53884
+ }
53885
+ const keyword = node.operator;
53886
+ return rendered.map((text, i) => i === 0 ? text : ind + keyword + " " + text.slice(ind.length)).join("\n");
53359
53887
  }
53360
- return parts.join(", ");
53888
+ return ind + printAttribute$1(node, depth, ind.length, opts, src);
53889
+ }
53890
+ function printRefinement$1(node, depth, opts, src) {
53891
+ return node.content ? printRefinementMember$1(node.content, depth, 0, opts, src) : "";
53361
53892
  }
53362
53893
  function printAttribute$1(node, depth, column, opts, src) {
53363
- const preNameSrc = src.slice(node.range.start.offset, node.name.range.start.offset).trim();
53364
- const cardinalityPrefix = preNameSrc.length > 0 ? preNameSrc + " " : "";
53894
+ const cardinalityPrefix = node.cardinality ? node.cardinality + " " : "";
53365
53895
  let name;
53366
53896
  if (node.name.conceptId) {
53367
53897
  name = node.name.term ? node.name.conceptId + normalizeTerm(node.name.term) : node.name.conceptId;
@@ -53395,110 +53925,442 @@ function lastLineLength(text) {
53395
53925
  const lastNewline = text.lastIndexOf("\n");
53396
53926
  return lastNewline === -1 ? text.length : text.length - lastNewline - 1;
53397
53927
  }
53398
- function splitExpressions(text) {
53399
- const delimiter = "/* ECL-END */";
53400
- const delimiterPositions = [];
53401
- let i = 0;
53402
- while (i < text.length) {
53403
- if (text[i] === "/" && i + 1 < text.length && text[i + 1] === "/") {
53404
- while (i < text.length && text[i] !== "\n") i++;
53405
- continue;
53928
+ function printCanonical(ast, sourceText, outerOperator) {
53929
+ if (ast.type === NodeType.SubExpressionConstraint) {
53930
+ return printSubExpression(ast, sourceText, outerOperator);
53931
+ }
53932
+ return printExpression(ast, sourceText, outerOperator);
53933
+ }
53934
+ function printExpression(node, src, outerOperator) {
53935
+ const inner = node.expression;
53936
+ switch (inner.type) {
53937
+ case NodeType.SubExpressionConstraint:
53938
+ return printSubExpression(inner, src, outerOperator);
53939
+ case NodeType.CompoundExpression:
53940
+ return printCompoundExpression(inner, src);
53941
+ case NodeType.RefinedExpression:
53942
+ return printRefinedExpression(inner, src);
53943
+ case NodeType.DottedExpression:
53944
+ return printDottedExpression(inner, src);
53945
+ default: {
53946
+ const _exhaustive = inner;
53947
+ return String(_exhaustive);
53406
53948
  }
53407
- if (text.startsWith(delimiter, i)) {
53408
- delimiterPositions.push(i);
53409
- i += delimiter.length;
53410
- continue;
53949
+ }
53950
+ }
53951
+ function printSubExpression(node, src, outerOperator) {
53952
+ let result = "";
53953
+ if (node.operator) {
53954
+ result += node.operator.operator;
53955
+ }
53956
+ if (node.memberOf) {
53957
+ result += "^";
53958
+ }
53959
+ switch (node.focus.type) {
53960
+ case NodeType.ConceptReference:
53961
+ result += printConceptReference(node.focus);
53962
+ break;
53963
+ case NodeType.Wildcard:
53964
+ result += "*";
53965
+ break;
53966
+ case NodeType.ExpressionConstraint: {
53967
+ const innerExpr = node.focus.expression;
53968
+ if (innerExpr.type !== NodeType.CompoundExpression) {
53969
+ result += printExpression(node.focus, src, outerOperator);
53970
+ } else if (outerOperator && innerExpr.operator.operator === outerOperator) {
53971
+ result += printExpression(node.focus, src, outerOperator);
53972
+ } else {
53973
+ result += "(" + printExpression(node.focus, src) + ")";
53974
+ }
53975
+ break;
53411
53976
  }
53412
- i++;
53413
53977
  }
53414
- if (delimiterPositions.length === 0) {
53415
- return { expressions: [text], hasDelimiters: false };
53978
+ if (node.filters) {
53979
+ for (const filter of node.filters) {
53980
+ const filterText = src.slice(filter.range.start.offset, filter.range.end.offset);
53981
+ result += " " + filterText.replaceAll(/\s+/g, " ").trim();
53982
+ }
53416
53983
  }
53417
- const parts = [];
53418
- let lastEnd = 0;
53419
- for (const pos of delimiterPositions) {
53420
- parts.push(text.substring(lastEnd, pos));
53421
- lastEnd = pos + delimiter.length;
53984
+ if (node.historySupplement) {
53985
+ const histText = src.slice(node.historySupplement.range.start.offset, node.historySupplement.range.end.offset);
53986
+ result += " " + histText.replaceAll(/\s+/g, " ").trim();
53422
53987
  }
53423
- parts.push(text.substring(lastEnd));
53424
- const expressions = parts.map((p) => p.trim()).filter((p) => p.length > 0);
53425
- return { expressions, hasDelimiters: true };
53988
+ return result;
53426
53989
  }
53427
- function joinExpressions(expressions) {
53428
- return expressions.join("\n\n/* ECL-END */\n\n");
53990
+ function printCompoundExpression(node, src) {
53991
+ const op = node.operator.operator;
53992
+ return node.operands.map((operand) => printSubExpression(operand, src, op)).join(` ${op} `);
53429
53993
  }
53430
- function isCommentOrBlankLine(line) {
53431
- const trimmed = line.trim();
53432
- if (!trimmed) return true;
53433
- if (trimmed.startsWith("//")) return true;
53434
- const stripped = trimmed.replace(/\/\*[^]*?\*\//g, "").trim();
53435
- return stripped.length === 0;
53994
+ function printRefinedExpression(node, src) {
53995
+ const focus = printSubExpression(node.expression, src);
53996
+ const refinement = printRefinement(node.refinement, src);
53997
+ return focus + ":" + refinement;
53436
53998
  }
53437
- function maybeWrapCommentLine(line, options) {
53438
- if (!options.wrapComments || options.maxLineLength <= 0) return line;
53439
- if (line.length <= options.maxLineLength) return line;
53440
- const match = /^(\s*\/\/\s?)(.*)/.exec(line);
53441
- if (!match) return line;
53442
- const prefix = match[1];
53443
- const words = match[2].split(" ");
53444
- const lines = [];
53445
- let current = prefix;
53446
- for (const word of words) {
53447
- if (current.length + word.length + 1 > options.maxLineLength && current.trim() !== prefix.trim()) {
53448
- lines.push(current.trimEnd());
53449
- current = prefix + word;
53450
- } else {
53451
- current = current === prefix ? prefix + word : current + " " + word;
53452
- }
53453
- }
53454
- if (current.trim()) lines.push(current.trimEnd());
53455
- return lines.join("\n");
53999
+ function printDottedExpression(node, src) {
54000
+ const source = printSubExpression(node.source, src);
54001
+ const dots = node.attributes.map((a) => printSubExpression(a.attributeName, src));
54002
+ return source + dots.map((d) => "." + d).join("");
53456
54003
  }
53457
- function maybeWrapCommentBlock(text, options) {
53458
- if (!options.wrapComments) return text;
53459
- return text.split("\n").map((line) => maybeWrapCommentLine(line, options)).join("\n");
54004
+ function printRefinement(node, src) {
54005
+ return node.content ? printRefinementMember(node.content, src) : "";
53460
54006
  }
53461
- function formatExpression(text, options, ast) {
53462
- const lines = text.split("\n");
53463
- let firstCodeLine = -1;
53464
- let lastCodeLine = -1;
53465
- for (let i = 0; i < lines.length; i++) {
53466
- if (!isCommentOrBlankLine(lines[i])) {
53467
- if (firstCodeLine === -1) firstCodeLine = i;
53468
- lastCodeLine = i;
54007
+ function printRefinementMember(node, src) {
54008
+ switch (node.type) {
54009
+ case NodeType.Attribute:
54010
+ return printAttribute(node, src);
54011
+ case NodeType.AttributeGroup:
54012
+ return (node.cardinality ?? "") + "{" + printRefinementMember(node.content, src) + "}";
54013
+ case NodeType.AttributeSet: {
54014
+ const sep = node.operator === "OR" ? " OR " : ",";
54015
+ return node.members.map(
54016
+ (member) => member.type === NodeType.AttributeSet ? "(" + printRefinementMember(member, src) + ")" : printRefinementMember(member, src)
54017
+ ).join(sep);
53469
54018
  }
53470
54019
  }
53471
- if (firstCodeLine === -1) {
53472
- return text;
54020
+ }
54021
+ function printAttribute(node, src) {
54022
+ const cardinalityPrefix = node.cardinality ? node.cardinality + " " : "";
54023
+ let name;
54024
+ if (node.name.conceptId) {
54025
+ name = node.name.conceptId;
54026
+ } else if (node.name.expression) {
54027
+ name = printSubExpression(node.name.expression, src);
54028
+ } else {
54029
+ name = src.slice(node.name.range.start.offset, node.name.range.end.offset).trim();
53473
54030
  }
53474
- const leadingRaw = firstCodeLine > 0 ? lines.slice(0, firstCodeLine).join("\n") + "\n" : "";
53475
- const trailingRaw = lastCodeLine < lines.length - 1 ? "\n" + lines.slice(lastCodeLine + 1).join("\n") : "";
53476
- const bodyText = lines.slice(firstCodeLine, lastCodeLine + 1).join("\n");
53477
- const leadingText = maybeWrapCommentBlock(leadingRaw, options);
53478
- const trailingText = maybeWrapCommentBlock(trailingRaw, options);
53479
- const formattedBody = formatExpressionBody(bodyText, options, ast);
53480
- return leadingText + formattedBody + trailingText;
54031
+ const between = src.slice(node.name.range.end.offset, node.value.range.start.offset);
54032
+ const opMatch = /(!?=|[<>]=)/.exec(between);
54033
+ const compOp = opMatch ? opMatch[1] : "=";
54034
+ const hasHashPrefix = between.includes("#");
54035
+ let value;
54036
+ if (node.value.expression) {
54037
+ value = printSubExpression(node.value.expression, src);
54038
+ } else if (node.value.rawValue) {
54039
+ value = hasHashPrefix ? "#" + node.value.rawValue : node.value.rawValue;
54040
+ } else {
54041
+ value = src.slice(node.value.range.start.offset, node.value.range.end.offset).trim();
54042
+ }
54043
+ const reversed = node.reversed ? "R " : "";
54044
+ return cardinalityPrefix + reversed + name + " " + compOp + " " + value;
53481
54045
  }
53482
- function applyRefinementCommaBreaks(text, options) {
53483
- var _a;
53484
- const lines = text.split("\n");
53485
- const result = [];
53486
- let depth = 0;
53487
- let refinementIndent = null;
53488
- for (const line of lines) {
53489
- const lineIndent = ((_a = /^(\s*)/.exec(line)) == null ? void 0 : _a[1]) ?? "";
53490
- if (refinementIndent === null && depth === 0 && lineIndent.length > 0) {
53491
- refinementIndent = lineIndent;
53492
- }
53493
- let commaIndent;
53494
- if (depth === 0 && refinementIndent) {
53495
- commaIndent = refinementIndent;
53496
- } else if (lineIndent.length > 0) {
53497
- commaIndent = lineIndent;
53498
- } else {
53499
- commaIndent = getIndentString(1, options);
53500
- }
53501
- let output = "";
54046
+ function printConceptReference(node) {
54047
+ return node.conceptId;
54048
+ }
54049
+ function normaliseAst(ast, sourceText) {
54050
+ return normaliseExpression(ast, sourceText);
54051
+ }
54052
+ function normaliseExpression(node, src) {
54053
+ const inner = node.expression;
54054
+ let normalised;
54055
+ switch (inner.type) {
54056
+ case NodeType.SubExpressionConstraint:
54057
+ normalised = normaliseSubExpression(inner, src);
54058
+ break;
54059
+ case NodeType.CompoundExpression:
54060
+ normalised = normaliseCompoundExpression(inner, src);
54061
+ break;
54062
+ case NodeType.RefinedExpression:
54063
+ normalised = normaliseRefinedExpression(inner, src);
54064
+ break;
54065
+ case NodeType.DottedExpression:
54066
+ normalised = normaliseDottedExpression(inner, src);
54067
+ break;
54068
+ default: {
54069
+ const _exhaustive = inner;
54070
+ normalised = _exhaustive;
54071
+ }
54072
+ }
54073
+ return { ...node, expression: normalised };
54074
+ }
54075
+ function normaliseSubExpression(node, src) {
54076
+ let focus;
54077
+ switch (node.focus.type) {
54078
+ case NodeType.ConceptReference:
54079
+ focus = stripTerm(node.focus);
54080
+ break;
54081
+ case NodeType.Wildcard:
54082
+ focus = { ...node.focus };
54083
+ break;
54084
+ case NodeType.ExpressionConstraint:
54085
+ focus = normaliseExpression(node.focus, src);
54086
+ break;
54087
+ }
54088
+ return {
54089
+ ...node,
54090
+ operator: node.operator ? { ...node.operator } : void 0,
54091
+ focus,
54092
+ filters: node.filters ? node.filters.map(copyFilter) : void 0,
54093
+ historySupplement: node.historySupplement ? { ...node.historySupplement } : void 0
54094
+ };
54095
+ }
54096
+ function normaliseCompoundExpression(node, src) {
54097
+ const op = node.operator.operator;
54098
+ let normOperands = node.operands.map((o) => normaliseSubExpression(o, src));
54099
+ if (op === "AND" || op === "OR") {
54100
+ normOperands = flattenSameOperator(normOperands, op, src);
54101
+ }
54102
+ if (op === "AND" || op === "OR") {
54103
+ normOperands.sort((a, b) => {
54104
+ const ka = printCanonical(a, src);
54105
+ const kb = printCanonical(b, src);
54106
+ return ka.localeCompare(kb);
54107
+ });
54108
+ }
54109
+ return {
54110
+ ...node,
54111
+ operator: { ...node.operator },
54112
+ operands: normOperands
54113
+ };
54114
+ }
54115
+ function flattenSameOperator(operands, operator, src) {
54116
+ const result = [];
54117
+ for (const operand of operands) {
54118
+ if (operand.focus.type === NodeType.ExpressionConstraint && !operand.operator && !operand.memberOf && !operand.filters && !operand.historySupplement) {
54119
+ const inner = operand.focus.expression;
54120
+ if (inner.type === NodeType.CompoundExpression && inner.operator.operator === operator) {
54121
+ const innerNorm = normaliseCompoundExpression(inner, src);
54122
+ result.push(...innerNorm.operands);
54123
+ continue;
54124
+ }
54125
+ }
54126
+ result.push(operand);
54127
+ }
54128
+ return result;
54129
+ }
54130
+ function normaliseRefinedExpression(node, src) {
54131
+ return {
54132
+ ...node,
54133
+ expression: normaliseSubExpression(node.expression, src),
54134
+ refinement: normaliseRefinement(node.refinement, src)
54135
+ };
54136
+ }
54137
+ function normaliseRefinement(node, src) {
54138
+ const content = node.content ? normaliseRefinementMember(node.content, src) : null;
54139
+ const attributes = [];
54140
+ collectAttributes(content, attributes);
54141
+ return { ...node, attributes, content };
54142
+ }
54143
+ function normaliseRefinementMember(node, src) {
54144
+ switch (node.type) {
54145
+ case NodeType.Attribute:
54146
+ return normaliseAttribute(node, src);
54147
+ case NodeType.AttributeGroup:
54148
+ return { ...node, content: normaliseRefinementMember(node.content, src) };
54149
+ case NodeType.AttributeSet: {
54150
+ const members = flattenSameOperatorMembers(node).map((m) => normaliseRefinementMember(m, src));
54151
+ members.sort((a, b) => compareRefinementMembers(a, b, src));
54152
+ return { ...node, conjunctionStyle: ",", members };
54153
+ }
54154
+ }
54155
+ }
54156
+ function flattenSameOperatorMembers(node) {
54157
+ const result = [];
54158
+ for (const member of node.members) {
54159
+ if (member.type === NodeType.AttributeSet && member.operator === node.operator) {
54160
+ result.push(...flattenSameOperatorMembers(member));
54161
+ } else {
54162
+ result.push(member);
54163
+ }
54164
+ }
54165
+ return result;
54166
+ }
54167
+ function collectAttributes(node, out) {
54168
+ if (!node) return;
54169
+ switch (node.type) {
54170
+ case NodeType.Attribute:
54171
+ out.push(node);
54172
+ break;
54173
+ case NodeType.AttributeGroup:
54174
+ collectAttributes(node.content, out);
54175
+ break;
54176
+ case NodeType.AttributeSet:
54177
+ for (const member of node.members) {
54178
+ collectAttributes(member, out);
54179
+ }
54180
+ break;
54181
+ }
54182
+ }
54183
+ function compareRefinementMembers(a, b, src) {
54184
+ if (a.type === NodeType.Attribute && b.type === NodeType.Attribute) {
54185
+ return compareAttributes(a, b, src);
54186
+ }
54187
+ if (a.type === NodeType.Attribute) return -1;
54188
+ if (b.type === NodeType.Attribute) return 1;
54189
+ return printRefinementMember(a, src).localeCompare(printRefinementMember(b, src));
54190
+ }
54191
+ function compareAttributes(a, b, src) {
54192
+ const aId = a.name.conceptId;
54193
+ const bId = b.name.conceptId;
54194
+ if (aId && bId) {
54195
+ const aBig = BigInt(aId);
54196
+ const bBig = BigInt(bId);
54197
+ if (aBig < bBig) return -1;
54198
+ if (aBig > bBig) return 1;
54199
+ return 0;
54200
+ }
54201
+ if (aId) return -1;
54202
+ if (bId) return 1;
54203
+ const aKey = a.name.expression ? printCanonical(a.name.expression, src) : "";
54204
+ const bKey = b.name.expression ? printCanonical(b.name.expression, src) : "";
54205
+ return aKey.localeCompare(bKey);
54206
+ }
54207
+ function normaliseAttribute(node, src) {
54208
+ return {
54209
+ ...node,
54210
+ name: normaliseAttributeName(node.name, src),
54211
+ value: normaliseAttributeValue(node.value, src)
54212
+ };
54213
+ }
54214
+ function normaliseAttributeName(node, src) {
54215
+ return {
54216
+ ...node,
54217
+ term: void 0,
54218
+ // §5.1: strip display terms
54219
+ expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
54220
+ };
54221
+ }
54222
+ function normaliseAttributeValue(node, src) {
54223
+ return {
54224
+ ...node,
54225
+ expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
54226
+ };
54227
+ }
54228
+ function normaliseDottedExpression(node, src) {
54229
+ return {
54230
+ ...node,
54231
+ source: normaliseSubExpression(node.source, src),
54232
+ attributes: node.attributes.map(
54233
+ (a) => ({
54234
+ ...a,
54235
+ attributeName: normaliseSubExpression(a.attributeName, src)
54236
+ })
54237
+ )
54238
+ };
54239
+ }
54240
+ function stripTerm(node) {
54241
+ return { ...node, term: void 0 };
54242
+ }
54243
+ function copyFilter(node) {
54244
+ return { ...node };
54245
+ }
54246
+ function structuralSignature(ast, sourceText) {
54247
+ return printCanonical(normaliseAst(ast, sourceText), sourceText);
54248
+ }
54249
+ function signatureOf(text) {
54250
+ try {
54251
+ const { ast, errors: errors2 } = parseECL(text);
54252
+ if (!ast || errors2.length > 0) {
54253
+ return null;
54254
+ }
54255
+ return structuralSignature(ast, text);
54256
+ } catch {
54257
+ return null;
54258
+ }
54259
+ }
54260
+ function splitExpressions(text) {
54261
+ const delimiter = "/* ECL-END */";
54262
+ const delimiterPositions = [];
54263
+ let i = 0;
54264
+ while (i < text.length) {
54265
+ if (text[i] === "/" && i + 1 < text.length && text[i + 1] === "/") {
54266
+ while (i < text.length && text[i] !== "\n") i++;
54267
+ continue;
54268
+ }
54269
+ if (text.startsWith(delimiter, i)) {
54270
+ delimiterPositions.push(i);
54271
+ i += delimiter.length;
54272
+ continue;
54273
+ }
54274
+ i++;
54275
+ }
54276
+ if (delimiterPositions.length === 0) {
54277
+ return { expressions: [text], hasDelimiters: false };
54278
+ }
54279
+ const parts = [];
54280
+ let lastEnd = 0;
54281
+ for (const pos of delimiterPositions) {
54282
+ parts.push(text.substring(lastEnd, pos));
54283
+ lastEnd = pos + delimiter.length;
54284
+ }
54285
+ parts.push(text.substring(lastEnd));
54286
+ const expressions = parts.map((p) => p.trim()).filter((p) => p.length > 0);
54287
+ return { expressions, hasDelimiters: true };
54288
+ }
54289
+ function joinExpressions(expressions) {
54290
+ return expressions.join("\n\n/* ECL-END */\n\n");
54291
+ }
54292
+ function isCommentOrBlankLine(line) {
54293
+ const trimmed = line.trim();
54294
+ if (!trimmed) return true;
54295
+ if (trimmed.startsWith("//")) return true;
54296
+ const stripped = trimmed.replace(/\/\*[^]*?\*\//g, "").trim();
54297
+ return stripped.length === 0;
54298
+ }
54299
+ function maybeWrapCommentLine(line, options) {
54300
+ if (!options.wrapComments || options.maxLineLength <= 0) return line;
54301
+ if (line.length <= options.maxLineLength) return line;
54302
+ const match = /^(\s*\/\/\s?)(.*)/.exec(line);
54303
+ if (!match) return line;
54304
+ const prefix = match[1];
54305
+ const words = match[2].split(" ");
54306
+ const lines = [];
54307
+ let current = prefix;
54308
+ for (const word of words) {
54309
+ if (current.length + word.length + 1 > options.maxLineLength && current.trim() !== prefix.trim()) {
54310
+ lines.push(current.trimEnd());
54311
+ current = prefix + word;
54312
+ } else {
54313
+ current = current === prefix ? prefix + word : current + " " + word;
54314
+ }
54315
+ }
54316
+ if (current.trim()) lines.push(current.trimEnd());
54317
+ return lines.join("\n");
54318
+ }
54319
+ function maybeWrapCommentBlock(text, options) {
54320
+ if (!options.wrapComments) return text;
54321
+ return text.split("\n").map((line) => maybeWrapCommentLine(line, options)).join("\n");
54322
+ }
54323
+ function formatExpression(text, options, ast) {
54324
+ const lines = text.split("\n");
54325
+ let firstCodeLine = -1;
54326
+ let lastCodeLine = -1;
54327
+ for (let i = 0; i < lines.length; i++) {
54328
+ if (!isCommentOrBlankLine(lines[i])) {
54329
+ if (firstCodeLine === -1) firstCodeLine = i;
54330
+ lastCodeLine = i;
54331
+ }
54332
+ }
54333
+ if (firstCodeLine === -1) {
54334
+ return text;
54335
+ }
54336
+ const leadingRaw = firstCodeLine > 0 ? lines.slice(0, firstCodeLine).join("\n") + "\n" : "";
54337
+ const trailingRaw = lastCodeLine < lines.length - 1 ? "\n" + lines.slice(lastCodeLine + 1).join("\n") : "";
54338
+ const bodyText = lines.slice(firstCodeLine, lastCodeLine + 1).join("\n");
54339
+ const leadingText = maybeWrapCommentBlock(leadingRaw, options);
54340
+ const trailingText = maybeWrapCommentBlock(trailingRaw, options);
54341
+ const formattedBody = formatExpressionBody(bodyText, options, ast);
54342
+ return leadingText + formattedBody + trailingText;
54343
+ }
54344
+ function applyRefinementCommaBreaks(text, options) {
54345
+ var _a;
54346
+ const lines = text.split("\n");
54347
+ const result = [];
54348
+ let depth = 0;
54349
+ let refinementIndent = null;
54350
+ for (const line of lines) {
54351
+ const lineIndent = ((_a = /^(\s*)/.exec(line)) == null ? void 0 : _a[1]) ?? "";
54352
+ if (refinementIndent === null && depth === 0 && lineIndent.length > 0) {
54353
+ refinementIndent = lineIndent;
54354
+ }
54355
+ let commaIndent;
54356
+ if (depth === 0 && refinementIndent) {
54357
+ commaIndent = refinementIndent;
54358
+ } else if (lineIndent.length > 0) {
54359
+ commaIndent = lineIndent;
54360
+ } else {
54361
+ commaIndent = getIndentString(1, options);
54362
+ }
54363
+ let output = "";
53502
54364
  let inTerm = false;
53503
54365
  for (let i = 0; i < line.length; i++) {
53504
54366
  const ch = line[i];
@@ -53564,13 +54426,28 @@ function normalizeFilterBlocks(text) {
53564
54426
  return match.toLowerCase() === lower ? canonical : match;
53565
54427
  });
53566
54428
  }
53567
- normalized = normalized.replace(/\s*(!?=)\s*/g, " $1 ");
54429
+ normalized = normalized.replace(/\s*(!=|>=|<=)\s*/g, " $1 ");
54430
+ normalized = normalized.replace(new RegExp("\\s*(?<![!<>])=\\s*", "g"), " = ");
53568
54431
  normalized = normalized.replace(/,\s*/g, ", ");
53569
54432
  normalized = normalized.replace(/ {2,}/g, " ");
53570
54433
  normalized = normalized.replace(/^\s*/, " ").replace(/\s*$/, " ");
53571
54434
  return "{{" + normalized + "}}";
53572
54435
  });
53573
54436
  }
54437
+ function applyAstPrinter(normalizedText, options) {
54438
+ try {
54439
+ const reParsed = parseECL(normalizedText);
54440
+ const coversAll = reParsed.ast && reParsed.errors.length === 0 && reParsed.ast.range.end.offset >= normalizedText.trimEnd().length;
54441
+ if (!coversAll || !reParsed.ast) {
54442
+ return normalizedText;
54443
+ }
54444
+ const before = structuralSignature(reParsed.ast, normalizedText);
54445
+ const printed = printAst(reParsed.ast, normalizedText, options);
54446
+ return signatureOf(printed) === before ? printed : normalizedText;
54447
+ } catch {
54448
+ return normalizedText;
54449
+ }
54450
+ }
53574
54451
  function formatExpressionBody(text, options, ast) {
53575
54452
  const { comments, textWithoutComments } = extractComments(text);
53576
54453
  const nonDelimiterComments = comments.filter((c) => c.content.trim() !== "/* ECL-END */");
@@ -53578,9 +54455,9 @@ function formatExpressionBody(text, options, ast) {
53578
54455
  formatted = formatted.replace(
53579
54456
  // eslint-disable-next-line sonarjs/slow-regex -- bounded ECL expression text; no ReDoS risk
53580
54457
  new RegExp("(\\S?)(?<![A-Za-z])\\s*(AND|OR|MINUS)\\s*(?![A-Za-z])(\\S?)", "g"),
53581
- (match, before, op, after) => {
53582
- const formattedOp = options.spaceAroundOperators ? ` ${op} ` : op;
53583
- return (before ?? "") + formattedOp + (after ?? "");
54458
+ (_match, before, op, after) => {
54459
+ const formattedOp = ` ${op} `;
54460
+ return before + formattedOp + after;
53584
54461
  }
53585
54462
  );
53586
54463
  formatted = formatted.replace(/[ \t]*(:)[ \t]*/g, formatRefinementColon("$1"));
@@ -53588,23 +54465,21 @@ function formatExpressionBody(text, options, ast) {
53588
54465
  formatted = formatted.replace(new RegExp("[ \\t]*(?<![!<>])(=)[ \\t]*", "g"), formatRefinementEquals("$1"));
53589
54466
  formatted = formatted.replace(/(<<|<|>>|>)\s*(\d)/g, "$1 $2");
53590
54467
  formatted = formatted.replace(/(\d)\s+(\|)/g, "$1$2");
53591
- formatted = formatted.replace(/\|([^|]+)\|/g, (match, content) => {
54468
+ formatted = formatted.replace(/\|([^|]+)\|/g, (_match, content) => {
53592
54469
  return normalizeTerm(content);
53593
54470
  });
53594
54471
  if (ast) {
53595
- try {
53596
- const reParsed = parseECL(formatted);
53597
- const astCoversAll = reParsed.ast && reParsed.errors.length === 0 && reParsed.ast.range.end.offset >= formatted.trimEnd().length;
53598
- if (astCoversAll && reParsed.ast) {
53599
- formatted = printAst(reParsed.ast, formatted, options);
53600
- } else {
53601
- }
53602
- } catch {
53603
- }
54472
+ formatted = applyAstPrinter(formatted, options);
53604
54473
  }
53605
54474
  if (options.breakOnRefinementComma) {
53606
54475
  formatted = applyRefinementCommaBreaks(formatted, options);
53607
54476
  }
54477
+ {
54478
+ const baseline = signatureOf(normalizeFilterBlocks(textWithoutComments));
54479
+ if (baseline !== null && signatureOf(formatted) !== baseline) {
54480
+ formatted = textWithoutComments;
54481
+ }
54482
+ }
53608
54483
  const withComments = reinsertComments(formatted.trim(), text, nonDelimiterComments);
53609
54484
  return withComments;
53610
54485
  }
@@ -55826,62 +56701,45 @@ const eclTokenTypes = [
55826
56701
  // 8 — history supplement keywords
55827
56702
  ];
55828
56703
  const eclTokenModifiers = [];
55829
- const NT = {
55830
- ExpressionConstraint: "ExpressionConstraint",
55831
- SubExpressionConstraint: "SubExpressionConstraint",
55832
- CompoundExpression: "CompoundExpression",
55833
- RefinedExpression: "RefinedExpression",
55834
- DottedExpression: "DottedExpression",
55835
- DottedAttribute: "DottedAttribute",
55836
- Refinement: "Refinement",
55837
- Attribute: "Attribute",
55838
- FilterConstraint: "FilterConstraint",
55839
- HistorySupplement: "HistorySupplement"
55840
- };
55841
56704
  function collectAttributeNamePositions(ast, lineOffsets) {
55842
56705
  const positions = /* @__PURE__ */ new Set();
55843
56706
  function visit(node) {
55844
- var _a;
55845
- if (!(node == null ? void 0 : node.type)) return;
56707
+ if (!node) return;
55846
56708
  switch (node.type) {
55847
- case NT.ExpressionConstraint:
55848
- if (node.expression) visit(node.expression);
56709
+ case NodeType.ExpressionConstraint:
56710
+ visit(node.expression);
55849
56711
  break;
55850
- case NT.SubExpressionConstraint:
55851
- if (node.focus) visit(node.focus);
55852
- if (node.filters) {
55853
- for (const f of node.filters) visit(f);
55854
- }
55855
- if (node.historySupplement) visit(node.historySupplement);
56712
+ case NodeType.SubExpressionConstraint:
56713
+ visit(node.focus);
56714
+ for (const f of node.filters ?? []) visit(f);
56715
+ visit(node.historySupplement);
55856
56716
  break;
55857
- case NT.CompoundExpression:
56717
+ case NodeType.CompoundExpression:
55858
56718
  for (const op of node.operands) visit(op);
55859
56719
  break;
55860
- case NT.RefinedExpression:
56720
+ case NodeType.RefinedExpression:
55861
56721
  visit(node.expression);
55862
56722
  visit(node.refinement);
55863
56723
  break;
55864
- case NT.DottedExpression:
56724
+ case NodeType.DottedExpression:
55865
56725
  visit(node.source);
55866
56726
  for (const attr of node.attributes) visit(attr);
55867
56727
  break;
55868
- case NT.DottedAttribute:
55869
- if (node.attributeName) {
55870
- markSubExpressionAsAttrName(node.attributeName, lineOffsets, positions);
55871
- }
56728
+ case NodeType.DottedAttribute:
56729
+ markSubExpressionAsAttrName(node.attributeName, lineOffsets, positions);
55872
56730
  break;
55873
- case NT.Refinement:
56731
+ case NodeType.Refinement:
55874
56732
  for (const attr of node.attributes) visit(attr);
55875
56733
  break;
55876
- case NT.Attribute:
56734
+ case NodeType.Attribute:
55877
56735
  markAttributeName(node.name, lineOffsets, positions);
55878
- if ((_a = node.value) == null ? void 0 : _a.expression) visit(node.value.expression);
56736
+ visit(node.value.expression);
55879
56737
  break;
55880
- case NT.FilterConstraint:
56738
+ case NodeType.FilterConstraint:
55881
56739
  for (const ce of node.conceptExpressions) visit(ce);
55882
56740
  break;
55883
- case NT.HistorySupplement:
55884
- if (node.subsetExpression) visit(node.subsetExpression);
56741
+ case NodeType.HistorySupplement:
56742
+ visit(node.subsetExpression);
55885
56743
  break;
55886
56744
  }
55887
56745
  }
@@ -56115,275 +56973,6 @@ function isInsideFilterBlock(ranges, matchStart, matchEnd) {
56115
56973
  }
56116
56974
  return false;
56117
56975
  }
56118
- function printCanonical(ast, sourceText, outerOperator) {
56119
- if (ast.type === NodeType.SubExpressionConstraint) {
56120
- return printSubExpression(ast, sourceText, outerOperator);
56121
- }
56122
- return printExpression(ast, sourceText, outerOperator);
56123
- }
56124
- function printExpression(node, src, outerOperator) {
56125
- const inner = node.expression;
56126
- switch (inner.type) {
56127
- case NodeType.SubExpressionConstraint:
56128
- return printSubExpression(inner, src, outerOperator);
56129
- case NodeType.CompoundExpression:
56130
- return printCompoundExpression(inner, src);
56131
- case NodeType.RefinedExpression:
56132
- return printRefinedExpression(inner, src);
56133
- case NodeType.DottedExpression:
56134
- return printDottedExpression(inner, src);
56135
- default: {
56136
- const _exhaustive = inner;
56137
- return String(_exhaustive);
56138
- }
56139
- }
56140
- }
56141
- function printSubExpression(node, src, outerOperator) {
56142
- let result = "";
56143
- if (node.operator) {
56144
- result += node.operator.operator;
56145
- }
56146
- if (node.memberOf) {
56147
- result += "^";
56148
- }
56149
- switch (node.focus.type) {
56150
- case NodeType.ConceptReference:
56151
- result += printConceptReference(node.focus);
56152
- break;
56153
- case NodeType.Wildcard:
56154
- result += "*";
56155
- break;
56156
- case NodeType.ExpressionConstraint: {
56157
- const innerExpr = node.focus.expression;
56158
- if (innerExpr.type !== NodeType.CompoundExpression) {
56159
- result += printExpression(node.focus, src, outerOperator);
56160
- } else if (outerOperator && innerExpr.operator.operator === outerOperator) {
56161
- result += printExpression(node.focus, src, outerOperator);
56162
- } else {
56163
- result += "(" + printExpression(node.focus, src) + ")";
56164
- }
56165
- break;
56166
- }
56167
- }
56168
- if (node.filters) {
56169
- for (const filter of node.filters) {
56170
- const filterText = src.slice(filter.range.start.offset, filter.range.end.offset);
56171
- result += " " + filterText.replaceAll(/\s+/g, " ").trim();
56172
- }
56173
- }
56174
- if (node.historySupplement) {
56175
- const histText = src.slice(node.historySupplement.range.start.offset, node.historySupplement.range.end.offset);
56176
- result += " " + histText.replaceAll(/\s+/g, " ").trim();
56177
- }
56178
- return result;
56179
- }
56180
- function printCompoundExpression(node, src) {
56181
- const op = node.operator.operator;
56182
- return node.operands.map((operand) => printSubExpression(operand, src, op)).join(` ${op} `);
56183
- }
56184
- function printRefinedExpression(node, src) {
56185
- const focus = printSubExpression(node.expression, src);
56186
- const refinement = printRefinement(node.refinement, src);
56187
- return focus + ":" + refinement;
56188
- }
56189
- function printDottedExpression(node, src) {
56190
- const source = printSubExpression(node.source, src);
56191
- const dots = node.attributes.map((a) => printSubExpression(a.attributeName, src));
56192
- return source + dots.map((d) => "." + d).join("");
56193
- }
56194
- function printRefinement(node, src) {
56195
- const parts = [];
56196
- let prevEnd = node.range.start.offset;
56197
- for (const attr of node.attributes) {
56198
- const printed = printAttribute(attr, src);
56199
- const inBraces = isAttrInBraceGroup(attr, prevEnd, src);
56200
- parts.push(inBraces ? "{" + printed + "}" : printed);
56201
- prevEnd = attr.range.end.offset;
56202
- }
56203
- return parts.join(",");
56204
- }
56205
- function isAttrInBraceGroup(attr, prevEnd, src) {
56206
- const gap = src.slice(prevEnd, attr.range.start.offset);
56207
- return gap.includes("{");
56208
- }
56209
- function printAttribute(node, src) {
56210
- const preNameSrc = src.slice(node.range.start.offset, node.name.range.start.offset).trim();
56211
- const cardinalityRaw = preNameSrc.replace(/^\{?\s*/, "").trim();
56212
- const cardinalityPrefix = cardinalityRaw.length > 0 ? cardinalityRaw + " " : "";
56213
- let name;
56214
- if (node.name.conceptId) {
56215
- name = node.name.conceptId;
56216
- } else if (node.name.expression) {
56217
- name = printSubExpression(node.name.expression, src);
56218
- } else {
56219
- name = src.slice(node.name.range.start.offset, node.name.range.end.offset).trim();
56220
- }
56221
- const between = src.slice(node.name.range.end.offset, node.value.range.start.offset);
56222
- const opMatch = /(!?=|[<>]=)/.exec(between);
56223
- const compOp = opMatch ? opMatch[1] : "=";
56224
- const hasHashPrefix = between.includes("#");
56225
- let value;
56226
- if (node.value.expression) {
56227
- value = printSubExpression(node.value.expression, src);
56228
- } else if (node.value.rawValue) {
56229
- value = hasHashPrefix ? "#" + node.value.rawValue : node.value.rawValue;
56230
- } else {
56231
- value = src.slice(node.value.range.start.offset, node.value.range.end.offset).trim();
56232
- }
56233
- const reversed = node.reversed ? "R " : "";
56234
- return cardinalityPrefix + reversed + name + " " + compOp + " " + value;
56235
- }
56236
- function printConceptReference(node) {
56237
- return node.conceptId;
56238
- }
56239
- function normaliseAst(ast, sourceText) {
56240
- return normaliseExpression(ast, sourceText);
56241
- }
56242
- function normaliseExpression(node, src) {
56243
- const inner = node.expression;
56244
- let normalised;
56245
- switch (inner.type) {
56246
- case NodeType.SubExpressionConstraint:
56247
- normalised = normaliseSubExpression(inner, src);
56248
- break;
56249
- case NodeType.CompoundExpression:
56250
- normalised = normaliseCompoundExpression(inner, src);
56251
- break;
56252
- case NodeType.RefinedExpression:
56253
- normalised = normaliseRefinedExpression(inner, src);
56254
- break;
56255
- case NodeType.DottedExpression:
56256
- normalised = normaliseDottedExpression(inner, src);
56257
- break;
56258
- default: {
56259
- const _exhaustive = inner;
56260
- normalised = _exhaustive;
56261
- }
56262
- }
56263
- return { ...node, expression: normalised };
56264
- }
56265
- function normaliseSubExpression(node, src) {
56266
- let focus;
56267
- switch (node.focus.type) {
56268
- case NodeType.ConceptReference:
56269
- focus = stripTerm(node.focus);
56270
- break;
56271
- case NodeType.Wildcard:
56272
- focus = { ...node.focus };
56273
- break;
56274
- case NodeType.ExpressionConstraint:
56275
- focus = normaliseExpression(node.focus, src);
56276
- break;
56277
- }
56278
- return {
56279
- ...node,
56280
- operator: node.operator ? { ...node.operator } : void 0,
56281
- focus,
56282
- filters: node.filters ? node.filters.map(copyFilter) : void 0,
56283
- historySupplement: node.historySupplement ? { ...node.historySupplement } : void 0
56284
- };
56285
- }
56286
- function normaliseCompoundExpression(node, src) {
56287
- const op = node.operator.operator;
56288
- let normOperands = node.operands.map((o) => normaliseSubExpression(o, src));
56289
- if (op === "AND" || op === "OR") {
56290
- normOperands = flattenSameOperator(normOperands, op, src);
56291
- }
56292
- if (op === "AND" || op === "OR") {
56293
- normOperands.sort((a, b) => {
56294
- const ka = printCanonical(a, src);
56295
- const kb = printCanonical(b, src);
56296
- return ka.localeCompare(kb);
56297
- });
56298
- }
56299
- return {
56300
- ...node,
56301
- operator: { ...node.operator },
56302
- operands: normOperands
56303
- };
56304
- }
56305
- function flattenSameOperator(operands, operator, src) {
56306
- const result = [];
56307
- for (const operand of operands) {
56308
- if (operand.focus.type === NodeType.ExpressionConstraint && !operand.operator && !operand.memberOf && !operand.filters && !operand.historySupplement) {
56309
- const inner = operand.focus.expression;
56310
- if (inner.type === NodeType.CompoundExpression && inner.operator.operator === operator) {
56311
- const innerNorm = normaliseCompoundExpression(inner, src);
56312
- result.push(...innerNorm.operands);
56313
- continue;
56314
- }
56315
- }
56316
- result.push(operand);
56317
- }
56318
- return result;
56319
- }
56320
- function normaliseRefinedExpression(node, src) {
56321
- return {
56322
- ...node,
56323
- expression: normaliseSubExpression(node.expression, src),
56324
- refinement: normaliseRefinement(node.refinement, src)
56325
- };
56326
- }
56327
- function normaliseRefinement(node, src) {
56328
- const normAttrs = node.attributes.map((a) => normaliseAttribute(a, src));
56329
- normAttrs.sort((a, b) => compareAttributes(a, b, src));
56330
- return { ...node, attributes: normAttrs };
56331
- }
56332
- function compareAttributes(a, b, src) {
56333
- const aId = a.name.conceptId;
56334
- const bId = b.name.conceptId;
56335
- if (aId && bId) {
56336
- const aBig = BigInt(aId);
56337
- const bBig = BigInt(bId);
56338
- if (aBig < bBig) return -1;
56339
- if (aBig > bBig) return 1;
56340
- return 0;
56341
- }
56342
- if (aId) return -1;
56343
- if (bId) return 1;
56344
- const aKey = a.name.expression ? printCanonical(a.name.expression, src) : "";
56345
- const bKey = b.name.expression ? printCanonical(b.name.expression, src) : "";
56346
- return aKey.localeCompare(bKey);
56347
- }
56348
- function normaliseAttribute(node, src) {
56349
- return {
56350
- ...node,
56351
- name: normaliseAttributeName(node.name, src),
56352
- value: normaliseAttributeValue(node.value, src)
56353
- };
56354
- }
56355
- function normaliseAttributeName(node, src) {
56356
- return {
56357
- ...node,
56358
- term: void 0,
56359
- // §5.1: strip display terms
56360
- expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
56361
- };
56362
- }
56363
- function normaliseAttributeValue(node, src) {
56364
- return {
56365
- ...node,
56366
- expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
56367
- };
56368
- }
56369
- function normaliseDottedExpression(node, src) {
56370
- return {
56371
- ...node,
56372
- source: normaliseSubExpression(node.source, src),
56373
- attributes: node.attributes.map(
56374
- (a) => ({
56375
- ...a,
56376
- attributeName: normaliseSubExpression(a.attributeName, src)
56377
- })
56378
- )
56379
- };
56380
- }
56381
- function stripTerm(node) {
56382
- return { ...node, term: void 0 };
56383
- }
56384
- function copyFilter(node) {
56385
- return { ...node };
56386
- }
56387
56976
  class CanonicaliseError extends Error {
56388
56977
  constructor(message, parseErrors) {
56389
56978
  super(message);
@@ -57429,6 +58018,9 @@ export {
57429
58018
  CanonicaliseError,
57430
58019
  FhirTerminologyService,
57431
58020
  REFACTORING_RESOLVE_KIND,
58021
+ TerminologyError,
58022
+ TerminologyHttpError,
58023
+ TerminologyTransportError,
57432
58024
  allArticles,
57433
58025
  analyzeExpression,
57434
58026
  buildReplacementText,
@@ -57466,6 +58058,10 @@ export {
57466
58058
  getValidOperatorsAtPosition,
57467
58059
  groupIntoExpressions,
57468
58060
  isConceptPositionValid,
58061
+ isEclEvaluationStrategy,
58062
+ isTerminologyError,
58063
+ isTerminologyHttpError,
58064
+ isTerminologyTransportError,
57469
58065
  isValidConceptId,
57470
58066
  isValidDescriptionId,
57471
58067
  isValidSnomedId,
@@ -57477,6 +58073,8 @@ export {
57477
58073
  refineParseError,
57478
58074
  resolveAddDisplayTerms,
57479
58075
  resolveUnifiedSimplify,
58076
+ toHttpError,
58077
+ toTransportError,
57480
58078
  validateBoolean,
57481
58079
  validateIndentSize,
57482
58080
  validateIndentStyle,