@aehrc/ecl-core 1.7.0 → 1.9.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
@@ -42416,8 +42416,9 @@ function runParseAttempt(input, predictionMode) {
42416
42416
  parser.removeErrorListeners();
42417
42417
  parser.addErrorListener(errorListener);
42418
42418
  let ast = null;
42419
+ let tree = null;
42419
42420
  try {
42420
- const tree = parser.expressionconstraint();
42421
+ tree = parser.expressionconstraint();
42421
42422
  ast = new ECLASTVisitor().visit(tree);
42422
42423
  const currentToken = parser.currentToken;
42423
42424
  if (currentToken.type !== import_antlr4ts.Token.EOF) {
@@ -42434,7 +42435,8 @@ function runParseAttempt(input, predictionMode) {
42434
42435
  } catch {}
42435
42436
  return {
42436
42437
  ast,
42437
- errors: errorListener.getErrors()
42438
+ errors: errorListener.getErrors(),
42439
+ tree
42438
42440
  };
42439
42441
  }
42440
42442
  /**
@@ -42458,6 +42460,22 @@ function parseWithFallback(input) {
42458
42460
  if (sll.ast !== null && sll.errors.length === 0) return sll;
42459
42461
  return runParseAttempt(input, import_PredictionMode.PredictionMode.LL);
42460
42462
  }
42463
+ /**
42464
+ * Parses `input` and returns the ANTLR parse tree, which keeps every character
42465
+ * of the source: whitespace, comments and display terms included. The AST from
42466
+ * `parseECL` drops these, so code that rewrites the source text exactly (such as
42467
+ * the minifier) walks this tree instead.
42468
+ *
42469
+ * Uses the same SLL-then-LL strategy as `parseECL`. `errors` are ANTLR's raw
42470
+ * messages; call `parseECL` for the clearer ones shown to users.
42471
+ */
42472
+ function parseConcreteTree(input) {
42473
+ const { tree, errors } = parseWithFallback(input);
42474
+ return {
42475
+ tree,
42476
+ errors
42477
+ };
42478
+ }
42461
42479
  function parseECL(input) {
42462
42480
  if (input === lastInput && lastResult !== null) return lastResult;
42463
42481
  const tokenLexer = new ECLLexer(new import_antlr4ts.ANTLRInputStream(input));
@@ -43235,6 +43253,8 @@ function toHttpError(options) {
43235
43253
  return new TerminologyHttpError(`Terminology server returned HTTP ${options.status} for ${options.operation}${suffix}`, options);
43236
43254
  }
43237
43255
  // src/terminology/fhir-service.ts
43256
+ /** SNOMED CT's description type for a fully specified name. */
43257
+ var FSN_TYPE = "900000000000003001";
43238
43258
  /** URL of the R5 `ValueSet.expansion.contains.property` element as an R4 extension. */
43239
43259
  var CONTAINS_PROPERTY_EXTENSION = "http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.contains.property";
43240
43260
  /**
@@ -43242,23 +43262,53 @@ var CONTAINS_PROPERTY_EXTENSION = "http://hl7.org/fhir/5.0/StructureDefinition/e
43242
43262
  * extension form; undefined when the server sent no parent property at all.
43243
43263
  */
43244
43264
  function parentCodes(item) {
43265
+ return propertyCodes(item, "parent");
43266
+ }
43267
+ /** One boolean property of an expansion entry, from R5 `property` or its R4 extension form; undefined when absent. */
43268
+ function propertyBoolean(item, code) {
43269
+ const direct = item.property?.find((p) => p.code === code && typeof p.valueBoolean === "boolean");
43270
+ if (direct) return direct.valueBoolean;
43271
+ for (const ext of item.extension ?? []) {
43272
+ if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
43273
+ const parts = ext.extension ?? [];
43274
+ if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
43275
+ const value = parts.find((x) => x.url === "value")?.valueBoolean;
43276
+ if (typeof value === "boolean") return value;
43277
+ }
43278
+ }
43279
+ /** The codes of one coded property of an expansion entry, or undefined when the entry has none. */
43280
+ function propertyCodes(item, code) {
43245
43281
  const codes = [];
43246
43282
  let seen = false;
43247
43283
  for (const p of item.property ?? []) {
43248
- if (p.code !== "parent") continue;
43284
+ if (p.code !== code) continue;
43249
43285
  seen = true;
43250
43286
  if (p.valueCode) codes.push(p.valueCode);
43251
43287
  }
43252
43288
  for (const ext of item.extension ?? []) {
43253
43289
  if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
43254
43290
  const parts = ext.extension ?? [];
43255
- if (parts.find((x) => x.url === "code")?.valueCode !== "parent") continue;
43291
+ if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
43256
43292
  seen = true;
43257
43293
  const value = parts.find((x) => x.url === "value")?.valueCode;
43258
43294
  if (value) codes.push(value);
43259
43295
  }
43260
43296
  return seen ? codes : void 0;
43261
43297
  }
43298
+ var conceptListCache = /* @__PURE__ */ new WeakMap();
43299
+ /**
43300
+ * `[{"code": ...}, ...]` for a compose's `concept`. Cached for the life of the
43301
+ * list only when the array is frozen, so the text cannot go stale: derive
43302
+ * freezes its member list, which it sends with every comparison, and any other
43303
+ * caller's array is built afresh each time.
43304
+ */
43305
+ function conceptListJson(codes) {
43306
+ const cached = conceptListCache.get(codes);
43307
+ if (cached !== void 0) return cached;
43308
+ const json = "[" + codes.map((code) => "{\"code\":" + JSON.stringify(code) + "}").join(",") + "]";
43309
+ if (Object.isFrozen(codes)) conceptListCache.set(codes, json);
43310
+ return json;
43311
+ }
43262
43312
  var DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
43263
43313
  /** True when running in a browser environment. */
43264
43314
  var IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
@@ -43290,8 +43340,33 @@ var ConcurrencyQueue = class {
43290
43340
  };
43291
43341
  var RETRY_BASE_DELAY_MS = 500;
43292
43342
  var RETRY_MAX_DELAY_MS = 1e4;
43293
- var RETRY_MAX_ATTEMPTS = 3;
43294
43343
  var RETRY_JITTER_MS = 200;
43344
+ /** Default for {@link FhirTerminologyServiceOptions.rateLimitWaitMs}. */
43345
+ var DEFAULT_RATE_LIMIT_WAIT_MS = 6e4;
43346
+ /**
43347
+ * Milliseconds until the server says requests may resume, from `Retry-After`
43348
+ * (seconds or an HTTP date) or `x-ratelimit-reset` (seconds from now, or an
43349
+ * epoch time in seconds), whichever is later; 0 when it says neither.
43350
+ */
43351
+ /** `x-ratelimit-remaining`, when the server sends it. */
43352
+ function remainingRequests(headers) {
43353
+ const value = headers.get("x-ratelimit-remaining")?.trim();
43354
+ if (!value) return void 0;
43355
+ const n = Number(value);
43356
+ return Number.isFinite(n) && n >= 0 ? n : void 0;
43357
+ }
43358
+ function serverResetMs(headers, now) {
43359
+ let ms = 0;
43360
+ const retryAfter = headers.get("Retry-After")?.trim();
43361
+ if (retryAfter) {
43362
+ const seconds = Number(retryAfter);
43363
+ const at = Number.isFinite(seconds) ? now + seconds * 1e3 : Date.parse(retryAfter);
43364
+ if (Number.isFinite(at)) ms = Math.max(ms, at - now);
43365
+ }
43366
+ const reset = Number(headers.get("x-ratelimit-reset"));
43367
+ if (Number.isFinite(reset) && reset > 0) ms = Math.max(ms, reset > 1e9 ? reset * 1e3 - now : reset * 1e3);
43368
+ return Math.max(0, ms);
43369
+ }
43295
43370
  /**
43296
43371
  * Characters that carry structural meaning inside the *canonical* implicit ValueSet URL
43297
43372
  * (`http://snomed.info/sct?fhir_vs=ecl/<expression>`) and must therefore be percent-encoded
@@ -43368,10 +43443,26 @@ var FhirTerminologyService = class FhirTerminologyService {
43368
43443
  */
43369
43444
  bulkExpandUnsupported = false;
43370
43445
  queue;
43446
+ rateLimitWaitMs;
43447
+ /** No request is sent before this time: the server said its rate limit is spent until then. */
43448
+ pausedUntil = 0;
43449
+ /**
43450
+ * Requests held by the rate limit, oldest first (a retry goes back to the
43451
+ * front). When a pause ends they do not all go at once, which would meet
43452
+ * one success and a storm of 429s: one goes first (the probe), and its
43453
+ * response says how many more the server has room for.
43454
+ */
43455
+ held = [];
43456
+ /** A probe is in flight: the others wait for its answer. */
43457
+ probing = false;
43458
+ /** Requests sent and not yet answered, so `x-ratelimit-remaining` is not spent twice. */
43459
+ unanswered = 0;
43460
+ wakeTimer;
43371
43461
  constructor(options = {}) {
43372
43462
  const maxConcurrency = options.maxConcurrency ?? 25;
43373
43463
  if (maxConcurrency <= 0) throw new Error(`maxConcurrency must be > 0, got ${maxConcurrency}`);
43374
43464
  this.queue = new ConcurrencyQueue(maxConcurrency);
43465
+ this.rateLimitWaitMs = options.rateLimitWaitMs ?? DEFAULT_RATE_LIMIT_WAIT_MS;
43375
43466
  this.baseUrl = options.baseUrl ?? "https://tx.ontoserver.csiro.au/fhir";
43376
43467
  this.timeout = options.timeout ?? 2e3;
43377
43468
  this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
@@ -43549,18 +43640,74 @@ var FhirTerminologyService = class FhirTerminologyService {
43549
43640
  * status that is not an "unknown code" response.
43550
43641
  */
43551
43642
  async fetchWithRetry(url, timeoutMs, init) {
43552
- for (let attempt = 0; attempt < RETRY_MAX_ATTEMPTS; attempt++) {
43553
- const response = await this.fetchWithTimeout(url, timeoutMs, init);
43554
- if (response.status !== 429) return response;
43555
- if (attempt === 2) throw new Error(`FHIR request rate-limited after ${RETRY_MAX_ATTEMPTS} attempts`);
43556
- const retryAfterHeader = response.headers.get("Retry-After");
43557
- const retryAfterMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1e3 : 0;
43558
- const backoff = Math.min(RETRY_BASE_DELAY_MS * Math.pow(2, attempt), RETRY_MAX_DELAY_MS);
43643
+ const started = Date.now();
43644
+ for (let attempt = 1;; attempt++) {
43645
+ const probe = await this.waitForRateLimit(attempt > 1);
43646
+ this.unanswered++;
43647
+ let response;
43648
+ try {
43649
+ response = await this.fetchWithTimeout(url, timeoutMs, init);
43650
+ } catch (error) {
43651
+ this.release(probe, 0);
43652
+ throw error;
43653
+ }
43654
+ const now = Date.now();
43655
+ const resetMs = serverResetMs(response.headers, now);
43656
+ const remaining = remainingRequests(response.headers);
43657
+ if (response.status !== 429) {
43658
+ if (remaining === 0 && resetMs > 0) this.pauseUntil(now + resetMs);
43659
+ this.release(probe, remaining ?? Infinity);
43660
+ return response;
43661
+ }
43662
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1), RETRY_MAX_DELAY_MS);
43559
43663
  const jitter = Math.random() * RETRY_JITTER_MS;
43560
- const waitMs = Math.max(retryAfterMs, backoff + jitter);
43561
- await new Promise((resolve) => setTimeout(resolve, waitMs));
43664
+ const waitMs = (resetMs > 0 ? resetMs : backoff) + jitter;
43665
+ this.pauseUntil(now + waitMs);
43666
+ this.release(probe, 0);
43667
+ if (now + waitMs - started > this.rateLimitWaitMs) throw new Error(`FHIR request rate-limited after ${attempt} attempts over ${Math.round((now - started) / 1e3)} s`);
43562
43668
  }
43563
- throw new Error("Unreachable");
43669
+ }
43670
+ pauseUntil(time) {
43671
+ this.pausedUntil = Math.max(this.pausedUntil, time);
43672
+ this.schedule();
43673
+ }
43674
+ /**
43675
+ * Go now, or wait in line while the rate limit is spent or other requests
43676
+ * are held; true when this request is the probe. A retry waits at the front.
43677
+ */
43678
+ waitForRateLimit(retry) {
43679
+ if (!retry && !this.probing && this.held.length === 0 && Date.now() >= this.pausedUntil) return Promise.resolve(false);
43680
+ return new Promise((resolve) => {
43681
+ if (retry) this.held.unshift(resolve);
43682
+ else this.held.push(resolve);
43683
+ this.schedule();
43684
+ });
43685
+ }
43686
+ /** When the pause ends, send the oldest held request alone, as the probe. */
43687
+ schedule() {
43688
+ if (this.wakeTimer !== void 0 || this.probing || this.held.length === 0) return;
43689
+ this.wakeTimer = setTimeout(() => {
43690
+ this.wakeTimer = void 0;
43691
+ if (Date.now() < this.pausedUntil) {
43692
+ this.schedule();
43693
+ return;
43694
+ }
43695
+ const next = this.held.shift();
43696
+ if (!next) return;
43697
+ this.probing = true;
43698
+ next(true);
43699
+ }, Math.max(0, this.pausedUntil - Date.now()));
43700
+ }
43701
+ /**
43702
+ * A request's answer: if it was the probe, the next may go; while no pause
43703
+ * is set, let as many held requests go as the server has room for
43704
+ * (`remaining`), oldest first, and probe again for the rest.
43705
+ */
43706
+ release(probe, room) {
43707
+ this.unanswered--;
43708
+ if (probe) this.probing = false;
43709
+ if (Date.now() >= this.pausedUntil) for (let n = room - this.unanswered; n > 0 && this.held.length > 0; n--) this.held.shift()?.(false);
43710
+ this.schedule();
43564
43711
  }
43565
43712
  fetchQueued(url, timeoutMs, init) {
43566
43713
  return this.queue.run(() => this.fetchWithRetry(url, timeoutMs, init));
@@ -43604,7 +43751,7 @@ var FhirTerminologyService = class FhirTerminologyService {
43604
43751
  }
43605
43752
  const conceptInfo = {
43606
43753
  id: conceptId,
43607
- fsn: display,
43754
+ fsn: params.filter((p) => p.name === "designation").find((p) => p.part?.some((q) => q.name === "use" && q.valueCoding?.code === FSN_TYPE))?.part?.find((q) => q.name === "value")?.valueString ?? display,
43608
43755
  pt: display,
43609
43756
  active
43610
43757
  };
@@ -43725,7 +43872,7 @@ var FhirTerminologyService = class FhirTerminologyService {
43725
43872
  }));
43726
43873
  }
43727
43874
  async bulkExpand(conceptIds) {
43728
- const url = `${this.baseUrl}/ValueSet/$expand?property=inactive&activeOnly=false`;
43875
+ const url = `${this.baseUrl}/ValueSet/$expand?property=inactive&activeOnly=false&includeDesignations=true`;
43729
43876
  const include = {
43730
43877
  system: "http://snomed.info/sct",
43731
43878
  concept: conceptIds.map((code) => ({ code }))
@@ -43764,7 +43911,7 @@ var FhirTerminologyService = class FhirTerminologyService {
43764
43911
  else if ((entry.property ?? []).find((p) => p.code === "inactive")?.valueBoolean === true) active = false;
43765
43912
  results.set(code, {
43766
43913
  id: code,
43767
- fsn: display,
43914
+ fsn: entry.designation?.find((d) => d.use?.code === FSN_TYPE)?.value ?? display,
43768
43915
  pt: display,
43769
43916
  active
43770
43917
  });
@@ -43920,6 +44067,53 @@ var FhirTerminologyService = class FhirTerminologyService {
43920
44067
  const data = await response.json();
43921
44068
  return FhirTerminologyService.relationshipsOf(data.parameter ?? []);
43922
44069
  }
44070
+ /**
44071
+ * Many `$lookup`s in one FHIR batch Bundle, so a sample of relationships
44072
+ * costs one request against the rate limit rather than one per concept.
44073
+ */
44074
+ async getDefiningRelationshipsMany(conceptIds) {
44075
+ const version = this.snomedVersion ? `&version=${encodeURIComponent(this.snomedVersion)}` : "";
44076
+ const body = {
44077
+ resourceType: "Bundle",
44078
+ type: "batch",
44079
+ entry: conceptIds.map((id) => ({ request: {
44080
+ method: "GET",
44081
+ url: `CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(id)}&property=*${version}`
44082
+ } }))
44083
+ };
44084
+ const operation = `batch $lookup of the relationships of ${conceptIds.length} concepts`;
44085
+ const url = this.baseUrl;
44086
+ const response = await this.request(url, this.timeout * Math.max(1, conceptIds.length), operation, {
44087
+ method: "POST",
44088
+ headers: {
44089
+ "Content-Type": "application/fhir+json",
44090
+ Accept: "application/fhir+json"
44091
+ },
44092
+ body: JSON.stringify(body)
44093
+ });
44094
+ if (!response.ok) {
44095
+ const { detail } = await FhirTerminologyService.readErrorBody(response);
44096
+ throw toHttpError({
44097
+ status: response.status,
44098
+ statusText: response.statusText,
44099
+ url,
44100
+ operation,
44101
+ detail
44102
+ });
44103
+ }
44104
+ const data = await response.json();
44105
+ return conceptIds.map((id, i) => FhirTerminologyService.batchRelationships(id, data.entry?.[i]));
44106
+ }
44107
+ /** One batch entry's relationships: null for an unknown code, an Error for any other failure. */
44108
+ static batchRelationships(id, entry) {
44109
+ const status = Number.parseInt(entry?.response?.status ?? "", 10);
44110
+ const resource = entry?.resource;
44111
+ let answer;
44112
+ if (status >= 200 && status < 300 && resource?.resourceType === "Parameters") answer = FhirTerminologyService.relationshipsOf(resource.parameter ?? []);
44113
+ else if (FhirTerminologyService.isUnknownCodeResponse(status, resource?.resourceType === "OperationOutcome" ? resource : null)) answer = null;
44114
+ else answer = /* @__PURE__ */ new Error(`$lookup of ${id} in a batch answered ${entry?.response?.status ?? "nothing"}`);
44115
+ return answer;
44116
+ }
43923
44117
  /** The relationships in a `$lookup` response's `property` parameters; role groups are numbered from 1. */
43924
44118
  static relationshipsOf(parameters) {
43925
44119
  const partValue = (parts, name) => FhirTerminologyService.eclValue(parts?.find((p) => p.name === name));
@@ -43967,24 +44161,22 @@ var FhirTerminologyService = class FhirTerminologyService {
43967
44161
  * @throws {TerminologyHttpError} when the server answered with an error status.
43968
44162
  */
43969
44163
  async expandCompose(compose, options = {}) {
43970
- const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false } = options;
43971
- const toInclude = (clause) => ({
44164
+ const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false, children = false, activity = false } = options;
44165
+ const system = {
43972
44166
  system: "http://snomed.info/sct",
43973
- ...this.snomedVersion ? { version: this.snomedVersion } : {},
43974
- ..."ecl" in clause ? { filter: [{
44167
+ ...this.snomedVersion ? { version: this.snomedVersion } : {}
44168
+ };
44169
+ const toInclude = (clause) => "ecl" in clause ? JSON.stringify({
44170
+ ...system,
44171
+ filter: [{
43975
44172
  property: "constraint",
43976
44173
  op: "=",
43977
44174
  value: clause.ecl
43978
- }] } : { concept: clause.concepts.map((code) => ({ code })) }
43979
- });
43980
- const body = {
43981
- resourceType: "ValueSet",
43982
- compose: {
43983
- include: compose.include.map(toInclude),
43984
- ...compose.exclude?.length ? { exclude: compose.exclude.map(toInclude) } : {}
43985
- }
43986
- };
43987
- const property = parents ? "&property=parent" : "";
44175
+ }]
44176
+ }) : `${JSON.stringify(system).slice(0, -1)},"concept":${conceptListJson(clause.concepts)}}`;
44177
+ const exclude = compose.exclude?.length ? `,"exclude":[${compose.exclude.map(toInclude).join(",")}]` : "";
44178
+ const body = `{"resourceType":"ValueSet","compose":{"include":[${compose.include.map(toInclude).join(",")}]${exclude}}}`;
44179
+ const property = (parents ? "&property=parent" : "") + (children ? "&property=child" : "") + (activity ? "&property=inactive" : "");
43988
44180
  const url = `${this.baseUrl}/ValueSet/$expand?count=${count}&offset=${offset}&activeOnly=${activeOnly}${property}`;
43989
44181
  const operation = "POST ValueSet/$expand of an inline compose";
43990
44182
  const response = await this.request(url, timeoutMs, operation, {
@@ -43993,7 +44185,7 @@ var FhirTerminologyService = class FhirTerminologyService {
43993
44185
  "Content-Type": "application/fhir+json",
43994
44186
  Accept: "application/fhir+json"
43995
44187
  },
43996
- body: JSON.stringify(body)
44188
+ body
43997
44189
  });
43998
44190
  if (!response.ok) {
43999
44191
  const { detail } = await FhirTerminologyService.readErrorBody(response);
@@ -44011,6 +44203,13 @@ var FhirTerminologyService = class FhirTerminologyService {
44011
44203
  const found = parentCodes(item);
44012
44204
  if (found) result.concepts[i].parents = found;
44013
44205
  });
44206
+ if (activity) (data.expansion?.contains ?? []).forEach((item, i) => {
44207
+ const stated = item.inactive === true ? true : propertyBoolean(item, "inactive");
44208
+ if (stated !== void 0) result.concepts[i].inactive = stated;
44209
+ });
44210
+ if (children) (data.expansion?.contains ?? []).forEach((item, i) => {
44211
+ result.concepts[i].children = propertyCodes(item, "child") ?? [];
44212
+ });
44014
44213
  return result;
44015
44214
  }
44016
44215
  /**
@@ -44046,7 +44245,8 @@ var FhirTerminologyService = class FhirTerminologyService {
44046
44245
  const total = typeof expansion.total === "number" ? expansion.total : 0;
44047
44246
  const concepts = (expansion.contains ?? []).map((item) => ({
44048
44247
  code: item.code ?? "",
44049
- display: item.display ?? ""
44248
+ display: item.display ?? "",
44249
+ ...item.inactive === true ? { inactive: true } : {}
44050
44250
  }));
44051
44251
  return {
44052
44252
  total,
@@ -44083,7 +44283,7 @@ var FhirTerminologyService = class FhirTerminologyService {
44083
44283
  return {
44084
44284
  results: contains.slice(0, 20).map((item) => {
44085
44285
  const display = item.display ?? "";
44086
- const fsnDesignation = item.designation?.find((d) => d.use?.code === "900000000000003001");
44286
+ const fsnDesignation = item.designation?.find((d) => d.use?.code === FSN_TYPE);
44087
44287
  return {
44088
44288
  id: item.code ?? "",
44089
44289
  fsn: fsnDesignation?.value ?? display,
@@ -48433,6 +48633,12 @@ function compareExpressions(a, b) {
48433
48633
  var SNOMED_ROOT = "138875005";
48434
48634
  /** Ontoserver returns at most this many concepts per page, whatever `count` asks for. */
48435
48635
  var PAGE_SIZE = 5e4;
48636
+ /**
48637
+ * Codes per request when looking concepts up by code. The server's cost grows
48638
+ * with the codes in a request, and is paid again for every page of it, so a
48639
+ * long list costs least as many small requests rather than one paged one.
48640
+ */
48641
+ var LOOKUP_CHUNK = 1e4;
48436
48642
  /** Numeric order for SCTIDs, so output does not depend on input or server order. */
48437
48643
  function byId(a, b) {
48438
48644
  return a.length - b.length || compareText(a, b);
@@ -48457,15 +48663,92 @@ function countClauses(ecl) {
48457
48663
  return ecl.match(/\b\d{6,18}\b/g)?.length ?? 0;
48458
48664
  }
48459
48665
  /**
48666
+ * `terminology`, counting the requests that fail because of the server: it
48667
+ * could not be reached, timed out, was rate-limited or answered 5xx. A 4xx
48668
+ * other than 429 is about the request, not the server, and is not counted.
48669
+ * Derive drops what a failed request was for and goes on, so this count is
48670
+ * what tells a degraded result from a complete one.
48671
+ */
48672
+ var UNCOUNTED = Symbol("uncounted");
48673
+ /**
48674
+ * The service behind a {@link countingFailures} wrapper (or `terminology`
48675
+ * itself), for a request whose failure the caller recovers from by other
48676
+ * requests, which are counted: a failure there loses nothing, so it must not
48677
+ * mark the result incomplete.
48678
+ */
48679
+ function uncounted(terminology) {
48680
+ return terminology[UNCOUNTED] ?? terminology;
48681
+ }
48682
+ function countingFailures(terminology) {
48683
+ let count = 0;
48684
+ const counted = (error) => {
48685
+ if (!(isTerminologyHttpError(error) && error.status >= 400 && error.status < 500 && error.status !== 429)) count++;
48686
+ throw error;
48687
+ };
48688
+ return {
48689
+ service: new Proxy(terminology, { get(target, prop, receiver) {
48690
+ if (prop === UNCOUNTED) return uncounted(target);
48691
+ const value = Reflect.get(target, prop, receiver);
48692
+ if (typeof value !== "function") return value;
48693
+ return (...args) => {
48694
+ const out = value.apply(target, args);
48695
+ return out instanceof Promise ? out.catch(counted) : out;
48696
+ };
48697
+ } }),
48698
+ failures: () => count
48699
+ };
48700
+ }
48701
+ /**
48460
48702
  * Set queries against the server. At most {@link MAX_IN_FLIGHT} run at once:
48461
48703
  * many carry the whole member list, and the service may not queue them itself.
48462
48704
  */
48463
48705
  var SetQueries = class {
48464
48706
  expandCompose;
48707
+ parallelPages;
48465
48708
  inFlight = 0;
48466
48709
  waiting = [];
48467
- constructor(expandCompose) {
48710
+ constructor(expandCompose, parallelPages = false) {
48468
48711
  this.expandCompose = expandCompose;
48712
+ this.parallelPages = parallelPages;
48713
+ }
48714
+ /**
48715
+ * The rest of an expansion whose first `first.length` concepts have been
48716
+ * read, up to `until`, in order. Pages step by the first page's length, which
48717
+ * is the server's page cap when it returned fewer than asked (Ontoserver
48718
+ * caps at 50,000; other servers lower). With `parallelPages` those pages are
48719
+ * asked for at once. Whatever is still missing after that (a server whose
48720
+ * pages shrink) is read one page after another, advancing by what each page
48721
+ * actually held, so a smaller cap never silently drops concepts.
48722
+ */
48723
+ async rest(compose, first, until, options) {
48724
+ const concepts = [...first];
48725
+ const step = first.length;
48726
+ if (step === 0) return concepts;
48727
+ const page = async (offset, count) => (await this.expand(compose, {
48728
+ ...options,
48729
+ count,
48730
+ offset
48731
+ })).concepts;
48732
+ if (this.parallelPages) await this.pagesAtOnce(concepts, step, until, page);
48733
+ while (concepts.length < until) {
48734
+ const p = await page(concepts.length, Math.min(PAGE_SIZE, until - concepts.length));
48735
+ if (p.length === 0) break;
48736
+ for (const c of p) concepts.push(c);
48737
+ }
48738
+ return concepts;
48739
+ }
48740
+ /**
48741
+ * Append the pages from `step` to `until`, `step` apart, asked for at once.
48742
+ * Only the run of full pages is kept: after a short one the offsets no longer line up.
48743
+ */
48744
+ async pagesAtOnce(concepts, step, until, page) {
48745
+ const offsets = [];
48746
+ for (let o = step; o < until; o += step) offsets.push(o);
48747
+ const pages = await Promise.all(offsets.map((o) => page(o, Math.min(step, until - o))));
48748
+ for (const p of pages) {
48749
+ for (const c of p) concepts.push(c);
48750
+ if (p.length < step) return;
48751
+ }
48469
48752
  }
48470
48753
  async expand(...args) {
48471
48754
  if (this.inFlight >= 8) await new Promise((resolve) => this.waiting.push(resolve));
@@ -48492,23 +48775,75 @@ var SetQueries = class {
48492
48775
  }
48493
48776
  /** Up to `max` codes of the set, sorted, plus the set's exact total. */
48494
48777
  async codes(compose, max, activeOnly = true) {
48495
- const codes = [];
48496
- let total = 0;
48497
- for (let offset = 0; codes.length < max;) {
48498
- const r = await this.expand(compose, {
48499
- count: Math.min(PAGE_SIZE, max - codes.length),
48500
- offset,
48501
- activeOnly
48778
+ const { concepts, total } = await this.concepts(compose, max, activeOnly);
48779
+ return {
48780
+ codes: concepts.map((c) => c.code).sort(byId),
48781
+ total
48782
+ };
48783
+ }
48784
+ /** Up to `max` concepts of the set with their terms, in the server's order, plus the set's exact total. */
48785
+ async concepts(compose, max, activeOnly = true) {
48786
+ const first = await this.expand(compose, {
48787
+ count: Math.min(PAGE_SIZE, max),
48788
+ offset: 0,
48789
+ activeOnly
48790
+ });
48791
+ const total = first.total;
48792
+ return {
48793
+ concepts: await this.rest(compose, first.concepts, Math.min(max, total), { activeOnly }),
48794
+ total
48795
+ };
48796
+ }
48797
+ /**
48798
+ * The concepts of `codes` the server knows, in chunks of {@link LOOKUP_CHUNK}
48799
+ * run concurrently, with their terms and, as asked, parents and children.
48800
+ * With `activeOnly: false` inactive ones come back flagged `inactive`.
48801
+ */
48802
+ async lookup(codes, options = {}) {
48803
+ return (await this.lookupEach(codes, options, (concepts) => concepts)).flat();
48804
+ }
48805
+ /**
48806
+ * {@link lookup}, with each chunk's answer passed through `each` as it
48807
+ * arrives, so a caller that keeps less than the server sends need not hold
48808
+ * every answer at once. The results are in chunk order.
48809
+ */
48810
+ async lookupEach(codes, options, each) {
48811
+ const chunks = [];
48812
+ for (let i = 0; i < codes.length; i += LOOKUP_CHUNK) chunks.push(codes.slice(i, i + LOOKUP_CHUNK));
48813
+ return Promise.all(chunks.map(async (chunk) => {
48814
+ const compose = { include: [{ concepts: chunk }] };
48815
+ const expandOptions = {
48816
+ activeOnly: options.activeOnly ?? true,
48817
+ ...options
48818
+ };
48819
+ const page = await this.expand(compose, {
48820
+ ...expandOptions,
48821
+ count: chunk.length,
48822
+ offset: 0
48502
48823
  });
48503
- total = r.total;
48504
- if (r.concepts.length === 0) break;
48505
- for (const c of r.concepts) codes.push(c.code);
48506
- offset += r.concepts.length;
48507
- if (offset >= total) break;
48508
- }
48509
- codes.sort(byId);
48824
+ if (page.concepts.length >= page.total) return each(page.concepts);
48825
+ return each(await this.rest(compose, page.concepts, page.total, expandOptions));
48826
+ }));
48827
+ }
48828
+ /**
48829
+ * Up to `max` concepts of a set known to have at most `max`, such as a list
48830
+ * of codes: with `parallelPages` every page is asked for at once, since the
48831
+ * offsets do not depend on the first page's total.
48832
+ */
48833
+ async conceptsUpTo(compose, max, activeOnly = true) {
48834
+ if (!this.parallelPages || max <= PAGE_SIZE) return this.concepts(compose, max, activeOnly);
48835
+ const offsets = [];
48836
+ for (let o = 0; o < max; o += PAGE_SIZE) offsets.push(o);
48837
+ const pages = await Promise.all(offsets.map((offset) => this.expand(compose, {
48838
+ count: Math.min(PAGE_SIZE, max - offset),
48839
+ offset,
48840
+ activeOnly
48841
+ })));
48842
+ const total = pages[0].total;
48843
+ const concepts = pages.flatMap((p) => p.concepts);
48844
+ if (concepts.length < Math.min(max, total)) return this.concepts(compose, max, activeOnly);
48510
48845
  return {
48511
- codes,
48846
+ concepts,
48512
48847
  total
48513
48848
  };
48514
48849
  }
@@ -48518,20 +48853,17 @@ var SetQueries = class {
48518
48853
  */
48519
48854
  async graph(compose, max) {
48520
48855
  const graph = /* @__PURE__ */ new Map();
48521
- for (let offset = 0;;) {
48522
- const r = await this.expand(compose, {
48523
- count: PAGE_SIZE,
48524
- offset,
48525
- parents: true
48526
- });
48527
- if (r.total > max) return "too-large";
48528
- for (const c of r.concepts) {
48529
- if (!c.parents && c.code !== "138875005") return "no-parents";
48530
- graph.set(c.code, c.parents ?? []);
48531
- }
48532
- offset += r.concepts.length;
48533
- if (r.concepts.length === 0 || offset >= r.total) return graph;
48856
+ const first = await this.expand(compose, {
48857
+ count: PAGE_SIZE,
48858
+ offset: 0,
48859
+ parents: true
48860
+ });
48861
+ if (first.total > max) return "too-large";
48862
+ for (const c of await this.rest(compose, first.concepts, first.total, { parents: true })) {
48863
+ if (!c.parents && c.code !== "138875005") return "no-parents";
48864
+ graph.set(c.code, c.parents ?? []);
48534
48865
  }
48866
+ return graph;
48535
48867
  }
48536
48868
  countEcl(ecl) {
48537
48869
  return this.count({ include: [{ ecl }] });
@@ -48862,6 +49194,30 @@ function outermost(g, items, max) {
48862
49194
  }
48863
49195
  return kept;
48864
49196
  }
49197
+ /**
49198
+ * Groups of two or more concepts whose terms match, ordered by term. Runs of
49199
+ * whitespace and the case of the first letter are ignored, as SNOMED CT
49200
+ * terms are mostly case-insensitive only there. Concepts without a term are
49201
+ * left out.
49202
+ */
49203
+ function findDuplicateTerms(concepts) {
49204
+ const groups = /* @__PURE__ */ new Map();
49205
+ for (const { code, display } of concepts) {
49206
+ const term = display.trim().replaceAll(/\s+/g, " ");
49207
+ if (!term) continue;
49208
+ const key = term.charAt(0).toLowerCase() + term.slice(1);
49209
+ const group = groups.get(key) ?? /* @__PURE__ */ new Map();
49210
+ group.set(code, display.trim());
49211
+ groups.set(key, group);
49212
+ }
49213
+ return [...groups].filter(([, g]) => g.size > 1).sort(([a], [b]) => a.localeCompare(b)).map(([, g]) => {
49214
+ const conceptIds = [...g.keys()].sort(byId);
49215
+ return {
49216
+ term: g.get(conceptIds[0]) ?? "",
49217
+ conceptIds
49218
+ };
49219
+ });
49220
+ }
48865
49221
  // src/derive/greedy-grouping.ts
48866
49222
  var MINIMUM_CLUSTER_SIZE = 2;
48867
49223
  var FIT_THRESHOLD = .9;
@@ -49005,122 +49361,439 @@ function chooseInclusions(candidates, inList, maxClauses) {
49005
49361
  // src/derive/taxonomy-graph.ts
49006
49362
  async function loadTaxonomyGraph(members, q, options) {
49007
49363
  const max = options.maxConcepts;
49008
- const memberList = await q.codes({ include: [members.clause] }, max + 1);
49364
+ const memberList = options.memberCodes ? {
49365
+ codes: options.memberCodes,
49366
+ total: options.memberCodes.length
49367
+ } : await q.codes({ include: [members.clause] }, max + 1);
49009
49368
  if (memberList.total > max) return { unavailable: "the set" };
49369
+ if (options.walk) {
49370
+ const walked = await walkedGraph(memberList.codes, q, options);
49371
+ if (walked) return walked;
49372
+ }
49373
+ const around = await eclSubgraph(members, q, options);
49374
+ if ("unavailable" in around) return around;
49375
+ const ids = new Ids();
49376
+ return await withDescendants(new LoadedGraph(new Set(memberList.codes), numbered(ids, around.up), numbered(ids, around.childGraph), ids), options, async (load) => {
49377
+ if (load.length === 0) return /* @__PURE__ */ new Map();
49378
+ const below = await q.graph({ include: [{ ecl: `<< ${orGroup(load)}` }] }, max);
49379
+ return typeof below === "string" ? below : numbered(ids, below);
49380
+ }) ?? { unavailable: "the descendants of the candidate groupers" };
49381
+ }
49382
+ /** `>> set` with each concept's parents, and the children of those concepts, by ECL queries that carry the set. */
49383
+ async function eclSubgraph(members, q, options) {
49384
+ const max = options.maxConcepts;
49010
49385
  const up = await q.graph({ include: [{ ecl: `>> ${members.ecl}` }] }, max);
49011
49386
  if (typeof up === "string") return refused(up, "the set with its ancestors");
49012
49387
  const childGraph = await q.graph({ include: [{ ecl: `<! (>> ${members.ecl})` }] }, max);
49013
49388
  if (typeof childGraph === "string") return refused(childGraph, "the children of those ancestors");
49014
- const graph = new LoadedGraph(new Set(memberList.codes), up, childGraph);
49389
+ return {
49390
+ up,
49391
+ childGraph
49392
+ };
49393
+ }
49394
+ function numbered(ids, graph) {
49395
+ const out = /* @__PURE__ */ new Map();
49396
+ for (const [id, parents] of graph) out.set(ids.at(id), parents.map((p) => ids.at(p)));
49397
+ return out;
49398
+ }
49399
+ /**
49400
+ * The graph with the descendants loaded of the concepts `descend` picks (and
49401
+ * the roots), or of those `fallbackDescend` picks when those are too many
49402
+ * (the graph is then partial); a refusal when even those are too many, and
49403
+ * null when `fetch` cannot say.
49404
+ */
49405
+ async function withDescendants(graph, options, fetch) {
49015
49406
  const roots = new Set(graph.roots());
49016
- let down = await descendantsOf(graph, (id) => options.descend(id, graph) || roots.has(id), q, max);
49407
+ const loadFor = (pick) => graph.ancestors().filter((id) => graph.children(id).length > 0 && pick(id));
49408
+ let down = await fetch(loadFor((id) => options.descend(id, graph) || roots.has(id)));
49017
49409
  if (down === "too-large" && options.fallbackDescend) {
49018
49410
  const fallback = options.fallbackDescend;
49019
- down = await descendantsOf(graph, (id) => fallback(id, graph), q, max);
49411
+ down = await fetch(loadFor((id) => fallback(id, graph)));
49020
49412
  graph.partial = true;
49021
49413
  }
49414
+ if (down === null) return null;
49022
49415
  if (typeof down === "string") return refused(down, "the descendants of the candidate groupers");
49023
49416
  graph.addBelow(down);
49024
49417
  return graph;
49025
49418
  }
49026
- /** `<< (the concepts of >> list with children that `pick` picks)`, empty when it picks none. */
49027
- async function descendantsOf(graph, pick, q, max) {
49028
- const load = graph.ancestors().filter((id) => graph.children(id).length > 0 && pick(id));
49029
- if (load.length === 0) return /* @__PURE__ */ new Map();
49030
- return q.graph({ include: [{ ecl: `<< ${orGroup(load)}` }] }, max);
49419
+ /** Concept ids, each numbered once, shared by a walk and the graph built from it. */
49420
+ var Ids = class {
49421
+ list = [];
49422
+ index = /* @__PURE__ */ new Map();
49423
+ get(id) {
49424
+ return this.index.get(id);
49425
+ }
49426
+ /** The number of `id`, given one if it has none. */
49427
+ at(id) {
49428
+ let i = this.index.get(id);
49429
+ if (i === void 0) {
49430
+ i = this.list.length;
49431
+ this.list.push(id);
49432
+ this.index.set(id, i);
49433
+ }
49434
+ return i;
49435
+ }
49436
+ };
49437
+ /**
49438
+ * Concepts looked up with their parents and children, by number. Resolving a
49439
+ * list can start one, converting each chunk as it arrives, so the server's
49440
+ * answers are not all held at once (see {@link TaxonomyGraphOptions.seed}).
49441
+ */
49442
+ var Walk = class {
49443
+ ids = new Ids();
49444
+ nodes = /* @__PURE__ */ new Map();
49445
+ /** The nodes for `concepts`, not yet added; null when one came back without the parents or children asked for. */
49446
+ nodesFor(concepts) {
49447
+ const at = (id) => this.ids.at(id);
49448
+ const out = [];
49449
+ for (const c of concepts) {
49450
+ if (!c.children || !c.parents && c.code !== "138875005") return null;
49451
+ out.push([at(c.code), {
49452
+ parents: (c.parents ?? []).map(at),
49453
+ children: c.children.map(at),
49454
+ display: c.display
49455
+ }]);
49456
+ }
49457
+ return out;
49458
+ }
49459
+ add(nodes) {
49460
+ for (const [i, n] of nodes) this.nodes.set(i, n);
49461
+ }
49462
+ /** True when every one of `codes` has been looked up. */
49463
+ has(codes) {
49464
+ for (const c of codes) {
49465
+ const i = this.ids.get(c);
49466
+ if (i === void 0 || !this.nodes.has(i)) return false;
49467
+ }
49468
+ return true;
49469
+ }
49470
+ };
49471
+ /** Record looked-up concepts; false when one came back without the parents or children asked for. */
49472
+ function record(walk, concepts) {
49473
+ const nodes = walk.nodesFor(concepts);
49474
+ if (nodes) walk.add(nodes);
49475
+ return nodes !== null;
49476
+ }
49477
+ /**
49478
+ * The graph built by walking (see {@link TaxonomyGraphOptions.walk}), or null
49479
+ * when the server does not return children, or a refusal when it is too large.
49480
+ */
49481
+ async function walkedGraph(memberCodes, q, options) {
49482
+ const max = options.maxConcepts;
49483
+ const members = new Set(memberCodes);
49484
+ const seeded = options.seed?.has(members) ? options.seed : void 0;
49485
+ const walk = seeded ?? new Walk();
49486
+ if (!seeded && !record(walk, await q.lookup(memberCodes, {
49487
+ parents: true,
49488
+ children: true
49489
+ }))) return null;
49490
+ const climbed = await walkUp(memberCodes, walk, q, max);
49491
+ if (climbed !== "done") return climbed;
49492
+ const { ids, nodes } = walk;
49493
+ const up = /* @__PURE__ */ new Map();
49494
+ const childGraph = /* @__PURE__ */ new Map();
49495
+ for (const [i, n] of nodes) {
49496
+ up.set(i, n.parents);
49497
+ for (const c of n.children) {
49498
+ if (nodes.has(c)) continue;
49499
+ const parents = childGraph.get(c);
49500
+ if (parents) parents.push(i);
49501
+ else childGraph.set(c, [i]);
49502
+ }
49503
+ }
49504
+ const graph = new LoadedGraph(members, up, childGraph, ids);
49505
+ const loaded = await withDescendants(graph, options, (load) => walkDown(load, walk, q, max));
49506
+ if (!loaded || "unavailable" in loaded) return loaded;
49507
+ graph.loadBelow = async (load) => {
49508
+ const more = await walkDown(load, walk, options.belowQueries ?? q, max);
49509
+ if (more === "too-large" || more === null) return false;
49510
+ graph.addBelow(more);
49511
+ return true;
49512
+ };
49513
+ graph.term = (id) => {
49514
+ const i = ids.get(id);
49515
+ return i === void 0 ? void 0 : nodes.get(i)?.display;
49516
+ };
49517
+ return graph;
49518
+ }
49519
+ /**
49520
+ * Add the ancestors of `start` to the walk, a level at a time: `'done'`, a
49521
+ * refusal when they are too many, or null when the server ignored
49522
+ * `property=child` (then no parent lists its child).
49523
+ */
49524
+ async function walkUp(start, walk, q, max) {
49525
+ const { ids, nodes } = walk;
49526
+ let frontier = newParents(start.map((c) => ids.at(c)), nodes);
49527
+ while (frontier.length > 0) {
49528
+ if (nodes.size + frontier.length > max) return { unavailable: "the set with its ancestors" };
49529
+ const found = await q.lookup(frontier.map((i) => ids.list[i]), {
49530
+ parents: true,
49531
+ children: true
49532
+ });
49533
+ if (!record(walk, found)) return null;
49534
+ frontier = newParents(found.map((c) => ids.at(c.code)), nodes);
49535
+ }
49536
+ for (const [i, n] of nodes) if (n.parents.some((p) => !nodes.get(p)?.children.includes(i))) return null;
49537
+ return "done";
49538
+ }
49539
+ function newParents(codes, nodes) {
49540
+ const out = /* @__PURE__ */ new Set();
49541
+ for (const c of codes) for (const p of nodes.get(c)?.parents ?? []) if (!nodes.has(p)) out.add(p);
49542
+ return [...out];
49543
+ }
49544
+ /**
49545
+ * `<< load` with each concept's parents, walked down level by level. Concepts
49546
+ * already in the walk are not looked up, and those looked up are added to it,
49547
+ * so a later walk does not look them up again.
49548
+ */
49549
+ async function walkDown(load, walk, q, max) {
49550
+ const { ids, nodes } = walk;
49551
+ const result = /* @__PURE__ */ new Map();
49552
+ let level = [...new Set(load.map((c) => ids.at(c)))];
49553
+ while (level.length > 0) {
49554
+ const missing = level.filter((c) => !nodes.has(c));
49555
+ if (missing.length > 0 && !record(walk, await q.lookup(missing.map((i) => ids.list[i]), {
49556
+ parents: true,
49557
+ children: true
49558
+ }))) return null;
49559
+ level = descendOneLevel(level, nodes, result);
49560
+ if (result.size + level.length > max) return "too-large";
49561
+ }
49562
+ return result;
49563
+ }
49564
+ /** Record `level` in `result` and return its children not yet there. */
49565
+ function descendOneLevel(level, nodes, result) {
49566
+ const next = /* @__PURE__ */ new Set();
49567
+ for (const c of level) {
49568
+ const n = nodes.get(c);
49569
+ if (!n) continue;
49570
+ result.set(c, n.parents);
49571
+ for (const child of n.children) if (!result.has(child)) next.add(child);
49572
+ }
49573
+ return [...next];
49031
49574
  }
49032
49575
  function refused(reason, what) {
49033
49576
  return { unavailable: reason === "no-parents" ? "parents" : what };
49034
49577
  }
49578
+ /**
49579
+ * The graph, with each concept numbered once and its parents and children held
49580
+ * as lists of numbers, so a graph of a few hundred thousand concepts keeps one
49581
+ * copy of each edge in each direction (it held four, with strings, before).
49582
+ */
49035
49583
  var LoadedGraph = class {
49036
49584
  members;
49037
- up;
49585
+ ids;
49038
49586
  partial = false;
49039
- parentMap = /* @__PURE__ */ new Map();
49040
- childMap = /* @__PURE__ */ new Map();
49041
- below = /* @__PURE__ */ new Set();
49587
+ loadBelow;
49588
+ term;
49589
+ /** Parents by number; a list may be the caller's (see SHARED) until the graph adds to it. */
49590
+ parentIdx = [];
49591
+ /** Children, in the order each child was first given parents (as `childrenOf` built them). */
49592
+ childIdx = [];
49593
+ /** When each concept was first given parents; -1 for a concept only seen as a parent. */
49594
+ rank = (/* @__PURE__ */ new Int32Array(1024)).fill(-1);
49595
+ nextRank = 0;
49596
+ /** How many of a concept's parents came from `up`, which come first. */
49597
+ upLength = /* @__PURE__ */ new Int32Array(1024);
49598
+ /** Bits: IN_UP, BELOW and SHARED (below the class). */
49599
+ flags = /* @__PURE__ */ new Uint8Array(1024);
49600
+ counts = /* @__PURE__ */ new Int32Array(1024);
49042
49601
  cache = /* @__PURE__ */ new Map();
49043
- counts = /* @__PURE__ */ new Map();
49044
49602
  rootIds = [];
49045
- constructor(members, up, childGraph) {
49603
+ constructor(members, up, childGraph, ids) {
49046
49604
  this.members = members;
49047
- this.up = up;
49605
+ this.ids = ids;
49048
49606
  this.merge(up);
49607
+ for (const i of up.keys()) {
49608
+ this.flags[i] |= IN_UP;
49609
+ this.upLength[i] = this.parentIdx[i]?.length ?? 0;
49610
+ }
49049
49611
  this.merge(childGraph);
49050
- this.childMap = childrenOf(this.parentMap);
49051
49612
  this.countMembers();
49052
49613
  }
49053
49614
  /** Add `<< candidates`, so their descendants are complete. */
49054
49615
  addBelow(down) {
49055
49616
  this.merge(down);
49056
- for (const id of down.keys()) this.below.add(id);
49057
- this.childMap = childrenOf(this.parentMap);
49617
+ for (const i of down.keys()) this.flags[i] |= BELOW;
49058
49618
  this.cache.clear();
49059
49619
  }
49620
+ /** The number of `id`, given one if it has none, with room for it here. */
49621
+ at(id) {
49622
+ const i = this.ids.at(id);
49623
+ this.room(i);
49624
+ return i;
49625
+ }
49626
+ /** Room for concept `i`, and for every concept numbered before it. */
49627
+ room(i) {
49628
+ while (this.parentIdx.length <= i) {
49629
+ this.parentIdx.push(void 0);
49630
+ this.childIdx.push(void 0);
49631
+ }
49632
+ while (i >= this.rank.length) this.grow();
49633
+ }
49634
+ /** The number of `id` when the graph has it. */
49635
+ known(id) {
49636
+ const i = this.ids.get(id);
49637
+ return i !== void 0 && i < this.parentIdx.length ? i : void 0;
49638
+ }
49639
+ grow() {
49640
+ const size = this.rank.length * 2;
49641
+ const rank = new Int32Array(size).fill(-1);
49642
+ rank.set(this.rank);
49643
+ this.rank = rank;
49644
+ this.upLength = withSize(this.upLength, size);
49645
+ this.counts = withSize(this.counts, size);
49646
+ const flags = new Uint8Array(size);
49647
+ flags.set(this.flags);
49648
+ this.flags = flags;
49649
+ }
49060
49650
  merge(graph) {
49061
- for (const [id, parents] of graph) {
49062
- const known = this.parentMap.get(id) ?? [];
49063
- for (const p of parents) if (!known.includes(p)) known.push(p);
49064
- this.parentMap.set(id, known);
49651
+ for (const [i, parents] of graph) {
49652
+ this.room(i);
49653
+ for (const p of parents) this.room(p);
49654
+ if (this.rank[i] < 0) this.rank[i] = this.nextRank++;
49655
+ if (!this.parentIdx[i] && new Set(parents).size === parents.length) {
49656
+ this.parentIdx[i] = parents;
49657
+ this.flags[i] |= SHARED;
49658
+ for (const p of parents) this.addChild(p, i);
49659
+ } else for (const p of parents) this.addParent(i, p);
49660
+ }
49661
+ }
49662
+ addParent(i, p) {
49663
+ let known = this.parentIdx[i];
49664
+ if (known?.includes(p)) return;
49665
+ if (!known || (this.flags[i] & SHARED) !== 0) {
49666
+ known = known ? [...known] : [];
49667
+ this.parentIdx[i] = known;
49668
+ this.flags[i] &= ~SHARED;
49669
+ }
49670
+ known.push(p);
49671
+ this.addChild(p, i);
49672
+ }
49673
+ /** Put `child` among `parent`'s children, keeping them in rank order. */
49674
+ addChild(parent, child) {
49675
+ const list = this.childIdx[parent];
49676
+ if (!list) {
49677
+ this.childIdx[parent] = [child];
49678
+ return;
49065
49679
  }
49680
+ const r = this.rank[child];
49681
+ let at = list.length;
49682
+ while (at > 0 && this.rank[list[at - 1]] > r) at--;
49683
+ if (at === list.length) list.push(child);
49684
+ else list.splice(at, 0, child);
49066
49685
  }
49067
49686
  countMembers() {
49068
49687
  const nonRoots = /* @__PURE__ */ new Set();
49069
- for (const m of this.members) for (const a of reachable(m, this.up)) {
49070
- this.counts.set(a, (this.counts.get(a) ?? 0) + 1);
49071
- if (a !== m && this.members.has(a)) nonRoots.add(m);
49688
+ for (const m of this.members) this.at(m);
49689
+ const seen = new Uint8Array(this.parentIdx.length);
49690
+ const touched = [];
49691
+ for (const m of this.members) {
49692
+ const start = this.at(m);
49693
+ this.upFrom(start, seen, touched);
49694
+ for (const a of touched) {
49695
+ this.counts[a]++;
49696
+ seen[a] = 0;
49697
+ if (a !== start && this.members.has(this.ids.list[a])) nonRoots.add(m);
49698
+ }
49699
+ touched.length = 0;
49072
49700
  }
49073
49701
  this.rootIds.push(...[...this.members].filter((m) => !nonRoots.has(m)).sort(byId));
49074
49702
  }
49703
+ /** `start` and everything reachable from it along `up`'s parents, into `touched`, marked in `seen`. */
49704
+ upFrom(start, seen, touched) {
49705
+ seen[start] = 1;
49706
+ touched.push(start);
49707
+ for (const next of touched) {
49708
+ const parents = this.parentIdx[next] ?? [];
49709
+ const fromUp = this.upLength[next];
49710
+ for (const p of fromUp === parents.length ? parents : parents.slice(0, fromUp)) {
49711
+ if (seen[p]) continue;
49712
+ seen[p] = 1;
49713
+ touched.push(p);
49714
+ }
49715
+ }
49716
+ }
49717
+ names(list) {
49718
+ const out = [];
49719
+ if (list) for (const i of list) out.push(this.ids.list[i]);
49720
+ return out;
49721
+ }
49075
49722
  aboveMember(id) {
49076
- return this.up.has(id);
49723
+ const i = this.known(id);
49724
+ return i !== void 0 && (this.flags[i] & IN_UP) !== 0;
49077
49725
  }
49078
49726
  children(id) {
49079
- return this.childMap.get(id) ?? [];
49727
+ const i = this.known(id);
49728
+ return i === void 0 ? [] : this.names(this.childIdx[i]);
49080
49729
  }
49081
49730
  parents(id) {
49082
- return this.parentMap.get(id) ?? [];
49731
+ const i = this.known(id);
49732
+ return i === void 0 ? [] : this.names(this.parentIdx[i]);
49083
49733
  }
49084
49734
  descendants(id) {
49085
- let list = this.cache.get(id);
49735
+ const i = this.known(id);
49736
+ if (i === void 0) return [id];
49737
+ let list = this.cache.get(i);
49086
49738
  if (!list) {
49087
- list = [...reachable(id, this.childMap)];
49088
- this.cache.set(id, list);
49739
+ list = this.reachableDown(i);
49740
+ if (list.length >= CACHED_DESCENDANTS) this.cache.set(i, list);
49089
49741
  }
49090
- return list;
49742
+ return this.names(list);
49743
+ }
49744
+ /** `start` and everything below it, in the order a depth-first walk first meets them. */
49745
+ reachableDown(start) {
49746
+ const seen = /* @__PURE__ */ new Set([start]);
49747
+ const stack = [start];
49748
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of this.childIdx[next] ?? []) {
49749
+ if (seen.has(x)) continue;
49750
+ seen.add(x);
49751
+ stack.push(x);
49752
+ }
49753
+ return Int32Array.from(seen);
49091
49754
  }
49092
49755
  hasDescendants(id) {
49093
- return this.below.has(id) || this.up.has(id) && this.children(id).length === 0;
49756
+ const i = this.known(id);
49757
+ if (i === void 0) return false;
49758
+ return (this.flags[i] & BELOW) !== 0 || (this.flags[i] & IN_UP) !== 0 && !this.childIdx[i]?.length;
49094
49759
  }
49095
49760
  truePos(id) {
49096
- return this.counts.get(id) ?? 0;
49761
+ const i = this.known(id);
49762
+ return i === void 0 ? 0 : this.counts[i];
49763
+ }
49764
+ membersBelow(id) {
49765
+ const start = this.known(id);
49766
+ if (start === void 0) return this.members.has(id) ? [id] : [];
49767
+ const found = [];
49768
+ const seen = /* @__PURE__ */ new Set([start]);
49769
+ const stack = [start];
49770
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) {
49771
+ if (this.members.has(this.ids.list[next])) found.push(this.ids.list[next]);
49772
+ for (const c of this.childIdx[next] ?? []) {
49773
+ if (seen.has(c) || (this.flags[c] & IN_UP) === 0) continue;
49774
+ seen.add(c);
49775
+ stack.push(c);
49776
+ }
49777
+ }
49778
+ return found.sort(byId);
49097
49779
  }
49098
49780
  roots() {
49099
49781
  return this.rootIds;
49100
49782
  }
49101
49783
  ancestors() {
49102
- return [...this.up.keys()].filter((id) => id !== SNOMED_ROOT).sort(byId);
49784
+ return this.ids.list.filter((id, i) => i < this.parentIdx.length && (this.flags[i] & IN_UP) !== 0 && id !== "138875005").sort(byId);
49103
49785
  }
49104
49786
  };
49105
- function childrenOf(graph) {
49106
- const children = /* @__PURE__ */ new Map();
49107
- for (const [child, parents] of graph) for (const p of parents) {
49108
- const list = children.get(p) ?? [];
49109
- list.push(child);
49110
- children.set(p, list);
49111
- }
49112
- return children;
49113
- }
49114
- /** `start` and everything reachable from it along `edges`. */
49115
- function reachable(start, edges) {
49116
- const seen = /* @__PURE__ */ new Set([start]);
49117
- const stack = [start];
49118
- for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of edges.get(next) ?? []) {
49119
- if (seen.has(x)) continue;
49120
- seen.add(x);
49121
- stack.push(x);
49122
- }
49123
- return seen;
49787
+ /** The fewest descendants worth caching. */
49788
+ var CACHED_DESCENDANTS = 64;
49789
+ var IN_UP = 1;
49790
+ var BELOW = 2;
49791
+ /** The concept's parent list is the caller's, so it is copied before the graph adds to it. */
49792
+ var SHARED = 4;
49793
+ function withSize(a, size) {
49794
+ const out = new Int32Array(size);
49795
+ out.set(a);
49796
+ return out;
49124
49797
  }
49125
49798
  // src/derive/refinements.ts
49126
49799
  /** Members whose relationships are read to profile the attributes the set shares. */
@@ -49161,19 +49834,39 @@ async function readRelationships(sample, getRelationships, notes) {
49161
49834
  return sampled;
49162
49835
  }
49163
49836
  /**
49837
+ * The sample's relationships in one batch request; null (read one by one)
49838
+ * when the batch fails. Entries the batch could not answer are read one by
49839
+ * one. `many` is not counted as a failure (see `uncounted`): only the one-by-one
49840
+ * reads, which lose what they cannot read, are.
49841
+ */
49842
+ async function readMany(sample, many, getRelationships, notes) {
49843
+ let answers;
49844
+ try {
49845
+ answers = await many(sample);
49846
+ } catch {
49847
+ return null;
49848
+ }
49849
+ const answered = answers.filter((a) => !(a instanceof Error));
49850
+ const retry = sample.filter((_, i) => answers[i] instanceof Error);
49851
+ if (retry.length > 0) answered.push(...await readRelationships(retry, getRelationships, notes));
49852
+ return answered;
49853
+ }
49854
+ /**
49164
49855
  * Refinement candidates for the set, likeliest first. `roots` are the set's
49165
49856
  * roots (all of them when `roots.total` fits); `givenFoci` come from the input
49166
49857
  * or the caller, and the most specific concept above every member is added
49167
49858
  * unless `fixedFocus` says the caller chose the focus.
49168
49859
  */
49169
- async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes) {
49860
+ async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes, batch = false) {
49170
49861
  const getRelationships = terminology.getDefiningRelationships?.bind(terminology);
49171
49862
  if (!getRelationships) {
49172
49863
  notes.push("Refinement candidates need a terminology service with getDefiningRelationships.");
49173
49864
  return [];
49174
49865
  }
49175
49866
  const sample = (await q.codes({ include: [members.clause] }, REFINEMENT_SAMPLE)).codes;
49176
- const sampled = await readRelationships(sample, getRelationships, notes);
49867
+ const quiet = uncounted(terminology);
49868
+ const many = batch ? quiet.getDefiningRelationshipsMany?.bind(quiet) : void 0;
49869
+ const sampled = (many && await readMany(sample, many, getRelationships, notes)) ?? await readRelationships(sample, getRelationships, notes);
49177
49870
  const profiles = profileAttributes(sampled);
49178
49871
  if (profiles.length === 0) {
49179
49872
  notes.push("No attribute is shared by most members, so no refinement candidates were built.");
@@ -49418,14 +50111,21 @@ var DEFAULTS = {
49418
50111
  greedyGrouping: true,
49419
50112
  useGraph: true,
49420
50113
  maxGraphConcepts: 2e5,
49421
- critique: false
50114
+ critique: false,
50115
+ restrictTo: "auto",
50116
+ parallelPages: true,
50117
+ localScoring: false,
50118
+ scopedExclusions: true,
50119
+ walkGraph: true,
50120
+ batchLookups: true
49422
50121
  };
49423
50122
  var CRITIQUE_DEFAULTS = {
49424
50123
  maxClauses: 35,
49425
50124
  nearMissShare: .9,
49426
50125
  nearMissMinSize: 5,
49427
50126
  maxNearMisses: 5,
49428
- impliedInactive: false
50127
+ impliedInactive: false,
50128
+ maxDuplicateTerms: 20
49429
50129
  };
49430
50130
  /** Above this many concept references, candidates are not formatted or given terms. */
49431
50131
  var MAX_DECORATED_CLAUSES = 200;
@@ -49452,6 +50152,13 @@ var MAX_SUBTRACTED = 2;
49452
50152
  */
49453
50153
  async function deriveEcl(input, terminology, options = {}) {
49454
50154
  if (!terminology.expandCompose) throw new Error("deriveEcl needs a terminology service that supports expandCompose (POST ValueSet/$expand)");
50155
+ const { service, failures } = countingFailures(terminology);
50156
+ const result = await derive(input, service, options);
50157
+ result.failures = failures();
50158
+ return result;
50159
+ }
50160
+ async function derive(input, terminology, options) {
50161
+ if (!terminology.expandCompose) throw new Error("unreachable: checked by deriveEcl");
49455
50162
  const opts = {
49456
50163
  ...DEFAULTS,
49457
50164
  ...options
@@ -49460,21 +50167,28 @@ async function deriveEcl(input, terminology, options = {}) {
49460
50167
  const q = new SetQueries((compose, o) => expandCompose(compose, {
49461
50168
  timeoutMs: opts.queryTimeoutMs,
49462
50169
  ...o
49463
- }));
50170
+ }), opts.parallelPages);
50171
+ const quiet = uncounted(terminology);
50172
+ const quietExpand = quiet.expandCompose?.bind(quiet) ?? expandCompose;
50173
+ const belowQueries = new SetQueries((compose, o) => quietExpand(compose, {
50174
+ timeoutMs: opts.queryTimeoutMs,
50175
+ ...o
50176
+ }), opts.parallelPages);
49464
50177
  const notes = [];
49465
- const { report, members } = await resolveInput(input, q, terminology, notes);
50178
+ const { report, members } = await resolveInput(input, q, terminology, notes, opts.walkGraph);
49466
50179
  const result = {
49467
50180
  input: report,
49468
50181
  hierarchies: [],
49469
50182
  roots: 0,
49470
50183
  candidates: [],
49471
- notes
50184
+ notes,
50185
+ failures: 0
49472
50186
  };
49473
50187
  if (!members) {
49474
50188
  if (notes.length === 0) notes.push("The input has no active concepts the server knows, so there is nothing to derive.");
49475
50189
  return result;
49476
50190
  }
49477
- const graph = opts.useGraph ? await loadGraph(members, q, opts, notes) : null;
50191
+ const graph = opts.useGraph ? await loadGraph(members, q, opts, notes, belowQueries) : null;
49478
50192
  const critique = critiqueOptions(opts.critique);
49479
50193
  let hierarchies = [];
49480
50194
  if (opts.hierarchySummary || critique) hierarchies = graph ? await graphHierarchies(graph, terminology) : await hierarchyDistribution(members, q);
@@ -49488,8 +50202,12 @@ async function deriveEcl(input, terminology, options = {}) {
49488
50202
  }, opts.maxRoots + 1);
49489
50203
  result.roots = rootQuery.total;
49490
50204
  const scorer = new Scorer(members, q, opts, notes);
49491
- if (graph) await scorer.score(worthCounting(graphCandidates(graph, opts, notes), inputCost(input, members), opts, notes));
49492
- else await scorer.score(await hierarchyCandidates(rootQuery.codes, result.roots, members, q, opts, notes));
50205
+ const countedLocally = /* @__PURE__ */ new Set();
50206
+ if (graph) {
50207
+ const worth = worthCounting(graphCandidates(graph, opts, notes), inputCost(input, members), opts, notes);
50208
+ await scorer.score(countOnGraph(worth, graph, opts, countedLocally));
50209
+ await scorer.score(await restrictedCovers(graph, members, q, opts, notes));
50210
+ } else await scorer.score(await hierarchyCandidates(rootQuery.codes, result.roots, members, q, opts, notes));
49493
50211
  if (wantRefinements(opts.refinements, result.roots, scorer.scored)) await scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes);
49494
50212
  await scorer.score([inputItself(input, members)]);
49495
50213
  if (critique) result.critique = await buildCritique(critique, {
@@ -49500,9 +50218,11 @@ async function deriveEcl(input, terminology, options = {}) {
49500
50218
  hierarchies,
49501
50219
  scored: scorer.scored
49502
50220
  }, q, terminology, opts);
49503
- scorer.scored.sort((a, b) => byRank(rankOf(a), rankOf(b)));
49504
- const top = scorer.scored.slice(0, opts.maxCandidates);
49505
- const terms = opts.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology);
50221
+ const useful = scorer.scored.filter((s) => s.covered > 0);
50222
+ useful.sort((a, b) => byRank(rankOf(a), rankOf(b)));
50223
+ const top = useful.slice(0, opts.maxCandidates);
50224
+ await checkLocalCounts(top, countedLocally, members, q, opts, notes);
50225
+ const terms = opts.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology, notes);
49506
50226
  result.candidates = top.map((s) => ({
49507
50227
  expression: decorate(s.ecl, terms),
49508
50228
  ...s
@@ -49513,7 +50233,7 @@ async function deriveEcl(input, terminology, options = {}) {
49513
50233
  async function scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes) {
49514
50234
  let given = "ecl" in input ? refsetFoci(input.ecl) : [];
49515
50235
  if (opts.refinementFocus) given = [asFocus(opts.refinementFocus)];
49516
- const refinements = (await refinementCandidates(members, rootQuery, given, Boolean(opts.refinementFocus), q, terminology, notes)).map(({ focus, clauses }) => ({
50236
+ const refinements = (await refinementCandidates(members, rootQuery, given, Boolean(opts.refinementFocus), q, terminology, notes, opts.batchLookups)).map(({ focus, clauses }) => ({
49517
50237
  ecl: refinementText(focus, clauses),
49518
50238
  construction: {
49519
50239
  kind: "refinement",
@@ -49544,7 +50264,7 @@ async function subtractions(scored, members, terminology, opts) {
49544
50264
  critique: false,
49545
50265
  omitTerms: true,
49546
50266
  maxCandidates: 3
49547
- })).candidates.find((x) => x.construction.kind !== "expression" && x.misses.count === 0);
50267
+ })).candidates.find((x) => x.construction.kind !== "expression" && x.misses.count === 0 && x.additions.count < c.additions.count);
49548
50268
  if (d) built.push({
49549
50269
  ecl: `(${c.ecl}) MINUS (${d.ecl})`,
49550
50270
  construction: {
@@ -49564,6 +50284,7 @@ async function subtractions(scored, members, terminology, opts) {
49564
50284
  function wantRefinements(mode, roots, scored) {
49565
50285
  if (mode === "always") return true;
49566
50286
  if (mode === "never") return false;
50287
+ if (scored.some((c) => c.exact && c.construction.kind === "restricted-cover")) return false;
49567
50288
  if (roots > REFINEMENT_ROOTS) return true;
49568
50289
  return roots > 3 && !scored.some((c) => c.exact && c.clauses <= 3);
49569
50290
  }
@@ -49579,7 +50300,11 @@ async function buildCritique(limits, found, q, terminology, opts) {
49579
50300
  const { input, result, members, graph, hierarchies, scored } = found;
49580
50301
  const induced = scored.filter((s) => s.exact && s.construction.kind !== "refset" && s.construction.kind !== "expression");
49581
50302
  const best = Math.min(members.size, ...induced.map((s) => s.clauses));
49582
- const [near, inactive] = await Promise.all([nearMisses(limits, members, graph, q, terminology, opts, result.notes), "refsetId" in input ? inactiveMembers(members, graph, q, result.notes) : [...result.input.inactive]]);
50303
+ const [near, inactive, duplicateTerms] = await Promise.all([
50304
+ nearMisses(limits, members, graph, q, terminology, opts, result.notes),
50305
+ "refsetId" in input ? inactiveMembers(members, graph, q, result.notes) : [...result.input.inactive],
50306
+ sharedTerms(limits.maxDuplicateTerms, members, q, terminology, opts, result.notes)
50307
+ ]);
49583
50308
  const critique = {
49584
50309
  clauses: {
49585
50310
  best,
@@ -49589,7 +50314,8 @@ async function buildCritique(limits, found, q, terminology, opts) {
49589
50314
  nearMisses: near,
49590
50315
  hierarchies,
49591
50316
  spansHierarchies: hierarchies.length > 1,
49592
- inactive
50317
+ inactive,
50318
+ duplicateTerms
49593
50319
  };
49594
50320
  if (limits.impliedInactive) {
49595
50321
  const profile = limits.impliedInactive === true ? "HISTORY-MOD" : limits.impliedInactive;
@@ -49611,9 +50337,9 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
49611
50337
  return [];
49612
50338
  }
49613
50339
  const local = nearMissCandidates(graph, limits.nearMissShare, limits.nearMissMinSize).slice(0, limits.maxNearMisses * NEAR_MISS_CANDIDATES_PER_REPORTED);
49614
- const counted = await Promise.allSettled(local.map((n) => q.sample({
50340
+ const counted = await nearMissesOnGraph(local, graph, opts.sampleSize) ?? await Promise.allSettled(local.map((n) => q.sample({
49615
50341
  include: [{ ecl: `<< ${n.conceptId}` }],
49616
- exclude: [members.clause]
50342
+ exclude: [opts.scopedExclusions ? { concepts: graph.membersBelow(n.conceptId) } : members.clause]
49617
50343
  }, opts.sampleSize)));
49618
50344
  const confirmed = [];
49619
50345
  counted.forEach((r, i) => {
@@ -49640,6 +50366,71 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
49640
50366
  return found;
49641
50367
  }
49642
50368
  /**
50369
+ * What each near-miss candidate adds, counted on a walked graph
50370
+ * after walking down below the candidates whose descendants are not loaded;
50371
+ * null when the graph cannot (not walked, or too many), and the server counts.
50372
+ */
50373
+ async function nearMissesOnGraph(local, graph, sampleSize) {
50374
+ if (!graph.loadBelow || local.length === 0) return null;
50375
+ const need = local.map((n) => n.conceptId).filter((id) => !graph.hasDescendants(id));
50376
+ try {
50377
+ if (need.length > 0 && !await graph.loadBelow(need)) return null;
50378
+ } catch {
50379
+ return null;
50380
+ }
50381
+ return local.map((n) => {
50382
+ const missing = graph.descendants(n.conceptId).filter((x) => !graph.members.has(x)).sort(byId);
50383
+ const sample = missing.slice(0, sampleSize).map((code) => ({
50384
+ code,
50385
+ display: graph.term?.(code) ?? ""
50386
+ }));
50387
+ return {
50388
+ status: "fulfilled",
50389
+ value: {
50390
+ count: missing.length,
50391
+ sample
50392
+ }
50393
+ };
50394
+ });
50395
+ }
50396
+ /**
50397
+ * Members that share a preferred term (CHK13): one listing of the members with
50398
+ * their terms, plus a lookup of the FSNs that tell each group apart.
50399
+ */
50400
+ async function sharedTerms(max, members, q, terminology, opts, notes) {
50401
+ const limit = Math.max(0, Math.floor(max));
50402
+ if (limit === 0) return [];
50403
+ if (members.size > opts.maxGraphConcepts) {
50404
+ notes.push(`Shared terms were not checked: the list has ${members.size} members, more than ${opts.maxGraphConcepts} (maxGraphConcepts).`);
50405
+ return [];
50406
+ }
50407
+ let groups;
50408
+ try {
50409
+ groups = findDuplicateTerms(members.concepts ?? (await q.concepts({ include: [members.clause] }, members.size)).concepts);
50410
+ } catch (error) {
50411
+ notes.push(`Shared terms were not checked: ${errorMessage(error)}.`);
50412
+ return [];
50413
+ }
50414
+ if (groups.length > limit) notes.push(`${plural(groups.length, "term")} ${groups.length === 1 ? "is" : "are"} shared by more than one member; the first ${limit} ${limit === 1 ? "is" : "are"} listed (maxDuplicateTerms).`);
50415
+ const found = groups.slice(0, limit).map((g) => ({
50416
+ term: g.term,
50417
+ concepts: g.conceptIds.map((conceptId) => ({ conceptId }))
50418
+ }));
50419
+ if (!opts.omitTerms && found.length > 0) await addFsns(found, terminology);
50420
+ return found;
50421
+ }
50422
+ /** Each concept's FSN, where it says more than the shared term. */
50423
+ async function addFsns(found, terminology) {
50424
+ const concepts = found.flatMap((d) => d.concepts);
50425
+ try {
50426
+ const info = await terminology.validateConcepts(concepts.map((c) => c.conceptId));
50427
+ for (const c of concepts) {
50428
+ const concept = info.get(c.conceptId);
50429
+ if (concept?.fsn && concept.fsn !== concept.pt) c.fsn = concept.fsn;
50430
+ }
50431
+ } catch {}
50432
+ }
50433
+ /**
49643
50434
  * A reference set's inactive members (CHK07). Its member set holds only the
49644
50435
  * active ones, so one count says whether there are any, and a listing which
49645
50436
  * (two off the graph, which already holds the active members).
@@ -49689,7 +50480,7 @@ function formKey(ecl) {
49689
50480
  return ecl;
49690
50481
  }
49691
50482
  }
49692
- async function resolveInput(input, q, terminology, notes) {
50483
+ async function resolveInput(input, q, terminology, notes, lookUp = false) {
49693
50484
  if ("refsetId" in input) return resolveRefset(input.refsetId.trim(), q, terminology, notes);
49694
50485
  if ("ecl" in input) {
49695
50486
  const ecl = `(${stripTermsAndComments(input.ecl)})`;
@@ -49727,8 +50518,19 @@ async function resolveInput(input, q, terminology, notes) {
49727
50518
  members: null
49728
50519
  };
49729
50520
  const listed = { include: [{ concepts: wellFormed }] };
49730
- const active = (await q.codes(listed, wellFormed.length, true)).codes;
49731
- const known = new Set((await q.codes(listed, wellFormed.length, false)).codes);
50521
+ let activeConcepts;
50522
+ let knownConcepts;
50523
+ let walk;
50524
+ let walkable = true;
50525
+ const looked = lookUp ? await lookUpList(wellFormed, q) : null;
50526
+ if (looked) {
50527
+ knownConcepts = { concepts: looked.concepts };
50528
+ activeConcepts = { concepts: looked.concepts.filter((c) => !c.inactive) };
50529
+ walk = looked.walk;
50530
+ walkable = looked.walkable;
50531
+ } else [activeConcepts, knownConcepts] = await Promise.all([q.conceptsUpTo(listed, wellFormed.length, true), q.conceptsUpTo(listed, wellFormed.length, false)]);
50532
+ const active = activeConcepts.concepts.map((c) => c.code).sort(byId);
50533
+ const known = new Set(knownConcepts.concepts.map((c) => c.code));
49732
50534
  const activeSet = new Set(active);
49733
50535
  report.inactive = wellFormed.filter((id) => known.has(id) && !activeSet.has(id));
49734
50536
  report.unknown = wellFormed.filter((id) => !known.has(id));
@@ -49737,15 +50539,73 @@ async function resolveInput(input, q, terminology, notes) {
49737
50539
  report,
49738
50540
  members: null
49739
50541
  };
50542
+ Object.freeze(active);
49740
50543
  return {
49741
50544
  report,
49742
50545
  members: {
49743
50546
  clause: { concepts: active },
49744
50547
  ecl: orGroup(active),
49745
- size: active.length
50548
+ size: active.length,
50549
+ concepts: activeConcepts.concepts,
50550
+ ...walk ? { walk } : {},
50551
+ ...walkable ? {} : { walkUnsupported: true }
49746
50552
  }
49747
50553
  };
49748
50554
  }
50555
+ /**
50556
+ * One chunked lookup of a list, for activity, terms, parents and children (for
50557
+ * walkGraph). Each chunk is cut down as it arrives: the terms kept, the active
50558
+ * concepts' parents and children numbered into a walk (none when the server
50559
+ * left them out).
50560
+ */
50561
+ /**
50562
+ * The list looked up once, with each concept's activity, parents and children:
50563
+ * its concepts, and the walk they seed (absent, with `walkable` false, when
50564
+ * the server gave no parents or children). Activity is asked for explicitly
50565
+ * (`property=inactive`), so a server that states it (Ontoserver) answers with
50566
+ * nothing more. On one that does not, a list with no concept flagged inactive
50567
+ * is checked with one count per chunk; null when that count disagrees: the
50568
+ * server does not flag inactive concepts, so the caller must ask twice and
50569
+ * difference the answers.
50570
+ */
50571
+ async function lookUpList(codes, q) {
50572
+ const seed = new Walk();
50573
+ const chunks = await q.lookupEach(codes, {
50574
+ activeOnly: false,
50575
+ parents: true,
50576
+ children: true,
50577
+ activity: true
50578
+ }, (concepts) => ({
50579
+ terms: concepts.map(({ code, display, inactive }) => inactive ? {
50580
+ code,
50581
+ display,
50582
+ inactive
50583
+ } : {
50584
+ code,
50585
+ display
50586
+ }),
50587
+ nodes: seed.nodesFor(concepts.filter((c) => !c.inactive)),
50588
+ stated: concepts.every((c) => c.inactive !== void 0)
50589
+ }));
50590
+ const concepts = chunks.flatMap((c) => c.terms);
50591
+ if (chunks.some((c) => !c.stated) && !concepts.some((c) => c.inactive) && await activeCount(codes, q) !== concepts.length) return null;
50592
+ if (chunks.some((c) => c.nodes === null)) return {
50593
+ concepts,
50594
+ walkable: false
50595
+ };
50596
+ for (const c of chunks) if (c.nodes) seed.add(c.nodes);
50597
+ return {
50598
+ concepts,
50599
+ walk: seed,
50600
+ walkable: true
50601
+ };
50602
+ }
50603
+ /** How many of `codes` are active, one count per lookup chunk. */
50604
+ async function activeCount(codes, q) {
50605
+ const counts = [];
50606
+ for (let i = 0; i < codes.length; i += LOOKUP_CHUNK) counts.push(q.count({ include: [{ concepts: codes.slice(i, i + LOOKUP_CHUNK) }] }));
50607
+ return (await Promise.all(counts)).reduce((a, b) => a + b, 0);
50608
+ }
49749
50609
  async function resolveRefset(refsetId, q, terminology, notes) {
49750
50610
  const report = {
49751
50611
  given: 1,
@@ -49762,7 +50622,16 @@ async function resolveRefset(refsetId, q, terminology, notes) {
49762
50622
  const ecl = `(^ ${refsetId})`;
49763
50623
  report.members = await q.countEcl(ecl);
49764
50624
  if (report.members === 0) {
49765
- const info = await terminology.getConceptInfo(refsetId);
50625
+ let info;
50626
+ try {
50627
+ info = await terminology.getConceptInfo(refsetId);
50628
+ } catch (error) {
50629
+ notes.push(`${refsetId} has no active members; could not look it up to say why: ${errorMessage(error)}.`);
50630
+ return {
50631
+ report,
50632
+ members: null
50633
+ };
50634
+ }
49766
50635
  if (info === null) report.unknown.push(refsetId);
49767
50636
  else if (info.active) notes.push(`${refsetId} |${info.pt}| has no active members, or is not a reference set.`);
49768
50637
  else report.inactive.push(refsetId);
@@ -49802,14 +50671,19 @@ async function graphHierarchies(g, terminology) {
49802
50671
  })).sort((a, b) => b.count - a.count || byId(a.conceptId, b.conceptId));
49803
50672
  }
49804
50673
  /** The IS-A subgraph around the set, or null (with a note) when the per-query path must be used. */
49805
- async function loadGraph(members, q, opts, notes) {
50674
+ async function loadGraph(members, q, opts, notes, belowQueries) {
49806
50675
  let why;
49807
50676
  try {
49808
50677
  const graph = await loadTaxonomyGraph(members, q, {
49809
50678
  maxConcepts: opts.maxGraphConcepts,
49810
50679
  descend: (id, g) => coverDescend(id, g) || refactorDescend(id, g),
49811
- fallbackDescend: refactorDescend
50680
+ fallbackDescend: refactorDescend,
50681
+ walk: opts.walkGraph && !members.walkUnsupported,
50682
+ ...members.walk ? { seed: members.walk } : {},
50683
+ belowQueries,
50684
+ ..."concepts" in members.clause ? { memberCodes: members.clause.concepts } : {}
49812
50685
  });
50686
+ delete members.walk;
49813
50687
  if (!("unavailable" in graph)) {
49814
50688
  if (graph.partial) notes.push(`The IS-A subgraph is partial: below the set's roots and every candidate grouper it has more than ${opts.maxGraphConcepts} concepts (maxGraphConcepts), so descendants were loaded only for greedy grouping's candidates, and hierarchy forms that need others were left out.`);
49815
50689
  return graph;
@@ -49874,7 +50748,8 @@ function graphCandidates(g, opts, notes) {
49874
50748
  if (local) candidates.push({
49875
50749
  ecl,
49876
50750
  construction,
49877
- local
50751
+ local,
50752
+ form
49878
50753
  });
49879
50754
  }
49880
50755
  return candidates.sort((a, b) => byRank({
@@ -49887,6 +50762,70 @@ function graphCandidates(g, opts, notes) {
49887
50762
  ...b.local
49888
50763
  }));
49889
50764
  }
50765
+ /** AMT's level reference sets, likeliest first for a list of products: MPUU, MP, TPUU, TP, MPP, TPP, CTPP. */
50766
+ var AMT_LEVEL_REFSETS = [
50767
+ "929360071000036103",
50768
+ "929360061000036106",
50769
+ "929360031000036100",
50770
+ "929360021000036102",
50771
+ "929360081000036101",
50772
+ "929360041000036105",
50773
+ "929360051000036108"
50774
+ ];
50775
+ var MEDICINAL_PRODUCT = "763158003";
50776
+ /**
50777
+ * The cover exact within `restrictTo` (see {@link DeriveOptions.restrictTo}).
50778
+ * A concept of `>> set` may stand as `<< x` when nothing of `restrictTo` below
50779
+ * it is a non-member: one query finds the concepts of `>> set` that are above
50780
+ * such a non-member. The highest of the rest, with each member that is itself
50781
+ * above a non-member, cover the set exactly once ANDed with `restrictTo`.
50782
+ */
50783
+ async function restrictedCovers(g, members, q, opts, notes) {
50784
+ if (g.partial) return [];
50785
+ const restrictTo = opts.restrictTo === "auto" ? await amtLevel(g, members, q) : opts.restrictTo.trim();
50786
+ if (!restrictTo) return [];
50787
+ const within = /^\^ ?\d+$/.test(restrictTo) ? restrictTo : `(${restrictTo})`;
50788
+ let blocked;
50789
+ try {
50790
+ blocked = await q.codes({ include: [{ ecl: `(>> ${members.ecl}) AND (>> (${within} MINUS ${members.ecl}))` }] }, opts.maxGraphConcepts);
50791
+ } catch (error) {
50792
+ notes.push(`No cover within ${restrictTo}: ${errorMessage(error)}.`);
50793
+ return [];
50794
+ }
50795
+ const above = new Set(blocked.codes);
50796
+ const free = (id) => id !== "138875005" && !above.has(id);
50797
+ const includes = [];
50798
+ for (const x of /* @__PURE__ */ new Set([...g.ancestors(), ...g.members])) if (free(x)) {
50799
+ if (!g.parents(x).some(free)) includes.push({
50800
+ conceptId: x,
50801
+ operator: "<<"
50802
+ });
50803
+ } else if (g.members.has(x)) includes.push({
50804
+ conceptId: x,
50805
+ operator: "="
50806
+ });
50807
+ if (includes.length + 1 >= members.size) return [];
50808
+ includes.sort((a, b) => byId(a.conceptId, b.conceptId));
50809
+ return [{
50810
+ ecl: `${orGroup(includes.map((c) => c.operator === "=" ? c.conceptId : `<< ${c.conceptId}`))} AND ${within}`,
50811
+ construction: {
50812
+ kind: "restricted-cover",
50813
+ restrictTo,
50814
+ includes
50815
+ }
50816
+ }];
50817
+ }
50818
+ /** `^ R` for the AMT level reference set R holding every member, when all of them are medicinal products; else ''. */
50819
+ async function amtLevel(g, members, q) {
50820
+ if (g.truePos(MEDICINAL_PRODUCT) !== members.size) return "";
50821
+ for (const refset of AMT_LEVEL_REFSETS) try {
50822
+ if (await q.count({
50823
+ include: [members.clause],
50824
+ exclude: [{ ecl: `^ ${refset}` }]
50825
+ }) === 0) return `^ ${refset}`;
50826
+ } catch {}
50827
+ return "";
50828
+ }
49890
50829
  /**
49891
50830
  * The lowest non-member concepts with every member below them, at most 3. Their
49892
50831
  * descendants may not be loaded: under `within` they are still worth counting
@@ -50297,6 +51236,82 @@ function exactScore(size) {
50297
51236
  clauses: 0
50298
51237
  };
50299
51238
  }
51239
+ /**
51240
+ * localScoring: the candidates with their counts taken from the
51241
+ * graph, when it is complete and nothing restricts what additions count;
51242
+ * `countedLocally` collects those so counted.
51243
+ */
51244
+ function countOnGraph(candidates, graph, opts, countedLocally) {
51245
+ if (!opts.localScoring || graph.partial || opts.within) return candidates;
51246
+ return candidates.map((b) => {
51247
+ const known = b.form ? graphScore(b.form, graph, opts.sampleSize) : null;
51248
+ if (!known) return b;
51249
+ countedLocally.add(b.ecl);
51250
+ return {
51251
+ ...b,
51252
+ known: {
51253
+ ...known,
51254
+ clauses: countClauses(b.ecl)
51255
+ }
51256
+ };
51257
+ });
51258
+ }
51259
+ /** Additions and misses of a form counted on the graph, with sample codes (no terms yet). */
51260
+ function graphScore(form, g, sampleSize) {
51261
+ const selected = evaluate(form, g);
51262
+ if (!selected) return null;
51263
+ const additions = [...selected].filter((x) => !g.members.has(x)).sort(byId);
51264
+ const misses = [...g.members].filter((m) => !selected.has(m)).sort(byId);
51265
+ const sample = (ids) => ids.slice(0, sampleSize).map((code) => ({
51266
+ code,
51267
+ display: ""
51268
+ }));
51269
+ return {
51270
+ covered: g.members.size - misses.length,
51271
+ additions: {
51272
+ count: additions.length,
51273
+ sample: sample(additions)
51274
+ },
51275
+ misses: {
51276
+ count: misses.length,
51277
+ sample: sample(misses)
51278
+ },
51279
+ exact: additions.length === 0 && misses.length === 0
51280
+ };
51281
+ }
51282
+ /**
51283
+ * The best candidate, when counted on the graph, is counted again
51284
+ * on the server (the server's counts replace the graph's), and the samples of
51285
+ * the others counted on the graph get their terms in one lookup.
51286
+ */
51287
+ async function checkLocalCounts(top, countedLocally, members, q, opts, notes) {
51288
+ if (countedLocally.size === 0) return;
51289
+ const best = top.length > 0 ? top[0] : void 0;
51290
+ if (best && countedLocally.has(best.ecl)) try {
51291
+ if (await q.countEcl(best.ecl) === best.covered + best.additions.count) {
51292
+ await fillTerms(top, countedLocally, q);
51293
+ return;
51294
+ }
51295
+ const server = await compare(best.ecl, members, q, opts.sampleSize, opts.within);
51296
+ if (server.additions.count !== best.additions.count || server.misses.count !== best.misses.count) notes.push(`Graph counts for ${best.ecl.slice(0, 120)} differed from the server's (+${best.additions.count} -${best.misses.count} on the graph, +${server.additions.count} -${server.misses.count} on the server).`);
51297
+ Object.assign(best, server);
51298
+ } catch (error) {
51299
+ notes.push(`Could not check ${best.ecl.slice(0, 120)} on the server: ${errorMessage(error)}`);
51300
+ }
51301
+ await fillTerms(top, countedLocally, q);
51302
+ }
51303
+ /** Terms for the samples of the candidates counted on the graph, in one lookup. */
51304
+ async function fillTerms(top, countedLocally, q) {
51305
+ const codes = /* @__PURE__ */ new Set();
51306
+ for (const s of top) {
51307
+ if (!countedLocally.has(s.ecl)) continue;
51308
+ for (const c of [...s.additions.sample, ...s.misses.sample]) if (!c.display) codes.add(c.code);
51309
+ }
51310
+ if (codes.size === 0) return;
51311
+ const found = await q.concepts({ include: [{ concepts: [...codes] }] }, codes.size, false);
51312
+ const terms = new Map(found.concepts.map((c) => [c.code, c.display]));
51313
+ for (const s of top) for (const c of [...s.additions.sample, ...s.misses.sample]) if (!c.display) c.display = terms.get(c.code) ?? "";
51314
+ }
50300
51315
  /** Additions and misses of `ecl` against the set, counted and sampled by the server. */
50301
51316
  async function compare(ecl, members, q, sampleSize, within) {
50302
51317
  const counted = within ? `(${ecl}) AND (${within})` : ecl;
@@ -50315,7 +51330,13 @@ async function compare(ecl, members, q, sampleSize, within) {
50315
51330
  clauses: countClauses(ecl)
50316
51331
  };
50317
51332
  }
50318
- async function displayTerms(candidates, terminology) {
51333
+ /**
51334
+ * Preferred terms for the ids in the candidates worth decorating. Terms are
51335
+ * decoration: when the lookup fails, the candidates go out with bare ids and,
51336
+ * given `notes`, a note says why (the failure itself is counted by the caller's
51337
+ * service), rather than losing a finished result.
51338
+ */
51339
+ async function displayTerms(candidates, terminology, notes) {
50319
51340
  const ids = /* @__PURE__ */ new Set();
50320
51341
  for (const c of candidates) {
50321
51342
  if (c.clauses > MAX_DECORATED_CLAUSES) continue;
@@ -50323,7 +51344,13 @@ async function displayTerms(candidates, terminology) {
50323
51344
  }
50324
51345
  const terms = /* @__PURE__ */ new Map();
50325
51346
  if (ids.size === 0) return terms;
50326
- const infos = await terminology.validateConcepts([...ids].sort(byId));
51347
+ let infos;
51348
+ try {
51349
+ infos = await terminology.validateConcepts([...ids].sort(byId));
51350
+ } catch (error) {
51351
+ notes?.push(`Display terms could not be looked up: ${errorMessage(error)}.`);
51352
+ return terms;
51353
+ }
50327
51354
  for (const [id, info] of infos) if (info?.pt) terms.set(id, info.pt);
50328
51355
  return terms;
50329
51356
  }
@@ -50403,6 +51430,7 @@ function bareSub(s) {
50403
51430
  function formatDeriveReport(result) {
50404
51431
  const lines = [];
50405
51432
  const { input } = result;
51433
+ if (result.failures > 0) lines.push(incompleteLine(result.failures));
50406
51434
  const duplicates = input.duplicates ? ` (${plural(input.duplicates, "duplicate")} ignored)` : "";
50407
51435
  lines.push(`Members: ${input.members} of ${input.given} distinct ids${duplicates}`);
50408
51436
  const leftOut = [
@@ -50455,8 +51483,16 @@ function reviewLines(c, inactiveListedAbove) {
50455
51483
  lines.push(`Inactive members: ${c.inactive.length}: ${c.inactive.slice(0, 20).join(", ")}${more}.`);
50456
51484
  }
50457
51485
  if (c.impliedInactive?.count) lines.push(sampleLine("Implied inactive codes not listed", c.impliedInactive));
51486
+ for (const d of c.duplicateTerms) {
51487
+ const concepts = d.concepts.map((x) => x.fsn ? `${x.conceptId} |${x.fsn}|` : x.conceptId);
51488
+ lines.push(`Same term, different concepts: |${d.term}| is ${concepts.join(", ")}.`);
51489
+ }
50458
51490
  return lines.length > 0 ? lines : ["Nothing flagged."];
50459
51491
  }
51492
+ /** The first line of a report whose result lost candidates or checks to server failures. */
51493
+ function incompleteLine(failures) {
51494
+ return `Incomplete: ${failures} server ${failures === 1 ? "query" : "queries"} failed, so candidates or checks that needed them are missing and a better form may exist (see Notes). Run it again when the server recovers.`;
51495
+ }
50460
51496
  function errorMessage(error) {
50461
51497
  return error instanceof Error ? error.message : String(error);
50462
51498
  }
@@ -50471,6 +51507,12 @@ function plural(n, noun) {
50471
51507
  * Needs a terminology service with `expandCompose`.
50472
51508
  */
50473
51509
  async function compressExpression(ecl, terminology, options = {}) {
51510
+ const { service, failures } = countingFailures(terminology);
51511
+ const result = await compress(ecl, service, options);
51512
+ result.failures = failures();
51513
+ return result;
51514
+ }
51515
+ async function compress(ecl, terminology, options) {
50474
51516
  const original = stripTermsAndComments(ecl);
50475
51517
  const parsed = parseECL(original);
50476
51518
  const result = {
@@ -50478,7 +51520,8 @@ async function compressExpression(ecl, terminology, options = {}) {
50478
51520
  group: null,
50479
51521
  candidates: [],
50480
51522
  notes: [],
50481
- errors: []
51523
+ errors: [],
51524
+ failures: 0
50482
51525
  };
50483
51526
  if (!parsed.ast || parsed.errors.length > 0) {
50484
51527
  result.errors = parsed.errors.map((e) => e.message);
@@ -50527,7 +51570,7 @@ async function compressExpression(ecl, terminology, options = {}) {
50527
51570
  built.sort((a, b) => cost(a) - cost(b) || Number(b.exact) - Number(a.exact) || SOURCE_ORDER[a.source] - SOURCE_ORDER[b.source] || a.ecl.length - b.ecl.length);
50528
51571
  const top = built.slice(0, options.maxCandidates ?? 8);
50529
51572
  for (const c of built) if (c.source !== "derived" && !top.includes(c)) top.push(c);
50530
- const terms = options.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology);
51573
+ const terms = options.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology, result.notes);
50531
51574
  result.candidates = top.map((c) => ({
50532
51575
  expression: decorate(c.ecl, terms),
50533
51576
  ...c,
@@ -50652,6 +51695,7 @@ function orInside(sub, text) {
50652
51695
  function formatCompressReport(result) {
50653
51696
  if (result.errors.length > 0) return `Not compressed: ${result.errors.join("; ")}`;
50654
51697
  const lines = [`Original selects ${result.members} concepts.`];
51698
+ if (result.failures > 0) lines.unshift(incompleteLine(result.failures));
50655
51699
  if (result.group && result.group.start > 0) lines.push(`Compressed group: ${result.group.text}`);
50656
51700
  for (const note of result.notes) lines.push(`Note: ${note}`);
50657
51701
  result.candidates.forEach((c, i) => {
@@ -50667,6 +51711,189 @@ function formatCompressReport(result) {
50667
51711
  });
50668
51712
  return lines.join("\n");
50669
51713
  }
51714
+ // src/minify/minify.ts
51715
+ var import_TerminalNode = require_TerminalNode();
51716
+ var MinifyError = class extends Error {
51717
+ parseErrors;
51718
+ constructor(message, parseErrors) {
51719
+ super(message);
51720
+ this.parseErrors = parseErrors;
51721
+ this.name = "MinifyError";
51722
+ }
51723
+ };
51724
+ /**
51725
+ * Returns the shortest form of an ECL expression that parses to the same
51726
+ * expression.
51727
+ *
51728
+ * - Display terms (`404684003 |Clinical finding|`) are removed.
51729
+ * - Whitespace is removed wherever the grammar makes it optional, and becomes a
51730
+ * single space where it is mandatory (after `AND`, `OR` and `MINUS`, and
51731
+ * between the items of a set such as `(en-au (prefer) en-gb)`).
51732
+ * - A space is also kept where removing it would join two words or numbers
51733
+ * (`D term`, `R 363698007`) or two characters into a different operator
51734
+ * (`< !!>`, `{ {`).
51735
+ * - Quoted strings (term filters, alternate identifiers, dates) are kept as
51736
+ * written, except that a tab or line break in one becomes a space.
51737
+ * - Block comments are kept unless `removeComments` is set.
51738
+ *
51739
+ * The result contains no tab, carriage return or line feed, so it is safe for
51740
+ * an RF2 file. Operand order, brackets and refinement groups are unchanged.
51741
+ *
51742
+ * Throws `MinifyError` if the expression cannot be parsed.
51743
+ */
51744
+ function minifyExpression(expression, options = {}) {
51745
+ const tree = parseOrThrow(expression);
51746
+ const minified = new Minifier(options.removeComments ?? false).print(tree);
51747
+ const check = parseConcreteTree(minified);
51748
+ if (!check.tree || check.errors.length > 0 || structureOf(check.tree) !== structureOf(tree)) throw new MinifyError(`Minifying changed the expression's structure; the result was: ${minified}`, check.errors);
51749
+ return minified;
51750
+ }
51751
+ function parseOrThrow(expression) {
51752
+ const { tree, errors } = parseConcreteTree(expression);
51753
+ if (tree && errors.length === 0) return tree;
51754
+ const friendly = parseECL(expression).errors;
51755
+ const reported = friendly.length > 0 ? friendly : errors;
51756
+ throw new MinifyError(`Cannot minify invalid ECL: ${reported[0]?.message ?? "unknown error"}`, reported);
51757
+ }
51758
+ var VERBATIM_RULES = /* @__PURE__ */ new Set([ECLParser.RULE_matchsearchtermset]);
51759
+ var TERM_BEARING_RULES = /* @__PURE__ */ new Set([ECLParser.RULE_eclconceptreference, ECLParser.RULE_altidentifier]);
51760
+ var LINE_BREAK_OR_TAB = /[\t\r\n]/g;
51761
+ var WHITESPACE_CHAR_RULES = /* @__PURE__ */ new Set([
51762
+ ECLParser.RULE_htab,
51763
+ ECLParser.RULE_cr,
51764
+ ECLParser.RULE_lf
51765
+ ]);
51766
+ var WORD_CHAR = /[\p{L}\p{N}_]/u;
51767
+ var JOINING_PAIRS = /* @__PURE__ */ new Set([
51768
+ "<<",
51769
+ "<!",
51770
+ "<=",
51771
+ ">>",
51772
+ ">!",
51773
+ ">=",
51774
+ "!!",
51775
+ "!=",
51776
+ "!<",
51777
+ "!>",
51778
+ "{{",
51779
+ "}}",
51780
+ "/*",
51781
+ "*/",
51782
+ "//",
51783
+ ".."
51784
+ ]);
51785
+ function needsSpace(before, after) {
51786
+ if (WORD_CHAR.test(before) && WORD_CHAR.test(after)) return true;
51787
+ return JOINING_PAIRS.has(before + after);
51788
+ }
51789
+ var Minifier = class {
51790
+ removeComments;
51791
+ out = "";
51792
+ brokenHere = false;
51793
+ afterUnquotedCode = false;
51794
+ constructor(removeComments) {
51795
+ this.removeComments = removeComments;
51796
+ }
51797
+ print(tree) {
51798
+ this.visit(tree);
51799
+ return this.out;
51800
+ }
51801
+ visit(node) {
51802
+ if (node instanceof import_TerminalNode.TerminalNode) {
51803
+ this.append(node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
51804
+ return;
51805
+ }
51806
+ if (!(node instanceof import_antlr4ts.ParserRuleContext)) return;
51807
+ switch (node.ruleIndex) {
51808
+ case ECLParser.RULE_ws:
51809
+ this.separator(node, false);
51810
+ return;
51811
+ case ECLParser.RULE_mws:
51812
+ this.separator(node, true);
51813
+ return;
51814
+ }
51815
+ if (VERBATIM_RULES.has(node.ruleIndex)) {
51816
+ this.append(node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
51817
+ return;
51818
+ }
51819
+ if (TERM_BEARING_RULES.has(node.ruleIndex)) {
51820
+ this.visitWithoutTerm(node);
51821
+ return;
51822
+ }
51823
+ for (const child of node.children ?? []) this.visit(child);
51824
+ }
51825
+ /** Prints a concept reference or alternate identifier without its `|term|`. */
51826
+ visitWithoutTerm(node) {
51827
+ const children = node.children ?? [];
51828
+ const firstPipe = children.findIndex((c) => c instanceof import_TerminalNode.TerminalNode && c.text === "|");
51829
+ if (firstPipe === -1) {
51830
+ for (const child of children) this.visit(child);
51831
+ this.noteUnquotedCode(node);
51832
+ return;
51833
+ }
51834
+ for (const child of children.slice(0, firstPipe - 1)) this.visit(child);
51835
+ this.noteUnquotedCode(node);
51836
+ for (const child of children.slice(firstPipe - 1)) if (child instanceof import_antlr4ts.ParserRuleContext && child.ruleIndex === ECLParser.RULE_ws) this.visit(child);
51837
+ this.brokenHere = true;
51838
+ }
51839
+ noteUnquotedCode(node) {
51840
+ const first = node.children?.[0];
51841
+ const quoted = first instanceof import_antlr4ts.ParserRuleContext && first.ruleIndex === ECLParser.RULE_qm;
51842
+ this.afterUnquotedCode = node.ruleIndex === ECLParser.RULE_altidentifier && !quoted;
51843
+ }
51844
+ /** Optional (`ws`) or mandatory (`mws`) whitespace, which may hold comments. */
51845
+ separator(node, mandatory) {
51846
+ if (node.text.length === 0) return;
51847
+ const comments = this.removeComments ? [] : (node.children ?? []).filter((c) => c instanceof import_antlr4ts.ParserRuleContext && c.ruleIndex === ECLParser.RULE_comment);
51848
+ this.brokenHere = true;
51849
+ for (const comment of comments) {
51850
+ this.append(comment.text.replaceAll(/\s+/g, " "));
51851
+ this.brokenHere = true;
51852
+ }
51853
+ if (mandatory && comments.length === 0) {
51854
+ this.out += " ";
51855
+ this.brokenHere = false;
51856
+ }
51857
+ }
51858
+ append(text) {
51859
+ if (text.length === 0) return;
51860
+ const last = this.out.at(-1);
51861
+ const keepApart = needsSpace(last ?? "", text[0]) || this.afterUnquotedCode && text.startsWith(".");
51862
+ if (this.brokenHere && last !== void 0 && keepApart) this.out += " ";
51863
+ this.out += text;
51864
+ this.brokenHere = false;
51865
+ this.afterUnquotedCode = false;
51866
+ }
51867
+ };
51868
+ /**
51869
+ * The parse tree reduced to what the expression means: rule names and
51870
+ * characters, without whitespace, comments, display terms, or the difference
51871
+ * between a tab and a space inside a string.
51872
+ */
51873
+ function structureOf(tree) {
51874
+ const parts = [];
51875
+ const walk = (node) => {
51876
+ if (node instanceof import_TerminalNode.TerminalNode) {
51877
+ parts.push(node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
51878
+ return;
51879
+ }
51880
+ if (!(node instanceof import_antlr4ts.ParserRuleContext)) return;
51881
+ const rule = WHITESPACE_CHAR_RULES.has(node.ruleIndex) ? ECLParser.RULE_sp : node.ruleIndex;
51882
+ if (rule === ECLParser.RULE_ws || rule === ECLParser.RULE_mws) return;
51883
+ if (VERBATIM_RULES.has(rule)) {
51884
+ parts.push(`[${rule}]`, node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
51885
+ return;
51886
+ }
51887
+ parts.push(`[${rule}]`);
51888
+ const children = node.children ?? [];
51889
+ const firstPipe = TERM_BEARING_RULES.has(rule) ? children.findIndex((c) => c instanceof import_TerminalNode.TerminalNode && c.text === "|") : -1;
51890
+ const kept = firstPipe === -1 ? children : children.slice(0, firstPipe - 1);
51891
+ for (const child of kept) walk(child);
51892
+ parts.push("]");
51893
+ };
51894
+ walk(tree);
51895
+ return parts.join("");
51896
+ }
50670
51897
  // src/knowledge/operators.ts
50671
51898
  /**
50672
51899
  * All 15+ ECL operators with meanings, syntax, and examples.
@@ -51731,6 +52958,7 @@ function getGuide(uri) {
51731
52958
  }
51732
52959
  exports.CanonicaliseError = CanonicaliseError;
51733
52960
  exports.FhirTerminologyService = FhirTerminologyService;
52961
+ exports.MinifyError = MinifyError;
51734
52962
  exports.REFACTORING_RESOLVE_KIND = REFACTORING_RESOLVE_KIND;
51735
52963
  exports.TerminologyError = TerminologyError;
51736
52964
  exports.TerminologyHttpError = TerminologyHttpError;
@@ -51786,6 +53014,7 @@ exports.isValidConceptId = isValidConceptId;
51786
53014
  exports.isValidDescriptionId = isValidDescriptionId;
51787
53015
  exports.isValidSnomedId = isValidSnomedId;
51788
53016
  exports.knowledgeGuides = knowledgeGuides;
53017
+ exports.minifyExpression = minifyExpression;
51789
53018
  exports.offsetAt = offsetAt;
51790
53019
  exports.operatorHoverDocs = operatorHoverDocs;
51791
53020
  exports.parseConceptIdList = parseConceptIdList;