@aehrc/ecl-core 1.0.3 → 1.1.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.cjs CHANGED
@@ -52273,7 +52273,7 @@ function isValidDescriptionId(sctid) {
52273
52273
  }
52274
52274
  const DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
52275
52275
  const IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
52276
- class FhirTerminologyService {
52276
+ const _FhirTerminologyService = class _FhirTerminologyService {
52277
52277
  constructor(options = {}) {
52278
52278
  __publicField(this, "cache", /* @__PURE__ */ new Map());
52279
52279
  __publicField(this, "searchCache", /* @__PURE__ */ new Map());
@@ -52429,6 +52429,46 @@ class FhirTerminologyService {
52429
52429
  return null;
52430
52430
  }
52431
52431
  }
52432
+ async getHistoricalAssociations(conceptId) {
52433
+ const entries = Object.entries(_FhirTerminologyService.ASSOCIATION_REFSETS);
52434
+ const promises = entries.map(async ([refsetId, type2]) => {
52435
+ const targets = await this.translateAssociation(conceptId, refsetId);
52436
+ if (targets.length === 0) return null;
52437
+ return { type: type2, refsetId, targets };
52438
+ });
52439
+ const settled = await Promise.all(promises);
52440
+ const typeOrder = ["same-as", "replaced-by", "possibly-equivalent-to", "alternative"];
52441
+ return typeOrder.map((type2) => settled.find((a) => (a == null ? void 0 : a.type) === type2)).filter((a) => a !== null && a !== void 0);
52442
+ }
52443
+ /** Query a single implicit ConceptMap for historical association targets. */
52444
+ async translateAssociation(conceptId, refsetId) {
52445
+ try {
52446
+ const cmUrl = `${this.snomedSystemUrl}?fhir_cm=${refsetId}`;
52447
+ const targetUrl = "http://snomed.info/sct?fhir_vs";
52448
+ const url = `${this.baseUrl}/ConceptMap/$translate?code=${encodeURIComponent(conceptId)}&system=${encodeURIComponent("http://snomed.info/sct")}&target=${encodeURIComponent(targetUrl)}&url=${encodeURIComponent(cmUrl)}`;
52449
+ const response = await this.fetchWithTimeout(url, this.timeout, {
52450
+ headers: { Accept: "application/fhir+json" }
52451
+ });
52452
+ if (!response.ok) return [];
52453
+ const data = await response.json();
52454
+ const params = data.parameter ?? [];
52455
+ const resultParam = params.find((p) => p.name === "result");
52456
+ if ((resultParam == null ? void 0 : resultParam.valueBoolean) !== true) return [];
52457
+ const targets = [];
52458
+ for (const param of params) {
52459
+ if (param.name !== "match") continue;
52460
+ const parts = param.part ?? [];
52461
+ const conceptPart = parts.find((p) => p.name === "concept");
52462
+ const coding = conceptPart == null ? void 0 : conceptPart.valueCoding;
52463
+ if (coding == null ? void 0 : coding.code) {
52464
+ targets.push({ code: coding.code, display: coding.display ?? "" });
52465
+ }
52466
+ }
52467
+ return targets;
52468
+ } catch {
52469
+ return [];
52470
+ }
52471
+ }
52432
52472
  async validateConcepts(conceptIds) {
52433
52473
  const results = /* @__PURE__ */ new Map();
52434
52474
  if (conceptIds.length === 0) {
@@ -52678,7 +52718,15 @@ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by
52678
52718
  }
52679
52719
  return editions;
52680
52720
  }
52681
- }
52721
+ };
52722
+ /** Map of SNOMED CT historical association reference set IDs to association types. */
52723
+ __publicField(_FhirTerminologyService, "ASSOCIATION_REFSETS", {
52724
+ "900000000000527005": "same-as",
52725
+ "900000000000526001": "replaced-by",
52726
+ "900000000000523009": "possibly-equivalent-to",
52727
+ "900000000000530003": "alternative"
52728
+ });
52729
+ let FhirTerminologyService = _FhirTerminologyService;
52682
52730
  function getSymbolText(sym) {
52683
52731
  if (typeof sym === "string") return sym;
52684
52732
  if (sym && typeof sym === "object" && "text" in sym) {
@@ -53146,26 +53194,26 @@ function printAst(ast, sourceText, options) {
53146
53194
  if (!ast) {
53147
53195
  return "";
53148
53196
  }
53149
- return printExpression(ast, 0, 0, options, sourceText);
53197
+ return printExpression$1(ast, 0, 0, options, sourceText);
53150
53198
  }
53151
- function printExpression(node, depth, column, opts, src) {
53199
+ function printExpression$1(node, depth, column, opts, src) {
53152
53200
  const inner = node.expression;
53153
53201
  switch (inner.type) {
53154
53202
  case NodeType.SubExpressionConstraint:
53155
- return printSubExpression(inner, depth, column, opts, src);
53203
+ return printSubExpression$1(inner, depth, column, opts, src);
53156
53204
  case NodeType.CompoundExpression:
53157
- return printCompoundExpression(inner, depth, column, opts, src);
53205
+ return printCompoundExpression$1(inner, depth, column, opts, src);
53158
53206
  case NodeType.RefinedExpression:
53159
- return printRefinedExpression(inner, depth, column, opts, src);
53207
+ return printRefinedExpression$1(inner, depth, column, opts, src);
53160
53208
  case NodeType.DottedExpression:
53161
- return printDottedExpression(inner, depth, column, opts, src);
53209
+ return printDottedExpression$1(inner, depth, column, opts, src);
53162
53210
  default: {
53163
53211
  const _exhaustive = inner;
53164
53212
  return String(_exhaustive);
53165
53213
  }
53166
53214
  }
53167
53215
  }
53168
- function printSubExpression(node, depth, column, opts, src) {
53216
+ function printSubExpression$1(node, depth, column, opts, src) {
53169
53217
  let result = "";
53170
53218
  if (node.operator) {
53171
53219
  result += node.operator.operator + " ";
@@ -53175,22 +53223,29 @@ function printSubExpression(node, depth, column, opts, src) {
53175
53223
  }
53176
53224
  switch (node.focus.type) {
53177
53225
  case NodeType.ConceptReference:
53178
- result += printConceptReference(node.focus);
53226
+ result += printConceptReference$1(node.focus);
53179
53227
  break;
53180
53228
  case NodeType.Wildcard:
53181
53229
  result += "*";
53182
53230
  break;
53183
53231
  case NodeType.ExpressionConstraint: {
53184
53232
  const innerExpr = node.focus;
53233
+ if (opts.removeRedundantParentheses && !node.operator && !node.memberOf) {
53234
+ const inner = innerExpr.expression;
53235
+ if (inner.type !== NodeType.CompoundExpression) {
53236
+ result += printExpression$1(innerExpr, depth, column + result.length, opts, src);
53237
+ break;
53238
+ }
53239
+ }
53185
53240
  const innerIsRefined = innerExpr.expression.type === NodeType.RefinedExpression;
53186
53241
  const innerDepth = innerIsRefined ? depth : depth + 1;
53187
53242
  const openCol = column + result.length;
53188
- const innerInline = printExpression(innerExpr, innerDepth, openCol + 1, opts, src);
53243
+ const innerInline = printExpression$1(innerExpr, innerDepth, openCol + 1, opts, src);
53189
53244
  if (!innerInline.includes("\n") && (opts.maxLineLength <= 0 || openCol + 1 + innerInline.length + 1 <= opts.maxLineLength)) {
53190
53245
  result += "(" + innerInline + ")";
53191
53246
  } else {
53192
53247
  const innerInd = getIndentString(innerDepth, opts);
53193
- const innerMulti = printExpression(innerExpr, innerDepth, innerInd.length, opts, src);
53248
+ const innerMulti = printExpression$1(innerExpr, innerDepth, innerInd.length, opts, src);
53194
53249
  result += "(" + innerMulti + ")";
53195
53250
  }
53196
53251
  break;
@@ -53208,10 +53263,14 @@ function printSubExpression(node, depth, column, opts, src) {
53208
53263
  }
53209
53264
  return result;
53210
53265
  }
53211
- function printCompoundExpression(node, depth, column, opts, src) {
53266
+ function printCompoundExpression$1(node, depth, column, opts, src) {
53212
53267
  const op = node.operator.operator;
53213
53268
  const opSep = opts.spaceAroundOperators ? ` ${op} ` : op;
53214
- const printed = node.operands.map((operand) => printSubExpression(operand, depth, 0, opts, src));
53269
+ let operands = node.operands;
53270
+ if (opts.removeRedundantParentheses && (op === "AND" || op === "OR")) {
53271
+ operands = flattenSameOperatorOperands(operands, op);
53272
+ }
53273
+ const printed = operands.map((operand) => printSubExpression$1(operand, depth, 0, opts, src));
53215
53274
  const inline = printed.join(opSep);
53216
53275
  const fits = opts.maxLineLength <= 0 || column + inline.length <= opts.maxLineLength;
53217
53276
  if (fits && !opts.breakOnOperators) {
@@ -53230,9 +53289,23 @@ function printCompoundExpression(node, depth, column, opts, src) {
53230
53289
  }
53231
53290
  return lines.join("\n");
53232
53291
  }
53233
- function printDottedExpression(node, depth, column, opts, src) {
53234
- const source = printSubExpression(node.source, depth, column, opts, src);
53235
- const dotAttrs = node.attributes.map((a) => printSubExpression(a.attributeName, depth, 0, opts, src));
53292
+ function flattenSameOperatorOperands(operands, operator) {
53293
+ const result = [];
53294
+ for (const operand of operands) {
53295
+ if (operand.focus.type === NodeType.ExpressionConstraint && !operand.operator && !operand.memberOf && !operand.filters && !operand.historySupplement) {
53296
+ const inner = operand.focus.expression;
53297
+ if (inner.type === NodeType.CompoundExpression && inner.operator.operator === operator) {
53298
+ result.push(...flattenSameOperatorOperands(inner.operands, operator));
53299
+ continue;
53300
+ }
53301
+ }
53302
+ result.push(operand);
53303
+ }
53304
+ return result;
53305
+ }
53306
+ function printDottedExpression$1(node, depth, column, opts, src) {
53307
+ const source = printSubExpression$1(node.source, depth, column, opts, src);
53308
+ const dotAttrs = node.attributes.map((a) => printSubExpression$1(a.attributeName, depth, 0, opts, src));
53236
53309
  const inline = source + dotAttrs.map((a) => " . " + a).join("");
53237
53310
  if (opts.maxLineLength <= 0 || column + inline.length <= opts.maxLineLength) {
53238
53311
  return inline;
@@ -53244,9 +53317,9 @@ function printDottedExpression(node, depth, column, opts, src) {
53244
53317
  }
53245
53318
  return lines.join("\n");
53246
53319
  }
53247
- function printRefinedExpression(node, depth, column, opts, src) {
53248
- const focus = printSubExpression(node.expression, depth, column, opts, src);
53249
- const refinement = printRefinement(node.refinement, depth + 1, opts, src);
53320
+ function printRefinedExpression$1(node, depth, column, opts, src) {
53321
+ const focus = printSubExpression$1(node.expression, depth, column, opts, src);
53322
+ const refinement = printRefinement$1(node.refinement, depth + 1, opts, src);
53250
53323
  const inline = focus + ": " + refinement;
53251
53324
  const inlineEndCol = focus.includes("\n") ? lastLineLength(inline) : column + inline.length;
53252
53325
  const fits = opts.maxLineLength <= 0 || inlineEndCol <= opts.maxLineLength;
@@ -53260,42 +53333,42 @@ function printRefinedExpression(node, depth, column, opts, src) {
53260
53333
  const wholeBraces = refSrc.startsWith("{");
53261
53334
  if (wholeBraces) {
53262
53335
  const innerInd = getIndentString(attrDepth + 1, opts);
53263
- const attrs = node.refinement.attributes.map((a) => printAttribute(a, attrDepth + 1, innerInd.length, opts, src));
53336
+ const attrs = node.refinement.attributes.map((a) => printAttribute$1(a, attrDepth + 1, innerInd.length, opts, src));
53264
53337
  return focus + ":\n" + ind + "{\n" + attrs.map((a) => innerInd + a).join(",\n") + "\n" + ind + "}";
53265
53338
  }
53266
53339
  const attrParts = [];
53267
53340
  let prevEnd = node.refinement.range.start.offset;
53268
53341
  for (const attr of node.refinement.attributes) {
53269
- const printed = printAttribute(attr, attrDepth, ind.length, opts, src);
53270
- const inBraces = isAttrInBraceGroup(attr, prevEnd, src);
53342
+ const printed = printAttribute$1(attr, attrDepth, ind.length, opts, src);
53343
+ const inBraces = isAttrInBraceGroup$1(attr, prevEnd, src);
53271
53344
  attrParts.push(ind + (inBraces ? "{ " + printed + " }" : printed));
53272
53345
  prevEnd = attr.range.end.offset;
53273
53346
  }
53274
53347
  return focus + ":\n" + attrParts.join(",\n");
53275
53348
  }
53276
- function isAttrInBraceGroup(attr, prevEnd, src) {
53349
+ function isAttrInBraceGroup$1(attr, prevEnd, src) {
53277
53350
  const gap = src.slice(prevEnd, attr.range.start.offset);
53278
53351
  return gap.includes("{");
53279
53352
  }
53280
- function printRefinement(node, depth, opts, src) {
53353
+ function printRefinement$1(node, depth, opts, src) {
53281
53354
  const parts = [];
53282
53355
  let prevEnd = node.range.start.offset;
53283
53356
  for (const attr of node.attributes) {
53284
- const printed = printAttribute(attr, depth, 0, opts, src);
53285
- const inBraces = isAttrInBraceGroup(attr, prevEnd, src);
53357
+ const printed = printAttribute$1(attr, depth, 0, opts, src);
53358
+ const inBraces = isAttrInBraceGroup$1(attr, prevEnd, src);
53286
53359
  parts.push(inBraces ? "{ " + printed + " }" : printed);
53287
53360
  prevEnd = attr.range.end.offset;
53288
53361
  }
53289
53362
  return parts.join(", ");
53290
53363
  }
53291
- function printAttribute(node, depth, column, opts, src) {
53364
+ function printAttribute$1(node, depth, column, opts, src) {
53292
53365
  const preNameSrc = src.slice(node.range.start.offset, node.name.range.start.offset).trim();
53293
53366
  const cardinalityPrefix = preNameSrc.length > 0 ? preNameSrc + " " : "";
53294
53367
  let name;
53295
53368
  if (node.name.conceptId) {
53296
53369
  name = node.name.term ? node.name.conceptId + normalizeTerm(node.name.term) : node.name.conceptId;
53297
53370
  } else if (node.name.expression) {
53298
- name = printSubExpression(node.name.expression, depth, column, opts, src);
53371
+ name = printSubExpression$1(node.name.expression, depth, column, opts, src);
53299
53372
  } else {
53300
53373
  name = src.slice(node.name.range.start.offset, node.name.range.end.offset);
53301
53374
  }
@@ -53305,7 +53378,7 @@ function printAttribute(node, depth, column, opts, src) {
53305
53378
  const hasHashPrefix = between.includes("#");
53306
53379
  let value;
53307
53380
  if (node.value.expression) {
53308
- value = printSubExpression(node.value.expression, depth, column + name.length + 3, opts, src);
53381
+ value = printSubExpression$1(node.value.expression, depth, column + name.length + 3, opts, src);
53309
53382
  } else if (node.value.rawValue) {
53310
53383
  value = hasHashPrefix ? "#" + node.value.rawValue : node.value.rawValue;
53311
53384
  } else {
@@ -53314,7 +53387,7 @@ function printAttribute(node, depth, column, opts, src) {
53314
53387
  const reversed = node.reversed ? "R " : "";
53315
53388
  return cardinalityPrefix + reversed + name + " " + compOp + " " + value;
53316
53389
  }
53317
- function printConceptReference(node) {
53390
+ function printConceptReference$1(node) {
53318
53391
  if (node.term) {
53319
53392
  return node.conceptId + normalizeTerm(node.term);
53320
53393
  }
@@ -53575,7 +53648,8 @@ const defaultFormattingOptions = {
53575
53648
  wrapComments: false,
53576
53649
  breakOnOperators: false,
53577
53650
  breakOnRefinementComma: false,
53578
- breakAfterColon: false
53651
+ breakAfterColon: false,
53652
+ removeRedundantParentheses: false
53579
53653
  };
53580
53654
  function expandToExpressionBoundaries(text, range2) {
53581
53655
  const startOffset = offsetAt(text, range2.start);
@@ -54724,6 +54798,31 @@ function getRefactoringActions(documentUri, documentText, range2) {
54724
54798
  return actions;
54725
54799
  }
54726
54800
  const REFACTORING_RESOLVE_KIND = "ecl.refactoring.resolve";
54801
+ function buildReplacementText(association) {
54802
+ const targets = association.targets;
54803
+ const typeLabel = association.type.replace(/-/g, " ");
54804
+ if (targets.length === 0) {
54805
+ return { replacement: "", label: `No targets for ${typeLabel}` };
54806
+ }
54807
+ if (association.type === "same-as" || association.type === "replaced-by") {
54808
+ const target = targets[0];
54809
+ const display = target.display ? ` |${target.display}|` : "";
54810
+ const replacement2 = target.code + display;
54811
+ return { replacement: replacement2, label: `Replace with ${typeLabel}: ${replacement2}` };
54812
+ }
54813
+ if (targets.length === 1) {
54814
+ const target = targets[0];
54815
+ const display = target.display ? ` |${target.display}|` : "";
54816
+ const replacement2 = target.code + display;
54817
+ return { replacement: replacement2, label: `Replace with ${typeLabel}: ${replacement2}` };
54818
+ }
54819
+ const parts = targets.map((t) => {
54820
+ const display = t.display ? ` |${t.display}|` : "";
54821
+ return t.code + display;
54822
+ });
54823
+ const replacement = "(" + parts.join(" OR ") + ")";
54824
+ return { replacement, label: `Replace with ${typeLabel}: ${replacement}` };
54825
+ }
54727
54826
  const eclSnippetCompletions = [
54728
54827
  {
54729
54828
  label: "Descendant of",
@@ -55643,28 +55742,31 @@ async function getCompletionItemsWithSearch(inExpression, textBeforeCursor, curr
55643
55742
  if (!inExpression || !terminologyService) {
55644
55743
  return baseItems;
55645
55744
  }
55646
- const filterCtx = detectFilterContext(textBeforeCursor);
55647
- if ((filterCtx == null ? void 0 : filterCtx.kind) === "filter-block") {
55648
- const sub = filterCtx.subContext;
55649
- if (typeof sub === "object" && sub.keyword) {
55650
- const keyword = sub.keyword.toLowerCase();
55651
- if (keyword in FILTER_ECL_CONSTRAINTS) {
55652
- const fhirItems = await getFhirFilterCompletions(keyword, terminologyService);
55653
- if (fhirItems.length > 0) {
55654
- const staticCodes = new Set(
55655
- baseItems.map((item) => {
55745
+ try {
55746
+ const filterCtx = detectFilterContext(textBeforeCursor);
55747
+ if ((filterCtx == null ? void 0 : filterCtx.kind) === "filter-block") {
55748
+ const sub = filterCtx.subContext;
55749
+ if (typeof sub === "object" && sub.keyword) {
55750
+ const keyword = sub.keyword.toLowerCase();
55751
+ if (keyword in FILTER_ECL_CONSTRAINTS) {
55752
+ const fhirItems = await getFhirFilterCompletions(keyword, terminologyService);
55753
+ if (fhirItems.length > 0) {
55754
+ const staticCodes = new Set(
55755
+ baseItems.map((item) => {
55756
+ const codeMatch = /^(\d{6,18})\s/.exec(typeof item.label === "string" ? item.label : "");
55757
+ return codeMatch ? codeMatch[1] : null;
55758
+ }).filter((code) => code !== null)
55759
+ );
55760
+ const uniqueFhirItems = fhirItems.filter((item) => {
55656
55761
  const codeMatch = /^(\d{6,18})\s/.exec(typeof item.label === "string" ? item.label : "");
55657
- return codeMatch ? codeMatch[1] : null;
55658
- }).filter((code) => code !== null)
55659
- );
55660
- const uniqueFhirItems = fhirItems.filter((item) => {
55661
- const codeMatch = /^(\d{6,18})\s/.exec(typeof item.label === "string" ? item.label : "");
55662
- return codeMatch ? !staticCodes.has(codeMatch[1]) : true;
55663
- });
55664
- return [...baseItems, ...uniqueFhirItems];
55762
+ return codeMatch ? !staticCodes.has(codeMatch[1]) : true;
55763
+ });
55764
+ return [...baseItems, ...uniqueFhirItems];
55765
+ }
55665
55766
  }
55666
55767
  }
55667
55768
  }
55769
+ } catch {
55668
55770
  }
55669
55771
  const searchResult = extractConceptSearchQuery(currentLine.substring(0, cursorColumn));
55670
55772
  if (!searchResult) {
@@ -56015,6 +56117,297 @@ function isInsideFilterBlock(ranges, matchStart, matchEnd) {
56015
56117
  }
56016
56118
  return false;
56017
56119
  }
56120
+ function printCanonical(ast, sourceText, outerOperator) {
56121
+ if (ast.type === NodeType.SubExpressionConstraint) {
56122
+ return printSubExpression(ast, sourceText, outerOperator);
56123
+ }
56124
+ return printExpression(ast, sourceText, outerOperator);
56125
+ }
56126
+ function printExpression(node, src, outerOperator) {
56127
+ const inner = node.expression;
56128
+ switch (inner.type) {
56129
+ case NodeType.SubExpressionConstraint:
56130
+ return printSubExpression(inner, src, outerOperator);
56131
+ case NodeType.CompoundExpression:
56132
+ return printCompoundExpression(inner, src);
56133
+ case NodeType.RefinedExpression:
56134
+ return printRefinedExpression(inner, src);
56135
+ case NodeType.DottedExpression:
56136
+ return printDottedExpression(inner, src);
56137
+ default: {
56138
+ const _exhaustive = inner;
56139
+ return String(_exhaustive);
56140
+ }
56141
+ }
56142
+ }
56143
+ function printSubExpression(node, src, outerOperator) {
56144
+ let result = "";
56145
+ if (node.operator) {
56146
+ result += node.operator.operator;
56147
+ }
56148
+ if (node.memberOf) {
56149
+ result += "^";
56150
+ }
56151
+ switch (node.focus.type) {
56152
+ case NodeType.ConceptReference:
56153
+ result += printConceptReference(node.focus);
56154
+ break;
56155
+ case NodeType.Wildcard:
56156
+ result += "*";
56157
+ break;
56158
+ case NodeType.ExpressionConstraint: {
56159
+ const innerExpr = node.focus.expression;
56160
+ if (innerExpr.type !== NodeType.CompoundExpression) {
56161
+ result += printExpression(node.focus, src, outerOperator);
56162
+ } else if (outerOperator && innerExpr.operator.operator === outerOperator) {
56163
+ result += printExpression(node.focus, src, outerOperator);
56164
+ } else {
56165
+ result += "(" + printExpression(node.focus, src) + ")";
56166
+ }
56167
+ break;
56168
+ }
56169
+ }
56170
+ if (node.filters) {
56171
+ for (const filter of node.filters) {
56172
+ const filterText = src.slice(filter.range.start.offset, filter.range.end.offset);
56173
+ result += " " + filterText.replaceAll(/\s+/g, " ").trim();
56174
+ }
56175
+ }
56176
+ if (node.historySupplement) {
56177
+ const histText = src.slice(node.historySupplement.range.start.offset, node.historySupplement.range.end.offset);
56178
+ result += " " + histText.replaceAll(/\s+/g, " ").trim();
56179
+ }
56180
+ return result;
56181
+ }
56182
+ function printCompoundExpression(node, src) {
56183
+ const op = node.operator.operator;
56184
+ return node.operands.map((operand) => printSubExpression(operand, src, op)).join(` ${op} `);
56185
+ }
56186
+ function printRefinedExpression(node, src) {
56187
+ const focus = printSubExpression(node.expression, src);
56188
+ const refinement = printRefinement(node.refinement, src);
56189
+ return focus + ":" + refinement;
56190
+ }
56191
+ function printDottedExpression(node, src) {
56192
+ const source = printSubExpression(node.source, src);
56193
+ const dots = node.attributes.map((a) => printSubExpression(a.attributeName, src));
56194
+ return source + dots.map((d) => "." + d).join("");
56195
+ }
56196
+ function printRefinement(node, src) {
56197
+ const parts = [];
56198
+ let prevEnd = node.range.start.offset;
56199
+ for (const attr of node.attributes) {
56200
+ const printed = printAttribute(attr, src);
56201
+ const inBraces = isAttrInBraceGroup(attr, prevEnd, src);
56202
+ parts.push(inBraces ? "{" + printed + "}" : printed);
56203
+ prevEnd = attr.range.end.offset;
56204
+ }
56205
+ return parts.join(",");
56206
+ }
56207
+ function isAttrInBraceGroup(attr, prevEnd, src) {
56208
+ const gap = src.slice(prevEnd, attr.range.start.offset);
56209
+ return gap.includes("{");
56210
+ }
56211
+ function printAttribute(node, src) {
56212
+ const preNameSrc = src.slice(node.range.start.offset, node.name.range.start.offset).trim();
56213
+ const cardinalityRaw = preNameSrc.replace(/^\{?\s*/, "").trim();
56214
+ const cardinalityPrefix = cardinalityRaw.length > 0 ? cardinalityRaw + " " : "";
56215
+ let name;
56216
+ if (node.name.conceptId) {
56217
+ name = node.name.conceptId;
56218
+ } else if (node.name.expression) {
56219
+ name = printSubExpression(node.name.expression, src);
56220
+ } else {
56221
+ name = src.slice(node.name.range.start.offset, node.name.range.end.offset).trim();
56222
+ }
56223
+ const between = src.slice(node.name.range.end.offset, node.value.range.start.offset);
56224
+ const opMatch = /(!?=|[<>]=)/.exec(between);
56225
+ const compOp = opMatch ? opMatch[1] : "=";
56226
+ const hasHashPrefix = between.includes("#");
56227
+ let value;
56228
+ if (node.value.expression) {
56229
+ value = printSubExpression(node.value.expression, src);
56230
+ } else if (node.value.rawValue) {
56231
+ value = hasHashPrefix ? "#" + node.value.rawValue : node.value.rawValue;
56232
+ } else {
56233
+ value = src.slice(node.value.range.start.offset, node.value.range.end.offset).trim();
56234
+ }
56235
+ const reversed = node.reversed ? "R " : "";
56236
+ return cardinalityPrefix + reversed + name + " " + compOp + " " + value;
56237
+ }
56238
+ function printConceptReference(node) {
56239
+ return node.conceptId;
56240
+ }
56241
+ function normaliseAst(ast, sourceText) {
56242
+ return normaliseExpression(ast, sourceText);
56243
+ }
56244
+ function normaliseExpression(node, src) {
56245
+ const inner = node.expression;
56246
+ let normalised;
56247
+ switch (inner.type) {
56248
+ case NodeType.SubExpressionConstraint:
56249
+ normalised = normaliseSubExpression(inner, src);
56250
+ break;
56251
+ case NodeType.CompoundExpression:
56252
+ normalised = normaliseCompoundExpression(inner, src);
56253
+ break;
56254
+ case NodeType.RefinedExpression:
56255
+ normalised = normaliseRefinedExpression(inner, src);
56256
+ break;
56257
+ case NodeType.DottedExpression:
56258
+ normalised = normaliseDottedExpression(inner, src);
56259
+ break;
56260
+ default: {
56261
+ const _exhaustive = inner;
56262
+ normalised = _exhaustive;
56263
+ }
56264
+ }
56265
+ return { ...node, expression: normalised };
56266
+ }
56267
+ function normaliseSubExpression(node, src) {
56268
+ let focus;
56269
+ switch (node.focus.type) {
56270
+ case NodeType.ConceptReference:
56271
+ focus = stripTerm(node.focus);
56272
+ break;
56273
+ case NodeType.Wildcard:
56274
+ focus = { ...node.focus };
56275
+ break;
56276
+ case NodeType.ExpressionConstraint:
56277
+ focus = normaliseExpression(node.focus, src);
56278
+ break;
56279
+ }
56280
+ return {
56281
+ ...node,
56282
+ operator: node.operator ? { ...node.operator } : void 0,
56283
+ focus,
56284
+ filters: node.filters ? node.filters.map(copyFilter) : void 0,
56285
+ historySupplement: node.historySupplement ? { ...node.historySupplement } : void 0
56286
+ };
56287
+ }
56288
+ function normaliseCompoundExpression(node, src) {
56289
+ const op = node.operator.operator;
56290
+ let normOperands = node.operands.map((o) => normaliseSubExpression(o, src));
56291
+ if (op === "AND" || op === "OR") {
56292
+ normOperands = flattenSameOperator(normOperands, op, src);
56293
+ }
56294
+ if (op === "AND" || op === "OR") {
56295
+ normOperands.sort((a, b) => {
56296
+ const ka = printCanonical(a, src);
56297
+ const kb = printCanonical(b, src);
56298
+ return ka.localeCompare(kb);
56299
+ });
56300
+ }
56301
+ return {
56302
+ ...node,
56303
+ operator: { ...node.operator },
56304
+ operands: normOperands
56305
+ };
56306
+ }
56307
+ function flattenSameOperator(operands, operator, src) {
56308
+ const result = [];
56309
+ for (const operand of operands) {
56310
+ if (operand.focus.type === NodeType.ExpressionConstraint && !operand.operator && !operand.memberOf && !operand.filters && !operand.historySupplement) {
56311
+ const inner = operand.focus.expression;
56312
+ if (inner.type === NodeType.CompoundExpression && inner.operator.operator === operator) {
56313
+ const innerNorm = normaliseCompoundExpression(inner, src);
56314
+ result.push(...innerNorm.operands);
56315
+ continue;
56316
+ }
56317
+ }
56318
+ result.push(operand);
56319
+ }
56320
+ return result;
56321
+ }
56322
+ function normaliseRefinedExpression(node, src) {
56323
+ return {
56324
+ ...node,
56325
+ expression: normaliseSubExpression(node.expression, src),
56326
+ refinement: normaliseRefinement(node.refinement, src)
56327
+ };
56328
+ }
56329
+ function normaliseRefinement(node, src) {
56330
+ const normAttrs = node.attributes.map((a) => normaliseAttribute(a, src));
56331
+ normAttrs.sort((a, b) => compareAttributes(a, b, src));
56332
+ return { ...node, attributes: normAttrs };
56333
+ }
56334
+ function compareAttributes(a, b, src) {
56335
+ const aId = a.name.conceptId;
56336
+ const bId = b.name.conceptId;
56337
+ if (aId && bId) {
56338
+ const aBig = BigInt(aId);
56339
+ const bBig = BigInt(bId);
56340
+ if (aBig < bBig) return -1;
56341
+ if (aBig > bBig) return 1;
56342
+ return 0;
56343
+ }
56344
+ if (aId) return -1;
56345
+ if (bId) return 1;
56346
+ const aKey = a.name.expression ? printCanonical(a.name.expression, src) : "";
56347
+ const bKey = b.name.expression ? printCanonical(b.name.expression, src) : "";
56348
+ return aKey.localeCompare(bKey);
56349
+ }
56350
+ function normaliseAttribute(node, src) {
56351
+ return {
56352
+ ...node,
56353
+ name: normaliseAttributeName(node.name, src),
56354
+ value: normaliseAttributeValue(node.value, src)
56355
+ };
56356
+ }
56357
+ function normaliseAttributeName(node, src) {
56358
+ return {
56359
+ ...node,
56360
+ term: void 0,
56361
+ // §5.1: strip display terms
56362
+ expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
56363
+ };
56364
+ }
56365
+ function normaliseAttributeValue(node, src) {
56366
+ return {
56367
+ ...node,
56368
+ expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
56369
+ };
56370
+ }
56371
+ function normaliseDottedExpression(node, src) {
56372
+ return {
56373
+ ...node,
56374
+ source: normaliseSubExpression(node.source, src),
56375
+ attributes: node.attributes.map(
56376
+ (a) => ({
56377
+ ...a,
56378
+ attributeName: normaliseSubExpression(a.attributeName, src)
56379
+ })
56380
+ )
56381
+ };
56382
+ }
56383
+ function stripTerm(node) {
56384
+ return { ...node, term: void 0 };
56385
+ }
56386
+ function copyFilter(node) {
56387
+ return { ...node };
56388
+ }
56389
+ class CanonicaliseError extends Error {
56390
+ constructor(message, parseErrors) {
56391
+ super(message);
56392
+ this.parseErrors = parseErrors;
56393
+ this.name = "CanonicaliseError";
56394
+ }
56395
+ }
56396
+ function canonicalise(expression) {
56397
+ var _a;
56398
+ const { ast, errors: errors2 } = parseECL(expression);
56399
+ if (!ast || errors2.length > 0) {
56400
+ throw new CanonicaliseError(`Cannot canonicalise invalid ECL: ${((_a = errors2[0]) == null ? void 0 : _a.message) ?? "unknown error"}`, errors2);
56401
+ }
56402
+ const normalised = normaliseAst(ast, expression);
56403
+ return printCanonical(normalised, expression);
56404
+ }
56405
+ function compareExpressions(a, b) {
56406
+ if (a.trim() === b.trim()) return "identical";
56407
+ const ca = canonicalise(a);
56408
+ const cb = canonicalise(b);
56409
+ return ca === cb ? "structurally_equivalent" : "different";
56410
+ }
56018
56411
  const operatorArticles = [
56019
56412
  {
56020
56413
  id: "op:selfOf",
@@ -57034,12 +57427,16 @@ const knowledgeGuides = [
57034
57427
  function getGuide(uri2) {
57035
57428
  return knowledgeGuides.find((g) => g.uri === uri2);
57036
57429
  }
57430
+ exports.CanonicaliseError = CanonicaliseError;
57037
57431
  exports.FhirTerminologyService = FhirTerminologyService;
57038
57432
  exports.REFACTORING_RESOLVE_KIND = REFACTORING_RESOLVE_KIND;
57039
57433
  exports.allArticles = allArticles;
57040
57434
  exports.analyzeExpression = analyzeExpression;
57435
+ exports.buildReplacementText = buildReplacementText;
57436
+ exports.canonicalise = canonicalise;
57041
57437
  exports.checkMixedRefinementOperators = checkMixedRefinementOperators;
57042
57438
  exports.clearFilterCache = clearFilterCache;
57439
+ exports.compareExpressions = compareExpressions;
57043
57440
  exports.computeSemanticTokens = computeSemanticTokens;
57044
57441
  exports.coreInsert = coreInsert;
57045
57442
  exports.coreReplace = coreReplace;