@aehrc/ecl-core 1.8.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
@@ -43262,23 +43262,53 @@ var CONTAINS_PROPERTY_EXTENSION = "http://hl7.org/fhir/5.0/StructureDefinition/e
43262
43262
  * extension form; undefined when the server sent no parent property at all.
43263
43263
  */
43264
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) {
43265
43281
  const codes = [];
43266
43282
  let seen = false;
43267
43283
  for (const p of item.property ?? []) {
43268
- if (p.code !== "parent") continue;
43284
+ if (p.code !== code) continue;
43269
43285
  seen = true;
43270
43286
  if (p.valueCode) codes.push(p.valueCode);
43271
43287
  }
43272
43288
  for (const ext of item.extension ?? []) {
43273
43289
  if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
43274
43290
  const parts = ext.extension ?? [];
43275
- if (parts.find((x) => x.url === "code")?.valueCode !== "parent") continue;
43291
+ if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
43276
43292
  seen = true;
43277
43293
  const value = parts.find((x) => x.url === "value")?.valueCode;
43278
43294
  if (value) codes.push(value);
43279
43295
  }
43280
43296
  return seen ? codes : void 0;
43281
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
+ }
43282
43312
  var DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
43283
43313
  /** True when running in a browser environment. */
43284
43314
  var IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
@@ -43310,8 +43340,33 @@ var ConcurrencyQueue = class {
43310
43340
  };
43311
43341
  var RETRY_BASE_DELAY_MS = 500;
43312
43342
  var RETRY_MAX_DELAY_MS = 1e4;
43313
- var RETRY_MAX_ATTEMPTS = 3;
43314
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
+ }
43315
43370
  /**
43316
43371
  * Characters that carry structural meaning inside the *canonical* implicit ValueSet URL
43317
43372
  * (`http://snomed.info/sct?fhir_vs=ecl/<expression>`) and must therefore be percent-encoded
@@ -43388,10 +43443,26 @@ var FhirTerminologyService = class FhirTerminologyService {
43388
43443
  */
43389
43444
  bulkExpandUnsupported = false;
43390
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;
43391
43461
  constructor(options = {}) {
43392
43462
  const maxConcurrency = options.maxConcurrency ?? 25;
43393
43463
  if (maxConcurrency <= 0) throw new Error(`maxConcurrency must be > 0, got ${maxConcurrency}`);
43394
43464
  this.queue = new ConcurrencyQueue(maxConcurrency);
43465
+ this.rateLimitWaitMs = options.rateLimitWaitMs ?? DEFAULT_RATE_LIMIT_WAIT_MS;
43395
43466
  this.baseUrl = options.baseUrl ?? "https://tx.ontoserver.csiro.au/fhir";
43396
43467
  this.timeout = options.timeout ?? 2e3;
43397
43468
  this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
@@ -43569,18 +43640,74 @@ var FhirTerminologyService = class FhirTerminologyService {
43569
43640
  * status that is not an "unknown code" response.
43570
43641
  */
43571
43642
  async fetchWithRetry(url, timeoutMs, init) {
43572
- for (let attempt = 0; attempt < RETRY_MAX_ATTEMPTS; attempt++) {
43573
- const response = await this.fetchWithTimeout(url, timeoutMs, init);
43574
- if (response.status !== 429) return response;
43575
- if (attempt === 2) throw new Error(`FHIR request rate-limited after ${RETRY_MAX_ATTEMPTS} attempts`);
43576
- const retryAfterHeader = response.headers.get("Retry-After");
43577
- const retryAfterMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1e3 : 0;
43578
- 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);
43579
43663
  const jitter = Math.random() * RETRY_JITTER_MS;
43580
- const waitMs = Math.max(retryAfterMs, backoff + jitter);
43581
- 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`);
43582
43668
  }
43583
- 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();
43584
43711
  }
43585
43712
  fetchQueued(url, timeoutMs, init) {
43586
43713
  return this.queue.run(() => this.fetchWithRetry(url, timeoutMs, init));
@@ -43940,6 +44067,53 @@ var FhirTerminologyService = class FhirTerminologyService {
43940
44067
  const data = await response.json();
43941
44068
  return FhirTerminologyService.relationshipsOf(data.parameter ?? []);
43942
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
+ }
43943
44117
  /** The relationships in a `$lookup` response's `property` parameters; role groups are numbered from 1. */
43944
44118
  static relationshipsOf(parameters) {
43945
44119
  const partValue = (parts, name) => FhirTerminologyService.eclValue(parts?.find((p) => p.name === name));
@@ -43987,24 +44161,22 @@ var FhirTerminologyService = class FhirTerminologyService {
43987
44161
  * @throws {TerminologyHttpError} when the server answered with an error status.
43988
44162
  */
43989
44163
  async expandCompose(compose, options = {}) {
43990
- const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false } = options;
43991
- const toInclude = (clause) => ({
44164
+ const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false, children = false, activity = false } = options;
44165
+ const system = {
43992
44166
  system: "http://snomed.info/sct",
43993
- ...this.snomedVersion ? { version: this.snomedVersion } : {},
43994
- ..."ecl" in clause ? { filter: [{
44167
+ ...this.snomedVersion ? { version: this.snomedVersion } : {}
44168
+ };
44169
+ const toInclude = (clause) => "ecl" in clause ? JSON.stringify({
44170
+ ...system,
44171
+ filter: [{
43995
44172
  property: "constraint",
43996
44173
  op: "=",
43997
44174
  value: clause.ecl
43998
- }] } : { concept: clause.concepts.map((code) => ({ code })) }
43999
- });
44000
- const body = {
44001
- resourceType: "ValueSet",
44002
- compose: {
44003
- include: compose.include.map(toInclude),
44004
- ...compose.exclude?.length ? { exclude: compose.exclude.map(toInclude) } : {}
44005
- }
44006
- };
44007
- 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" : "");
44008
44180
  const url = `${this.baseUrl}/ValueSet/$expand?count=${count}&offset=${offset}&activeOnly=${activeOnly}${property}`;
44009
44181
  const operation = "POST ValueSet/$expand of an inline compose";
44010
44182
  const response = await this.request(url, timeoutMs, operation, {
@@ -44013,7 +44185,7 @@ var FhirTerminologyService = class FhirTerminologyService {
44013
44185
  "Content-Type": "application/fhir+json",
44014
44186
  Accept: "application/fhir+json"
44015
44187
  },
44016
- body: JSON.stringify(body)
44188
+ body
44017
44189
  });
44018
44190
  if (!response.ok) {
44019
44191
  const { detail } = await FhirTerminologyService.readErrorBody(response);
@@ -44031,6 +44203,13 @@ var FhirTerminologyService = class FhirTerminologyService {
44031
44203
  const found = parentCodes(item);
44032
44204
  if (found) result.concepts[i].parents = found;
44033
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
+ });
44034
44213
  return result;
44035
44214
  }
44036
44215
  /**
@@ -44066,7 +44245,8 @@ var FhirTerminologyService = class FhirTerminologyService {
44066
44245
  const total = typeof expansion.total === "number" ? expansion.total : 0;
44067
44246
  const concepts = (expansion.contains ?? []).map((item) => ({
44068
44247
  code: item.code ?? "",
44069
- display: item.display ?? ""
44248
+ display: item.display ?? "",
44249
+ ...item.inactive === true ? { inactive: true } : {}
44070
44250
  }));
44071
44251
  return {
44072
44252
  total,
@@ -48453,6 +48633,12 @@ function compareExpressions(a, b) {
48453
48633
  var SNOMED_ROOT = "138875005";
48454
48634
  /** Ontoserver returns at most this many concepts per page, whatever `count` asks for. */
48455
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;
48456
48642
  /** Numeric order for SCTIDs, so output does not depend on input or server order. */
48457
48643
  function byId(a, b) {
48458
48644
  return a.length - b.length || compareText(a, b);
@@ -48477,15 +48663,92 @@ function countClauses(ecl) {
48477
48663
  return ecl.match(/\b\d{6,18}\b/g)?.length ?? 0;
48478
48664
  }
48479
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
+ /**
48480
48702
  * Set queries against the server. At most {@link MAX_IN_FLIGHT} run at once:
48481
48703
  * many carry the whole member list, and the service may not queue them itself.
48482
48704
  */
48483
48705
  var SetQueries = class {
48484
48706
  expandCompose;
48707
+ parallelPages;
48485
48708
  inFlight = 0;
48486
48709
  waiting = [];
48487
- constructor(expandCompose) {
48710
+ constructor(expandCompose, parallelPages = false) {
48488
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
+ }
48489
48752
  }
48490
48753
  async expand(...args) {
48491
48754
  if (this.inFlight >= 8) await new Promise((resolve) => this.waiting.push(resolve));
@@ -48520,20 +48783,65 @@ var SetQueries = class {
48520
48783
  }
48521
48784
  /** Up to `max` concepts of the set with their terms, in the server's order, plus the set's exact total. */
48522
48785
  async concepts(compose, max, activeOnly = true) {
48523
- const concepts = [];
48524
- let total = 0;
48525
- for (let offset = 0; concepts.length < max;) {
48526
- const r = await this.expand(compose, {
48527
- count: Math.min(PAGE_SIZE, max - concepts.length),
48528
- offset,
48529
- activeOnly
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
48530
48823
  });
48531
- total = r.total;
48532
- if (r.concepts.length === 0) break;
48533
- for (const c of r.concepts) concepts.push(c);
48534
- offset += r.concepts.length;
48535
- if (offset >= total) break;
48536
- }
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);
48537
48845
  return {
48538
48846
  concepts,
48539
48847
  total
@@ -48545,20 +48853,17 @@ var SetQueries = class {
48545
48853
  */
48546
48854
  async graph(compose, max) {
48547
48855
  const graph = /* @__PURE__ */ new Map();
48548
- for (let offset = 0;;) {
48549
- const r = await this.expand(compose, {
48550
- count: PAGE_SIZE,
48551
- offset,
48552
- parents: true
48553
- });
48554
- if (r.total > max) return "too-large";
48555
- for (const c of r.concepts) {
48556
- if (!c.parents && c.code !== "138875005") return "no-parents";
48557
- graph.set(c.code, c.parents ?? []);
48558
- }
48559
- offset += r.concepts.length;
48560
- 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 ?? []);
48561
48865
  }
48866
+ return graph;
48562
48867
  }
48563
48868
  countEcl(ecl) {
48564
48869
  return this.count({ include: [{ ecl }] });
@@ -49056,122 +49361,439 @@ function chooseInclusions(candidates, inList, maxClauses) {
49056
49361
  // src/derive/taxonomy-graph.ts
49057
49362
  async function loadTaxonomyGraph(members, q, options) {
49058
49363
  const max = options.maxConcepts;
49059
- 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);
49060
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;
49061
49385
  const up = await q.graph({ include: [{ ecl: `>> ${members.ecl}` }] }, max);
49062
49386
  if (typeof up === "string") return refused(up, "the set with its ancestors");
49063
49387
  const childGraph = await q.graph({ include: [{ ecl: `<! (>> ${members.ecl})` }] }, max);
49064
49388
  if (typeof childGraph === "string") return refused(childGraph, "the children of those ancestors");
49065
- 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) {
49066
49406
  const roots = new Set(graph.roots());
49067
- 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)));
49068
49409
  if (down === "too-large" && options.fallbackDescend) {
49069
49410
  const fallback = options.fallbackDescend;
49070
- down = await descendantsOf(graph, (id) => fallback(id, graph), q, max);
49411
+ down = await fetch(loadFor((id) => fallback(id, graph)));
49071
49412
  graph.partial = true;
49072
49413
  }
49414
+ if (down === null) return null;
49073
49415
  if (typeof down === "string") return refused(down, "the descendants of the candidate groupers");
49074
49416
  graph.addBelow(down);
49075
49417
  return graph;
49076
49418
  }
49077
- /** `<< (the concepts of >> list with children that `pick` picks)`, empty when it picks none. */
49078
- async function descendantsOf(graph, pick, q, max) {
49079
- const load = graph.ancestors().filter((id) => graph.children(id).length > 0 && pick(id));
49080
- if (load.length === 0) return /* @__PURE__ */ new Map();
49081
- 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];
49082
49574
  }
49083
49575
  function refused(reason, what) {
49084
49576
  return { unavailable: reason === "no-parents" ? "parents" : what };
49085
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
+ */
49086
49583
  var LoadedGraph = class {
49087
49584
  members;
49088
- up;
49585
+ ids;
49089
49586
  partial = false;
49090
- parentMap = /* @__PURE__ */ new Map();
49091
- childMap = /* @__PURE__ */ new Map();
49092
- 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);
49093
49601
  cache = /* @__PURE__ */ new Map();
49094
- counts = /* @__PURE__ */ new Map();
49095
49602
  rootIds = [];
49096
- constructor(members, up, childGraph) {
49603
+ constructor(members, up, childGraph, ids) {
49097
49604
  this.members = members;
49098
- this.up = up;
49605
+ this.ids = ids;
49099
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
+ }
49100
49611
  this.merge(childGraph);
49101
- this.childMap = childrenOf(this.parentMap);
49102
49612
  this.countMembers();
49103
49613
  }
49104
49614
  /** Add `<< candidates`, so their descendants are complete. */
49105
49615
  addBelow(down) {
49106
49616
  this.merge(down);
49107
- for (const id of down.keys()) this.below.add(id);
49108
- this.childMap = childrenOf(this.parentMap);
49617
+ for (const i of down.keys()) this.flags[i] |= BELOW;
49109
49618
  this.cache.clear();
49110
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
+ }
49111
49650
  merge(graph) {
49112
- for (const [id, parents] of graph) {
49113
- const known = this.parentMap.get(id) ?? [];
49114
- for (const p of parents) if (!known.includes(p)) known.push(p);
49115
- 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;
49116
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);
49117
49685
  }
49118
49686
  countMembers() {
49119
49687
  const nonRoots = /* @__PURE__ */ new Set();
49120
- for (const m of this.members) for (const a of reachable(m, this.up)) {
49121
- this.counts.set(a, (this.counts.get(a) ?? 0) + 1);
49122
- 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;
49123
49700
  }
49124
49701
  this.rootIds.push(...[...this.members].filter((m) => !nonRoots.has(m)).sort(byId));
49125
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
+ }
49126
49722
  aboveMember(id) {
49127
- return this.up.has(id);
49723
+ const i = this.known(id);
49724
+ return i !== void 0 && (this.flags[i] & IN_UP) !== 0;
49128
49725
  }
49129
49726
  children(id) {
49130
- return this.childMap.get(id) ?? [];
49727
+ const i = this.known(id);
49728
+ return i === void 0 ? [] : this.names(this.childIdx[i]);
49131
49729
  }
49132
49730
  parents(id) {
49133
- return this.parentMap.get(id) ?? [];
49731
+ const i = this.known(id);
49732
+ return i === void 0 ? [] : this.names(this.parentIdx[i]);
49134
49733
  }
49135
49734
  descendants(id) {
49136
- 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);
49137
49738
  if (!list) {
49138
- list = [...reachable(id, this.childMap)];
49139
- this.cache.set(id, list);
49739
+ list = this.reachableDown(i);
49740
+ if (list.length >= CACHED_DESCENDANTS) this.cache.set(i, list);
49140
49741
  }
49141
- 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);
49142
49754
  }
49143
49755
  hasDescendants(id) {
49144
- 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;
49145
49759
  }
49146
49760
  truePos(id) {
49147
- 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);
49148
49779
  }
49149
49780
  roots() {
49150
49781
  return this.rootIds;
49151
49782
  }
49152
49783
  ancestors() {
49153
- 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);
49154
49785
  }
49155
49786
  };
49156
- function childrenOf(graph) {
49157
- const children = /* @__PURE__ */ new Map();
49158
- for (const [child, parents] of graph) for (const p of parents) {
49159
- const list = children.get(p) ?? [];
49160
- list.push(child);
49161
- children.set(p, list);
49162
- }
49163
- return children;
49164
- }
49165
- /** `start` and everything reachable from it along `edges`. */
49166
- function reachable(start, edges) {
49167
- const seen = /* @__PURE__ */ new Set([start]);
49168
- const stack = [start];
49169
- for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of edges.get(next) ?? []) {
49170
- if (seen.has(x)) continue;
49171
- seen.add(x);
49172
- stack.push(x);
49173
- }
49174
- 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;
49175
49797
  }
49176
49798
  // src/derive/refinements.ts
49177
49799
  /** Members whose relationships are read to profile the attributes the set shares. */
@@ -49212,19 +49834,39 @@ async function readRelationships(sample, getRelationships, notes) {
49212
49834
  return sampled;
49213
49835
  }
49214
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
+ /**
49215
49855
  * Refinement candidates for the set, likeliest first. `roots` are the set's
49216
49856
  * roots (all of them when `roots.total` fits); `givenFoci` come from the input
49217
49857
  * or the caller, and the most specific concept above every member is added
49218
49858
  * unless `fixedFocus` says the caller chose the focus.
49219
49859
  */
49220
- async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes) {
49860
+ async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes, batch = false) {
49221
49861
  const getRelationships = terminology.getDefiningRelationships?.bind(terminology);
49222
49862
  if (!getRelationships) {
49223
49863
  notes.push("Refinement candidates need a terminology service with getDefiningRelationships.");
49224
49864
  return [];
49225
49865
  }
49226
49866
  const sample = (await q.codes({ include: [members.clause] }, REFINEMENT_SAMPLE)).codes;
49227
- 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);
49228
49870
  const profiles = profileAttributes(sampled);
49229
49871
  if (profiles.length === 0) {
49230
49872
  notes.push("No attribute is shared by most members, so no refinement candidates were built.");
@@ -49469,7 +50111,13 @@ var DEFAULTS = {
49469
50111
  greedyGrouping: true,
49470
50112
  useGraph: true,
49471
50113
  maxGraphConcepts: 2e5,
49472
- critique: false
50114
+ critique: false,
50115
+ restrictTo: "auto",
50116
+ parallelPages: true,
50117
+ localScoring: false,
50118
+ scopedExclusions: true,
50119
+ walkGraph: true,
50120
+ batchLookups: true
49473
50121
  };
49474
50122
  var CRITIQUE_DEFAULTS = {
49475
50123
  maxClauses: 35,
@@ -49504,6 +50152,13 @@ var MAX_SUBTRACTED = 2;
49504
50152
  */
49505
50153
  async function deriveEcl(input, terminology, options = {}) {
49506
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");
49507
50162
  const opts = {
49508
50163
  ...DEFAULTS,
49509
50164
  ...options
@@ -49512,21 +50167,28 @@ async function deriveEcl(input, terminology, options = {}) {
49512
50167
  const q = new SetQueries((compose, o) => expandCompose(compose, {
49513
50168
  timeoutMs: opts.queryTimeoutMs,
49514
50169
  ...o
49515
- }));
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);
49516
50177
  const notes = [];
49517
- const { report, members } = await resolveInput(input, q, terminology, notes);
50178
+ const { report, members } = await resolveInput(input, q, terminology, notes, opts.walkGraph);
49518
50179
  const result = {
49519
50180
  input: report,
49520
50181
  hierarchies: [],
49521
50182
  roots: 0,
49522
50183
  candidates: [],
49523
- notes
50184
+ notes,
50185
+ failures: 0
49524
50186
  };
49525
50187
  if (!members) {
49526
50188
  if (notes.length === 0) notes.push("The input has no active concepts the server knows, so there is nothing to derive.");
49527
50189
  return result;
49528
50190
  }
49529
- const graph = opts.useGraph ? await loadGraph(members, q, opts, notes) : null;
50191
+ const graph = opts.useGraph ? await loadGraph(members, q, opts, notes, belowQueries) : null;
49530
50192
  const critique = critiqueOptions(opts.critique);
49531
50193
  let hierarchies = [];
49532
50194
  if (opts.hierarchySummary || critique) hierarchies = graph ? await graphHierarchies(graph, terminology) : await hierarchyDistribution(members, q);
@@ -49540,8 +50202,12 @@ async function deriveEcl(input, terminology, options = {}) {
49540
50202
  }, opts.maxRoots + 1);
49541
50203
  result.roots = rootQuery.total;
49542
50204
  const scorer = new Scorer(members, q, opts, notes);
49543
- if (graph) await scorer.score(worthCounting(graphCandidates(graph, opts, notes), inputCost(input, members), opts, notes));
49544
- 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));
49545
50211
  if (wantRefinements(opts.refinements, result.roots, scorer.scored)) await scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes);
49546
50212
  await scorer.score([inputItself(input, members)]);
49547
50213
  if (critique) result.critique = await buildCritique(critique, {
@@ -49552,9 +50218,11 @@ async function deriveEcl(input, terminology, options = {}) {
49552
50218
  hierarchies,
49553
50219
  scored: scorer.scored
49554
50220
  }, q, terminology, opts);
49555
- scorer.scored.sort((a, b) => byRank(rankOf(a), rankOf(b)));
49556
- const top = scorer.scored.slice(0, opts.maxCandidates);
49557
- 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);
49558
50226
  result.candidates = top.map((s) => ({
49559
50227
  expression: decorate(s.ecl, terms),
49560
50228
  ...s
@@ -49565,7 +50233,7 @@ async function deriveEcl(input, terminology, options = {}) {
49565
50233
  async function scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes) {
49566
50234
  let given = "ecl" in input ? refsetFoci(input.ecl) : [];
49567
50235
  if (opts.refinementFocus) given = [asFocus(opts.refinementFocus)];
49568
- 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 }) => ({
49569
50237
  ecl: refinementText(focus, clauses),
49570
50238
  construction: {
49571
50239
  kind: "refinement",
@@ -49596,7 +50264,7 @@ async function subtractions(scored, members, terminology, opts) {
49596
50264
  critique: false,
49597
50265
  omitTerms: true,
49598
50266
  maxCandidates: 3
49599
- })).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);
49600
50268
  if (d) built.push({
49601
50269
  ecl: `(${c.ecl}) MINUS (${d.ecl})`,
49602
50270
  construction: {
@@ -49616,6 +50284,7 @@ async function subtractions(scored, members, terminology, opts) {
49616
50284
  function wantRefinements(mode, roots, scored) {
49617
50285
  if (mode === "always") return true;
49618
50286
  if (mode === "never") return false;
50287
+ if (scored.some((c) => c.exact && c.construction.kind === "restricted-cover")) return false;
49619
50288
  if (roots > REFINEMENT_ROOTS) return true;
49620
50289
  return roots > 3 && !scored.some((c) => c.exact && c.clauses <= 3);
49621
50290
  }
@@ -49668,9 +50337,9 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
49668
50337
  return [];
49669
50338
  }
49670
50339
  const local = nearMissCandidates(graph, limits.nearMissShare, limits.nearMissMinSize).slice(0, limits.maxNearMisses * NEAR_MISS_CANDIDATES_PER_REPORTED);
49671
- 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({
49672
50341
  include: [{ ecl: `<< ${n.conceptId}` }],
49673
- exclude: [members.clause]
50342
+ exclude: [opts.scopedExclusions ? { concepts: graph.membersBelow(n.conceptId) } : members.clause]
49674
50343
  }, opts.sampleSize)));
49675
50344
  const confirmed = [];
49676
50345
  counted.forEach((r, i) => {
@@ -49697,6 +50366,34 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
49697
50366
  return found;
49698
50367
  }
49699
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
+ /**
49700
50397
  * Members that share a preferred term (CHK13): one listing of the members with
49701
50398
  * their terms, plus a lookup of the FSNs that tell each group apart.
49702
50399
  */
@@ -49709,7 +50406,7 @@ async function sharedTerms(max, members, q, terminology, opts, notes) {
49709
50406
  }
49710
50407
  let groups;
49711
50408
  try {
49712
- groups = findDuplicateTerms((await q.concepts({ include: [members.clause] }, members.size)).concepts);
50409
+ groups = findDuplicateTerms(members.concepts ?? (await q.concepts({ include: [members.clause] }, members.size)).concepts);
49713
50410
  } catch (error) {
49714
50411
  notes.push(`Shared terms were not checked: ${errorMessage(error)}.`);
49715
50412
  return [];
@@ -49783,7 +50480,7 @@ function formKey(ecl) {
49783
50480
  return ecl;
49784
50481
  }
49785
50482
  }
49786
- async function resolveInput(input, q, terminology, notes) {
50483
+ async function resolveInput(input, q, terminology, notes, lookUp = false) {
49787
50484
  if ("refsetId" in input) return resolveRefset(input.refsetId.trim(), q, terminology, notes);
49788
50485
  if ("ecl" in input) {
49789
50486
  const ecl = `(${stripTermsAndComments(input.ecl)})`;
@@ -49821,8 +50518,19 @@ async function resolveInput(input, q, terminology, notes) {
49821
50518
  members: null
49822
50519
  };
49823
50520
  const listed = { include: [{ concepts: wellFormed }] };
49824
- const active = (await q.codes(listed, wellFormed.length, true)).codes;
49825
- 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));
49826
50534
  const activeSet = new Set(active);
49827
50535
  report.inactive = wellFormed.filter((id) => known.has(id) && !activeSet.has(id));
49828
50536
  report.unknown = wellFormed.filter((id) => !known.has(id));
@@ -49831,15 +50539,73 @@ async function resolveInput(input, q, terminology, notes) {
49831
50539
  report,
49832
50540
  members: null
49833
50541
  };
50542
+ Object.freeze(active);
49834
50543
  return {
49835
50544
  report,
49836
50545
  members: {
49837
50546
  clause: { concepts: active },
49838
50547
  ecl: orGroup(active),
49839
- size: active.length
50548
+ size: active.length,
50549
+ concepts: activeConcepts.concepts,
50550
+ ...walk ? { walk } : {},
50551
+ ...walkable ? {} : { walkUnsupported: true }
49840
50552
  }
49841
50553
  };
49842
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
+ }
49843
50609
  async function resolveRefset(refsetId, q, terminology, notes) {
49844
50610
  const report = {
49845
50611
  given: 1,
@@ -49856,7 +50622,16 @@ async function resolveRefset(refsetId, q, terminology, notes) {
49856
50622
  const ecl = `(^ ${refsetId})`;
49857
50623
  report.members = await q.countEcl(ecl);
49858
50624
  if (report.members === 0) {
49859
- 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
+ }
49860
50635
  if (info === null) report.unknown.push(refsetId);
49861
50636
  else if (info.active) notes.push(`${refsetId} |${info.pt}| has no active members, or is not a reference set.`);
49862
50637
  else report.inactive.push(refsetId);
@@ -49896,14 +50671,19 @@ async function graphHierarchies(g, terminology) {
49896
50671
  })).sort((a, b) => b.count - a.count || byId(a.conceptId, b.conceptId));
49897
50672
  }
49898
50673
  /** The IS-A subgraph around the set, or null (with a note) when the per-query path must be used. */
49899
- async function loadGraph(members, q, opts, notes) {
50674
+ async function loadGraph(members, q, opts, notes, belowQueries) {
49900
50675
  let why;
49901
50676
  try {
49902
50677
  const graph = await loadTaxonomyGraph(members, q, {
49903
50678
  maxConcepts: opts.maxGraphConcepts,
49904
50679
  descend: (id, g) => coverDescend(id, g) || refactorDescend(id, g),
49905
- 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 } : {}
49906
50685
  });
50686
+ delete members.walk;
49907
50687
  if (!("unavailable" in graph)) {
49908
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.`);
49909
50689
  return graph;
@@ -49968,7 +50748,8 @@ function graphCandidates(g, opts, notes) {
49968
50748
  if (local) candidates.push({
49969
50749
  ecl,
49970
50750
  construction,
49971
- local
50751
+ local,
50752
+ form
49972
50753
  });
49973
50754
  }
49974
50755
  return candidates.sort((a, b) => byRank({
@@ -49981,6 +50762,70 @@ function graphCandidates(g, opts, notes) {
49981
50762
  ...b.local
49982
50763
  }));
49983
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
+ }
49984
50829
  /**
49985
50830
  * The lowest non-member concepts with every member below them, at most 3. Their
49986
50831
  * descendants may not be loaded: under `within` they are still worth counting
@@ -50391,6 +51236,82 @@ function exactScore(size) {
50391
51236
  clauses: 0
50392
51237
  };
50393
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
+ }
50394
51315
  /** Additions and misses of `ecl` against the set, counted and sampled by the server. */
50395
51316
  async function compare(ecl, members, q, sampleSize, within) {
50396
51317
  const counted = within ? `(${ecl}) AND (${within})` : ecl;
@@ -50409,7 +51330,13 @@ async function compare(ecl, members, q, sampleSize, within) {
50409
51330
  clauses: countClauses(ecl)
50410
51331
  };
50411
51332
  }
50412
- 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) {
50413
51340
  const ids = /* @__PURE__ */ new Set();
50414
51341
  for (const c of candidates) {
50415
51342
  if (c.clauses > MAX_DECORATED_CLAUSES) continue;
@@ -50417,7 +51344,13 @@ async function displayTerms(candidates, terminology) {
50417
51344
  }
50418
51345
  const terms = /* @__PURE__ */ new Map();
50419
51346
  if (ids.size === 0) return terms;
50420
- 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
+ }
50421
51354
  for (const [id, info] of infos) if (info?.pt) terms.set(id, info.pt);
50422
51355
  return terms;
50423
51356
  }
@@ -50497,6 +51430,7 @@ function bareSub(s) {
50497
51430
  function formatDeriveReport(result) {
50498
51431
  const lines = [];
50499
51432
  const { input } = result;
51433
+ if (result.failures > 0) lines.push(incompleteLine(result.failures));
50500
51434
  const duplicates = input.duplicates ? ` (${plural(input.duplicates, "duplicate")} ignored)` : "";
50501
51435
  lines.push(`Members: ${input.members} of ${input.given} distinct ids${duplicates}`);
50502
51436
  const leftOut = [
@@ -50555,6 +51489,10 @@ function reviewLines(c, inactiveListedAbove) {
50555
51489
  }
50556
51490
  return lines.length > 0 ? lines : ["Nothing flagged."];
50557
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
+ }
50558
51496
  function errorMessage(error) {
50559
51497
  return error instanceof Error ? error.message : String(error);
50560
51498
  }
@@ -50569,6 +51507,12 @@ function plural(n, noun) {
50569
51507
  * Needs a terminology service with `expandCompose`.
50570
51508
  */
50571
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) {
50572
51516
  const original = stripTermsAndComments(ecl);
50573
51517
  const parsed = parseECL(original);
50574
51518
  const result = {
@@ -50576,7 +51520,8 @@ async function compressExpression(ecl, terminology, options = {}) {
50576
51520
  group: null,
50577
51521
  candidates: [],
50578
51522
  notes: [],
50579
- errors: []
51523
+ errors: [],
51524
+ failures: 0
50580
51525
  };
50581
51526
  if (!parsed.ast || parsed.errors.length > 0) {
50582
51527
  result.errors = parsed.errors.map((e) => e.message);
@@ -50625,7 +51570,7 @@ async function compressExpression(ecl, terminology, options = {}) {
50625
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);
50626
51571
  const top = built.slice(0, options.maxCandidates ?? 8);
50627
51572
  for (const c of built) if (c.source !== "derived" && !top.includes(c)) top.push(c);
50628
- 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);
50629
51574
  result.candidates = top.map((c) => ({
50630
51575
  expression: decorate(c.ecl, terms),
50631
51576
  ...c,
@@ -50750,6 +51695,7 @@ function orInside(sub, text) {
50750
51695
  function formatCompressReport(result) {
50751
51696
  if (result.errors.length > 0) return `Not compressed: ${result.errors.join("; ")}`;
50752
51697
  const lines = [`Original selects ${result.members} concepts.`];
51698
+ if (result.failures > 0) lines.unshift(incompleteLine(result.failures));
50753
51699
  if (result.group && result.group.start > 0) lines.push(`Compressed group: ${result.group.text}`);
50754
51700
  for (const note of result.notes) lines.push(`Note: ${note}`);
50755
51701
  result.candidates.forEach((c, i) => {