node-autotask 0.68.0 → 0.69.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/MCP_TOOL_CATALOG.json +2 -2
  3. package/README.md +51 -10
  4. package/capabilities.json +7 -7
  5. package/dist/capabilities-data.js +6 -6
  6. package/dist/capabilities.cjs +4 -4
  7. package/dist/capabilities.js +1 -1
  8. package/dist/{chunk-HFWOHUVF.cjs → chunk-24GRFW55.cjs} +236 -222
  9. package/dist/{chunk-BF22HBNT.js → chunk-2BB7OASJ.js} +3 -30
  10. package/dist/{chunk-OUVUQQXH.js → chunk-AH6WAGPS.js} +80 -66
  11. package/dist/{chunk-CG6OPTFG.cjs → chunk-DPRY3CUJ.cjs} +30 -57
  12. package/dist/{chunk-V2GE763R.cjs → chunk-JLBSUZ5B.cjs} +993 -395
  13. package/dist/{chunk-SGH7F2CH.cjs → chunk-KAZE4WC7.cjs} +3 -3
  14. package/dist/{chunk-DPJLN5BB.js → chunk-QDBJCGQD.js} +986 -390
  15. package/dist/{chunk-JCMXQUIC.js → chunk-SCFB5MF3.js} +3 -3
  16. package/dist/{index-DQ08uOH0.d.ts → index-CxBU31jT.d.ts} +16 -9
  17. package/dist/{index-mIsdpO5d.d.cts → index-WZ3A8nG6.d.cts} +16 -9
  18. package/dist/index.cjs +92 -85
  19. package/dist/index.d.cts +3 -3
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +14 -7
  22. package/dist/operations/index.cjs +50 -50
  23. package/dist/operations/index.d.cts +2 -2
  24. package/dist/operations/index.d.ts +2 -2
  25. package/dist/operations/index.js +2 -2
  26. package/dist/pool.cjs +12 -12
  27. package/dist/pool.js +4 -4
  28. package/dist/resources/index.cjs +27 -27
  29. package/dist/resources/index.d.cts +1 -1
  30. package/dist/resources/index.d.ts +1 -1
  31. package/dist/resources/index.js +3 -3
  32. package/docs/API.md +77 -16
  33. package/docs/LIVE-TESTING.md +16 -2
  34. package/docs/VENDOR-QUIRKS.md +54 -0
  35. package/docs/performance-finance.md +35 -0
  36. package/examples/mcp-env-config.ts +3 -4
  37. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkSGH7F2CH_cjs = require('./chunk-SGH7F2CH.cjs');
3
+ var chunkKAZE4WC7_cjs = require('./chunk-KAZE4WC7.cjs');
4
4
  var chunkBD4AUGCJ_cjs = require('./chunk-BD4AUGCJ.cjs');
5
5
  var crypto = require('crypto');
6
6
  var async_hooks = require('async_hooks');
@@ -116,7 +116,7 @@ var ConflictError = class extends AutotaskError {
116
116
  var RateLimitError = class extends AutotaskError {
117
117
  /** Seconds the server asked the client to wait (`Retry-After`), when present. */
118
118
  retryAfter;
119
- /** True when the call was refused locally (the tenant cooldown gate) and never sent. */
119
+ /** True when the call was refused locally (cooldown or hourly admission) and never sent. */
120
120
  notSent;
121
121
  constructor(message, options = {}) {
122
122
  super(message, { code: "RATE_LIMITED", category: "rate_limit", retryable: true, ...options });
@@ -636,6 +636,7 @@ var TtlCache = class {
636
636
  ttlFor;
637
637
  store = /* @__PURE__ */ new Map();
638
638
  inflightMap = /* @__PURE__ */ new Map();
639
+ loads = /* @__PURE__ */ new Map();
639
640
  epochCounter = 0;
640
641
  constructor(ttlMs, options = {}) {
641
642
  if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
@@ -659,6 +660,85 @@ var TtlCache = class {
659
660
  }
660
661
  return structuredClone(entry.value);
661
662
  }
663
+ /**
664
+ * Load one record once for concurrent callers. Each subscriber owns its
665
+ * cancellation and receives a copy. The wire read is cancelled only when
666
+ * its last subscriber leaves. A fresh load starts a new flight and prevents
667
+ * an older flight from replacing its result; invalidation detaches flights
668
+ * without changing the answer owed to their existing subscribers.
669
+ * @internal
670
+ */
671
+ async load(key, loader, opts) {
672
+ const { signal } = opts;
673
+ if (signal?.aborted) throw opts.abortError();
674
+ if (!opts.fresh) {
675
+ const hit = this.get(key);
676
+ if (hit !== void 0) return hit;
677
+ }
678
+ let flight = opts.fresh ? void 0 : this.loads.get(key);
679
+ let start;
680
+ if (flight === void 0) {
681
+ const epoch = this.epoch;
682
+ const controller = new AbortController();
683
+ const created = { controller, promise: Promise.resolve(), subscribers: 0, settled: false };
684
+ created.promise = new Promise((resolve, reject) => {
685
+ start = () => {
686
+ try {
687
+ resolve(loader(controller.signal));
688
+ } catch (error) {
689
+ if (this.loads.get(key) === created) this.loads.delete(key);
690
+ reject(error);
691
+ }
692
+ };
693
+ }).then((value) => {
694
+ if (this.loads.get(key) === created && !controller.signal.aborted) this.set(key, value, epoch);
695
+ return value;
696
+ });
697
+ const settled = () => {
698
+ created.settled = true;
699
+ if (this.loads.get(key) === created) this.loads.delete(key);
700
+ };
701
+ created.promise.then(settled, settled);
702
+ this.loads.set(key, created);
703
+ flight = created;
704
+ }
705
+ const shared = flight;
706
+ shared.subscribers += 1;
707
+ const result = new Promise((resolve, reject) => {
708
+ let active = true;
709
+ const leave = () => {
710
+ if (!active) return false;
711
+ active = false;
712
+ signal?.removeEventListener("abort", aborted);
713
+ shared.subscribers -= 1;
714
+ if (shared.subscribers === 0 && !shared.settled) {
715
+ if (this.loads.get(key) === shared) this.loads.delete(key);
716
+ shared.controller.abort();
717
+ }
718
+ return true;
719
+ };
720
+ const aborted = () => {
721
+ if (leave()) reject(opts.abortError());
722
+ };
723
+ signal?.addEventListener("abort", aborted, { once: true });
724
+ shared.promise.then(
725
+ (value) => {
726
+ if (leave()) {
727
+ try {
728
+ resolve(structuredClone(value));
729
+ } catch (error) {
730
+ reject(error);
731
+ }
732
+ }
733
+ },
734
+ (error) => {
735
+ if (leave()) reject(error);
736
+ }
737
+ );
738
+ });
739
+ start?.();
740
+ return result;
741
+ }
662
742
  /** Store `value` under `key`. `epoch` is the value the caller read BEFORE its
663
743
  * wire request: a read that straddled a `clear()` (a write) is dropped. */
664
744
  set(key, value, epoch = this.epochCounter) {
@@ -693,12 +773,14 @@ var TtlCache = class {
693
773
  /** Drop one key. */
694
774
  delete(key) {
695
775
  this.inflightMap.delete(key);
776
+ this.loads.delete(key);
696
777
  return this.store.delete(key);
697
778
  }
698
779
  /** Drop every stored and in-flight key that starts with `prefix`. */
699
780
  invalidate(prefix) {
700
781
  for (const key of [...this.store.keys()]) if (key.startsWith(prefix)) this.store.delete(key);
701
782
  for (const key of [...this.inflightMap.keys()]) if (key.startsWith(prefix)) this.inflightMap.delete(key);
783
+ for (const key of [...this.loads.keys()]) if (key.startsWith(prefix)) this.loads.delete(key);
702
784
  }
703
785
  /** Drop every expired entry (returns the number removed). */
704
786
  purgeExpired() {
@@ -725,6 +807,7 @@ var TtlCache = class {
725
807
  this.epochCounter += 1;
726
808
  this.store.clear();
727
809
  this.inflightMap.clear();
810
+ this.loads.clear();
728
811
  }
729
812
  };
730
813
 
@@ -803,9 +886,10 @@ function cooldownDurationMs(retryAfterSecs, opts) {
803
886
  }
804
887
  return Math.min(retryAfterSecs !== void 0 ? retryAfterSecs * 1e3 : opts.defaultMs, opts.maxMs);
805
888
  }
806
- function admitMaintenance(host, ctx) {
889
+ function admitMaintenance(host, ctx, owned) {
807
890
  const gate = maintenance.get(host);
808
891
  if (gate === void 0) return "send";
892
+ if (gate === owned && gate.probing) return gate;
809
893
  const now = Date.now();
810
894
  if (!gate.probing && now >= gate.nextProbeAt) {
811
895
  gate.probing = true;
@@ -1447,8 +1531,8 @@ function buildFilter(conditions) {
1447
1531
  if (list.length === 0) {
1448
1532
  throw new AutotaskConfigError("buildFilter requires at least one condition");
1449
1533
  }
1450
- const root = list.length === 1 ? list[0] : { op: "and", items: list };
1451
- const filter = { filter: [root] };
1534
+ const root2 = list.length === 1 ? list[0] : { op: "and", items: list };
1535
+ const filter = { filter: [root2] };
1452
1536
  validateFilter(filter);
1453
1537
  return filter;
1454
1538
  }
@@ -1717,41 +1801,48 @@ function bodySnippet(text, redactPersonalData) {
1717
1801
 
1718
1802
  // src/http/limits.ts
1719
1803
  var HourlyBudget = class {
1720
- constructor(perHour, profile) {
1804
+ constructor(perHour, profile, scope = "local", stamps = []) {
1721
1805
  this.perHour = perHour;
1722
1806
  this.profile = profile;
1807
+ this.scope = scope;
1808
+ this.stamps = stamps;
1723
1809
  }
1724
1810
  perHour;
1725
1811
  profile;
1726
- /** Request timestamps inside the trailing hour. */
1727
- stamps = [];
1812
+ scope;
1813
+ stamps;
1728
1814
  prune(now) {
1729
- while (this.stamps.length > 0 && this.stamps[0] <= now - HOUR_MS) this.stamps.shift();
1815
+ let expired = 0;
1816
+ while (expired < this.stamps.length && this.stamps[expired] <= now - HOUR_MS) expired += 1;
1817
+ if (expired > 0) this.stamps.splice(0, expired);
1730
1818
  }
1731
1819
  snapshot() {
1732
1820
  this.prune(Date.now());
1733
1821
  return { perHour: this.perHour, used: this.stamps.length, remaining: Math.max(0, this.perHour - this.stamps.length) };
1734
1822
  }
1735
- /** Waits for a slot within the call budget, else throws. */
1736
- async take(deadlineAt, signal, ctx) {
1737
- for (; ; ) {
1738
- const now = Date.now();
1739
- this.prune(now);
1740
- if (this.stamps.length < this.perHour) {
1741
- this.stamps.push(now);
1742
- return;
1743
- }
1744
- const waitMs = this.stamps[0] + HOUR_MS - now;
1745
- if (waitMs >= deadlineAt - now) {
1746
- const err = new RateLimitError(`Client-side rateLimit.perHour (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s`, {
1747
- ...ctx,
1748
- suggestedAction: this.profile === "agent" ? "Stop or narrow the query \u2014 the LOCAL hourly budget is exhausted (per-process: it cannot see other instances or integrations on the tenant). Do NOT raise rateLimit.perHour; the window frees in about an hour." : "Back off until the hourly window frees a slot, or raise rateLimit.perHour."
1749
- });
1750
- err.retryAfter = Math.ceil(waitMs / 1e3);
1751
- throw err;
1823
+ /** Non-mutating admission check (apart from pruning); callers can inspect several quotas atomically. */
1824
+ waitMs(now) {
1825
+ this.prune(now);
1826
+ return this.stamps.length < this.perHour ? 0 : Math.max(0, this.stamps[0] + HOUR_MS - now);
1827
+ }
1828
+ /** Record an actual attempt immediately after every applicable quota was checked, without awaiting. */
1829
+ record(now) {
1830
+ this.stamps.push(now);
1831
+ }
1832
+ /** The typed local refusal. Its scope determines advice; the shared ceiling cannot be raised. */
1833
+ exhausted(waitMs, ctx) {
1834
+ const shared = this.scope === "origin";
1835
+ const err = new RateLimitError(
1836
+ shared ? `Shared origin hourly ceiling (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s` : `Client-side rateLimit.perHour (${this.perHour}) exhausted; next slot in ${Math.ceil(waitMs / 1e3)}s`,
1837
+ {
1838
+ ...ctx,
1839
+ details: { budgetScope: shared ? "process_origin" : "client" },
1840
+ suggestedAction: shared ? "Stop or narrow the query and coordinate traffic sharing this origin; retry after the hourly window frees a slot. The shared SDK ceiling cannot be raised and cannot account for external traffic." : this.profile === "agent" ? "Stop or narrow the query \u2014 the LOCAL hourly budget is exhausted (per-process: it cannot see other instances or integrations on the tenant). Do NOT raise rateLimit.perHour; the window frees in about an hour." : "Back off until the hourly window frees a slot, or raise rateLimit.perHour."
1752
1841
  }
1753
- await sleep(waitMs, signal);
1754
- }
1842
+ );
1843
+ err.retryAfter = Math.ceil(waitMs / 1e3);
1844
+ err.notSent = true;
1845
+ return err;
1755
1846
  }
1756
1847
  };
1757
1848
  var Semaphore = class {
@@ -1760,65 +1851,95 @@ var Semaphore = class {
1760
1851
  }
1761
1852
  maxConcurrent;
1762
1853
  inFlight = 0;
1763
- waitQueue = [];
1764
- acquire() {
1854
+ waitQueue = /* @__PURE__ */ new Set();
1855
+ acquire(signal) {
1856
+ if (signal?.aborted) return Promise.reject(signal.reason);
1765
1857
  if (this.inFlight < this.maxConcurrent) {
1766
1858
  this.inFlight += 1;
1767
1859
  return Promise.resolve();
1768
1860
  }
1769
- return new Promise((resolve) => {
1770
- this.waitQueue.push(() => {
1861
+ return new Promise((resolve, reject) => {
1862
+ const aborted = () => {
1863
+ this.waitQueue.delete(grant);
1864
+ signal?.removeEventListener("abort", aborted);
1865
+ reject(signal?.reason);
1866
+ };
1867
+ const grant = () => {
1868
+ signal?.removeEventListener("abort", aborted);
1771
1869
  this.inFlight += 1;
1772
1870
  resolve();
1773
- });
1871
+ };
1872
+ this.waitQueue.add(grant);
1873
+ signal?.addEventListener("abort", aborted, { once: true });
1774
1874
  });
1775
1875
  }
1776
1876
  release() {
1777
1877
  this.inFlight -= 1;
1778
- const next = this.waitQueue.shift();
1779
- if (next !== void 0) next();
1878
+ const next = this.waitQueue.values().next();
1879
+ if (!next.done) {
1880
+ this.waitQueue.delete(next.value);
1881
+ next.value();
1882
+ }
1780
1883
  }
1781
1884
  };
1782
1885
 
1783
- // src/http/credentials.ts
1784
- var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
1785
- "ApiIntegrationCode",
1786
- "UserName",
1787
- "Secret",
1788
- "ImpersonationResourceId"
1789
- ]);
1790
- function assertCredentialShape(headers, auth) {
1791
- const owned = new Set(CREDENTIAL_HEADER_NAMES);
1792
- for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
1793
- for (const name of Object.keys(headers)) {
1794
- if (!owned.has(name)) continue;
1795
- const value = headers[name];
1796
- const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
1797
- if (shape === void 0) continue;
1798
- throw new AutotaskConfigError(
1799
- `${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
1800
- {
1801
- code: "INVALID_CREDENTIAL_SHAPE",
1802
- suggestedAction: "Load the credential with the shell (`set -a; . ./.env; set +a`) or with loadAutotaskCredentialsFromEnv() from node-autotask; single-quoted values must be shell-sourced, not parsed by a quote-preserving loader. No request was sent."
1803
- }
1804
- );
1886
+ // src/http/hourly-gates.ts
1887
+ var ORIGIN_HOURLY_CEILING = 1e4;
1888
+ var REGISTRY = /* @__PURE__ */ Symbol.for("node-autotask.origin-hourly-gates.v1");
1889
+ var root = globalThis;
1890
+ var registry = root[REGISTRY] ??= { budgets: /* @__PURE__ */ new Map(), active: 0, waiting: 0, requests: 0 };
1891
+ function budgetFor(url) {
1892
+ const origin = new URL(url).origin.toLowerCase();
1893
+ let entry = registry.budgets.get(origin);
1894
+ if (entry === void 0) {
1895
+ for (const [key, previous] of registry.budgets) {
1896
+ if (new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", previous.stamps).snapshot().used === 0) registry.budgets.delete(key);
1897
+ }
1898
+ entry = { stamps: [] };
1899
+ registry.budgets.set(origin, entry);
1900
+ }
1901
+ return new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", entry.stamps);
1902
+ }
1903
+ function admitHourlyAttempt(url, local, now) {
1904
+ const origin = budgetFor(url);
1905
+ const budgets = local === void 0 ? [origin] : [local, origin];
1906
+ let blocked;
1907
+ for (const budget of budgets) {
1908
+ const waitMs = budget.waitMs(now);
1909
+ if (waitMs > (blocked?.waitMs ?? 0)) blocked = { admitted: false, budget, waitMs };
1910
+ }
1911
+ if (blocked !== void 0) return blocked;
1912
+ for (const budget of budgets) budget.record(now);
1913
+ registry.active += 1;
1914
+ let active = true;
1915
+ return { admitted: true, finish: () => {
1916
+ if (active) {
1917
+ active = false;
1918
+ registry.active -= 1;
1919
+ }
1920
+ } };
1921
+ }
1922
+ async function waitHourlyAdmission(blocked, deadlineAt, signal, ctx) {
1923
+ if (signal.aborted) throw signal.reason;
1924
+ const now = Date.now();
1925
+ const waitMs = blocked.budget.waitMs(now);
1926
+ if (waitMs === 0) return;
1927
+ if (waitMs >= deadlineAt - now) throw blocked.budget.exhausted(waitMs, ctx);
1928
+ registry.waiting += 1;
1929
+ try {
1930
+ await sleep(waitMs, signal);
1931
+ } finally {
1932
+ registry.waiting -= 1;
1805
1933
  }
1806
1934
  }
1807
- function credentialShapeExpectation(headers, auth) {
1808
- const owned = new Set(CREDENTIAL_HEADER_NAMES);
1809
- for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
1810
- const names = Object.keys(headers).filter((name) => owned.has(name));
1811
- if (names.length === 0) return void 0;
1812
- let problem;
1813
- for (const name of names) {
1814
- const value = headers[name];
1815
- problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
1816
- if (problem !== void 0) break;
1817
- }
1818
- return {
1819
- headerNames: names,
1820
- allValuesClean: problem === void 0,
1821
- ...problem !== void 0 ? { problem } : {}
1935
+ function trackHourlyRequest() {
1936
+ registry.requests += 1;
1937
+ let active = true;
1938
+ return () => {
1939
+ if (active) {
1940
+ active = false;
1941
+ registry.requests -= 1;
1942
+ }
1822
1943
  };
1823
1944
  }
1824
1945
 
@@ -14062,6 +14183,171 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
14062
14183
  ]
14063
14184
  };
14064
14185
 
14186
+ // src/http/object-key.ts
14187
+ var UNKNOWN_OBJECT_KEY = "unknown-object";
14188
+ var roots = /* @__PURE__ */ new Map();
14189
+ var byResource = /* @__PURE__ */ new Map();
14190
+ var byKey = /* @__PURE__ */ new Map();
14191
+ function descriptor(row) {
14192
+ const key = row.apiEntity ?? row.resource;
14193
+ let value = byKey.get(key);
14194
+ if (value === void 0) {
14195
+ value = { key, children: /* @__PURE__ */ new Map() };
14196
+ byKey.set(key, value);
14197
+ }
14198
+ return value;
14199
+ }
14200
+ for (const row of Object.values(RELATIONSHIP_MAP)) {
14201
+ const value = descriptor(row);
14202
+ byResource.set(row.resource, value);
14203
+ const path = row.path?.replace(/^\/?v\d+\.\d+\//i, "").replace(/^\//, "");
14204
+ if (path !== void 0 && !path.includes("/")) roots.set(path.toLowerCase(), value);
14205
+ }
14206
+ for (const [alias, resource] of [["expenses", "expense_reports"], ["userdefinedfields", "user_defined_field_definitions"]]) {
14207
+ const value = byResource.get(resource);
14208
+ if (value !== void 0) roots.set(alias, value);
14209
+ }
14210
+ for (const row of Object.values(RELATIONSHIP_MAP)) {
14211
+ const parent = row.parent === null ? void 0 : byResource.get(row.parent.resource);
14212
+ if (parent !== void 0 && row.parent?.segment != null) {
14213
+ parent.children.set(row.parent.segment.toLowerCase(), byResource.get(row.resource));
14214
+ }
14215
+ }
14216
+ function canonicalObjectKey(url) {
14217
+ let path;
14218
+ if (url instanceof URL) {
14219
+ if (url.protocol !== "https:" && url.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
14220
+ path = url.pathname;
14221
+ } else {
14222
+ try {
14223
+ if (/^[a-z][a-z\d+.-]*:/i.test(url)) {
14224
+ const parsed = new URL(url);
14225
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
14226
+ path = parsed.pathname;
14227
+ } else {
14228
+ if (!url.startsWith("/")) return UNKNOWN_OBJECT_KEY;
14229
+ path = url.split(/[?#]/, 1)[0];
14230
+ }
14231
+ } catch {
14232
+ return UNKNOWN_OBJECT_KEY;
14233
+ }
14234
+ }
14235
+ let parts;
14236
+ try {
14237
+ parts = path.split("/").filter(Boolean).map((part) => decodeURIComponent(part).toLowerCase());
14238
+ } catch {
14239
+ return UNKNOWN_OBJECT_KEY;
14240
+ }
14241
+ if (parts.some((part) => part === "." || part === ".." || /[/\\]/.test(part))) return UNKNOWN_OBJECT_KEY;
14242
+ const version = parts.findIndex((part) => /^v\d+\.\d+$/.test(part));
14243
+ if (version >= 0) {
14244
+ if (parts.slice(0, version).some((part) => roots.has(part))) return UNKNOWN_OBJECT_KEY;
14245
+ parts = parts.slice(version + 1);
14246
+ } else if (parts[0] === "atservicesrest") parts = parts.slice(1);
14247
+ let object = roots.get(parts[0] ?? "");
14248
+ if (object === void 0) return UNKNOWN_OBJECT_KEY;
14249
+ if (object.key === "zone_information") return parts.length === 1 ? void 0 : UNKNOWN_OBJECT_KEY;
14250
+ let offset = 1;
14251
+ while (offset < parts.length) {
14252
+ const part = parts[offset];
14253
+ if (/^\d+$/.test(part)) {
14254
+ offset++;
14255
+ if (offset === parts.length) return object.key;
14256
+ const child = object.children.get(parts[offset]);
14257
+ if (child !== void 0) {
14258
+ object = child;
14259
+ offset++;
14260
+ continue;
14261
+ }
14262
+ }
14263
+ const tail = parts.slice(offset);
14264
+ if (tail[0] === "query") return object.key;
14265
+ if (tail[0] === "entityinformation") return object.key;
14266
+ if (tail.length === 1) return object.key;
14267
+ return UNKNOWN_OBJECT_KEY;
14268
+ }
14269
+ return object.key;
14270
+ }
14271
+
14272
+ // src/http/object-threads.ts
14273
+ var REGISTRY2 = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-gates.v1");
14274
+ var OBJECT_THREAD_LIMIT = 3;
14275
+ var state = globalThis;
14276
+ async function acquireObjectThread(url, trackingIdentifier, signal) {
14277
+ if (signal.aborted) throw signal.reason;
14278
+ const target = new URL(url);
14279
+ const object = canonicalObjectKey(target.pathname);
14280
+ if (object === void 0) return () => void 0;
14281
+ const key = crypto.createHash("sha256").update(JSON.stringify([target.origin, trackingIdentifier.trim().toLowerCase(), object])).digest("hex");
14282
+ const registry2 = state[REGISTRY2] ??= /* @__PURE__ */ new Map();
14283
+ let entry = registry2.get(key);
14284
+ if (entry === void 0) {
14285
+ entry = { semaphore: new Semaphore(OBJECT_THREAD_LIMIT), users: 0 };
14286
+ registry2.set(key, entry);
14287
+ }
14288
+ const active = entry;
14289
+ active.users += 1;
14290
+ const leave = () => {
14291
+ active.users -= 1;
14292
+ if (active.users === 0 && registry2.get(key) === active) registry2.delete(key);
14293
+ };
14294
+ try {
14295
+ await active.semaphore.acquire(signal);
14296
+ } catch (error) {
14297
+ leave();
14298
+ throw error;
14299
+ }
14300
+ let released = false;
14301
+ return () => {
14302
+ if (released) return;
14303
+ released = true;
14304
+ active.semaphore.release();
14305
+ leave();
14306
+ };
14307
+ }
14308
+
14309
+ // src/http/credentials.ts
14310
+ var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
14311
+ "ApiIntegrationCode",
14312
+ "UserName",
14313
+ "Secret",
14314
+ "ImpersonationResourceId"
14315
+ ]);
14316
+ function assertCredentialShape(headers, auth) {
14317
+ const owned = new Set(CREDENTIAL_HEADER_NAMES);
14318
+ for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
14319
+ for (const name of Object.keys(headers)) {
14320
+ if (!owned.has(name)) continue;
14321
+ const value = headers[name];
14322
+ const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
14323
+ if (shape === void 0) continue;
14324
+ throw new AutotaskConfigError(
14325
+ `${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
14326
+ {
14327
+ code: "INVALID_CREDENTIAL_SHAPE",
14328
+ suggestedAction: "Load the credential with the shell (`set -a; . ./.env; set +a`) or with loadAutotaskCredentialsFromEnv() from node-autotask; single-quoted values must be shell-sourced, not parsed by a quote-preserving loader. No request was sent."
14329
+ }
14330
+ );
14331
+ }
14332
+ }
14333
+ function credentialShapeExpectation(headers, auth) {
14334
+ const owned = new Set(CREDENTIAL_HEADER_NAMES);
14335
+ for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
14336
+ const names = Object.keys(headers).filter((name) => owned.has(name));
14337
+ if (names.length === 0) return void 0;
14338
+ let problem;
14339
+ for (const name of names) {
14340
+ const value = headers[name];
14341
+ problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
14342
+ if (problem !== void 0) break;
14343
+ }
14344
+ return {
14345
+ headerNames: names,
14346
+ allValuesClean: problem === void 0,
14347
+ ...problem !== void 0 ? { problem } : {}
14348
+ };
14349
+ }
14350
+
14065
14351
  // src/http/envelope.ts
14066
14352
  var INVALID_SHAPE_ACTION = "Report the unexpected response shape; verify baseUrl points at the REST API.";
14067
14353
  function attachEmptyReasonDetails(err) {
@@ -14191,38 +14477,45 @@ function canReResolveZone(reResolveZoneOn401, zone, opts) {
14191
14477
  }
14192
14478
  async function discoverZoneBase(userName, maxResponseBytes, signal, ctx) {
14193
14479
  const discoveryUrl = `${ZONE_DISCOVERY_URL}?user=${encodeURIComponent(userName)}`;
14194
- let res;
14195
- try {
14196
- res = await fetch(discoveryUrl, {
14197
- method: "GET",
14198
- headers: { Accept: "application/json" },
14199
- redirect: "manual",
14200
- // a redirect off the discovery host is a fault, not a target
14201
- signal
14202
- });
14203
- } catch {
14204
- return void 0;
14205
- }
14206
- if (res.status < 200 || res.status >= 300) {
14207
- await res.body?.cancel().catch(() => void 0);
14208
- return void 0;
14209
- }
14210
- let text;
14480
+ if (signal.aborted) return void 0;
14481
+ const admission = admitHourlyAttempt(discoveryUrl, void 0, Date.now());
14482
+ if (!admission.admitted) return void 0;
14211
14483
  try {
14212
- text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14213
- } catch {
14214
- return void 0;
14215
- }
14216
- let body;
14217
- try {
14218
- body = JSON.parse(text);
14219
- } catch {
14220
- return void 0;
14221
- }
14222
- if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
14223
- return void 0;
14484
+ let res;
14485
+ try {
14486
+ res = await fetch(discoveryUrl, {
14487
+ method: "GET",
14488
+ headers: { Accept: "application/json" },
14489
+ redirect: "manual",
14490
+ // a redirect off the discovery host is a fault, not a target
14491
+ signal
14492
+ });
14493
+ } catch {
14494
+ return void 0;
14495
+ }
14496
+ if (res.status < 200 || res.status >= 300) {
14497
+ await res.body?.cancel().catch(() => void 0);
14498
+ return void 0;
14499
+ }
14500
+ let text;
14501
+ try {
14502
+ text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14503
+ } catch {
14504
+ return void 0;
14505
+ }
14506
+ let body;
14507
+ try {
14508
+ body = JSON.parse(text);
14509
+ } catch {
14510
+ return void 0;
14511
+ }
14512
+ if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
14513
+ return void 0;
14514
+ }
14515
+ return normalizeZoneBase(body.url);
14516
+ } finally {
14517
+ admission.finish();
14224
14518
  }
14225
- return normalizeZoneBase(body.url);
14226
14519
  }
14227
14520
 
14228
14521
  // src/http/HttpClient.ts
@@ -14339,8 +14632,9 @@ var HttpClient = class {
14339
14632
  /**
14340
14633
  * The LOCAL hourly-budget state (the sliding window this client counts):
14341
14634
  * `{ perHour, used, remaining }` — `undefined` when `rateLimit.perHour`
14342
- * is off. The limiter is PER PROCESS (issue #4): it cannot see other
14343
- * instances or integrations on the tenant — the tenant-wide count is
14635
+ * is off. This optional quota is PER CLIENT (issue #4); the separate
14636
+ * always-on origin ceiling is shared within the JavaScript realm. Neither
14637
+ * measures external integrations — the vendor-wide count is
14344
14638
  * `thresholdInformation.get()`.
14345
14639
  */
14346
14640
  hourlyBudget() {
@@ -14518,16 +14812,20 @@ var HttpClient = class {
14518
14812
  * zone maintenance gate (issue #285), which admits one probe per poll
14519
14813
  * interval while open. An already-aborted caller still gets the abort error.
14520
14814
  */
14521
- gate(s) {
14815
+ gate(s, auditRefusal = true) {
14522
14816
  const cooldown = this.cooldownEnabled && !s.opts.bypassCooldown ? cooldownRefusal(this.tenantKey, s.ctx) : void 0;
14523
- const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx);
14817
+ const owned = s.maintenanceProbe?.host === this.hostKey ? s.maintenanceProbe.gate : void 0;
14818
+ const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx, owned);
14524
14819
  if (verdict === "send") return;
14525
14820
  if (!(verdict instanceof AutotaskError)) {
14821
+ if (s.maintenanceProbe !== void 0 && (s.maintenanceProbe.host !== this.hostKey || s.maintenanceProbe.gate !== verdict)) {
14822
+ releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
14823
+ }
14526
14824
  s.maintenanceProbe = { host: this.hostKey, gate: verdict };
14527
14825
  return;
14528
14826
  }
14529
14827
  if (s.callerSignal?.aborted) throw this.interrupted(s);
14530
- this.auditNotSent(s, verdict.code);
14828
+ if (auditRefusal) this.auditNotSent(s, verdict.code);
14531
14829
  throw verdict;
14532
14830
  }
14533
14831
  // ---- the attempt --------------------------------------------------------
@@ -14538,18 +14836,51 @@ var HttpClient = class {
14538
14836
  */
14539
14837
  async sendOnce(s) {
14540
14838
  const { method, opts, ctx } = s;
14541
- try {
14542
- await this.hourly?.take(s.deadlineAt, s.signal, ctx);
14543
- } catch (err) {
14544
- if (s.signal.aborted) throw this.interrupted(s);
14545
- throw err;
14839
+ let release;
14840
+ for (; ; ) {
14841
+ try {
14842
+ await this.semaphore.acquire(s.signal);
14843
+ } catch (err) {
14844
+ if (s.signal.aborted) throw this.interrupted(s);
14845
+ throw err;
14846
+ }
14847
+ let releaseObject = () => void 0;
14848
+ let finishHourly = () => void 0;
14849
+ let released = false;
14850
+ const releaseCurrent = () => {
14851
+ if (released) return;
14852
+ released = true;
14853
+ finishHourly();
14854
+ releaseObject();
14855
+ this.semaphore.release();
14856
+ };
14857
+ try {
14858
+ releaseObject = await acquireObjectThread(s.url, this.auth.apiIntegrationCode, s.signal);
14859
+ if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
14860
+ this.gate(s, false);
14861
+ if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
14862
+ const admission = admitHourlyAttempt(s.url, this.hourly, Date.now());
14863
+ if (!admission.admitted) {
14864
+ releaseCurrent();
14865
+ await waitHourlyAdmission(admission, s.deadlineAt, s.signal, ctx);
14866
+ continue;
14867
+ }
14868
+ finishHourly = admission.finish;
14869
+ release = releaseCurrent;
14870
+ s.wireAttempts += 1;
14871
+ break;
14872
+ } catch (err) {
14873
+ releaseCurrent();
14874
+ if (s.signal.aborted) throw this.interrupted(s);
14875
+ if ((err instanceof RateLimitError || err instanceof MaintenanceError) && s.wireAttempts > 0) delete err.notSent;
14876
+ throw err;
14877
+ }
14546
14878
  }
14547
- await this.semaphore.acquire();
14548
14879
  let res;
14549
14880
  try {
14550
14881
  res = await fetch(s.url, { method, headers: s.headers, body: s.bodyText, signal: s.signal, redirect: "manual" });
14551
14882
  } catch (err) {
14552
- this.semaphore.release();
14883
+ release();
14553
14884
  if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
14554
14885
  const delay = backoffDelay(s.attempt);
14555
14886
  if (s.attempt < s.maxRetries && s.retriable5xx && await this.retryAfterDelay(s, delay, `network error on ${method} ${opts.path}`)) {
@@ -14573,7 +14904,7 @@ var HttpClient = class {
14573
14904
  }
14574
14905
  text = await readBodyText(res, this.maxResponseBytes, `${method} ${opts.path}`, { ...ctx, httpStatus: status });
14575
14906
  } catch (err) {
14576
- this.semaphore.release();
14907
+ release();
14577
14908
  if (err instanceof AutotaskError) throw err;
14578
14909
  if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
14579
14910
  throw new AutotaskNetworkError(
@@ -14581,7 +14912,7 @@ var HttpClient = class {
14581
14912
  ctx
14582
14913
  );
14583
14914
  }
14584
- this.semaphore.release();
14915
+ release();
14585
14916
  s.lastStatus = status;
14586
14917
  return { retry: false, res, status, text };
14587
14918
  }
@@ -14771,7 +15102,8 @@ var HttpClient = class {
14771
15102
  status: s.lastStatus,
14772
15103
  durationMs: Date.now() - s.started,
14773
15104
  body: s.auditBody,
14774
- errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR"
15105
+ errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR",
15106
+ ...s.wireAttempts === 0 ? { notSent: true } : {}
14775
15107
  });
14776
15108
  if (this.fieldCache !== void 0 && err instanceof AutotaskError) {
14777
15109
  const op = typeof opts.operation === "string" ? opts.operation : void 0;
@@ -14854,12 +15186,14 @@ var HttpClient = class {
14854
15186
  lastStatus: void 0,
14855
15187
  zoneRetry: void 0,
14856
15188
  attempt: 0,
15189
+ wireAttempts: 0,
14857
15190
  maintenanceProbe: void 0,
14858
15191
  maintenancePage: false,
14859
15192
  // Armed LAST in the literal: nothing after this can throw, and the single
14860
15193
  // try/finally below clears it on every exit path (#190).
14861
15194
  deadlineTimer: setTimeout(() => deadline.abort(), timeoutMs)
14862
15195
  };
15196
+ const finishRequest = trackHourlyRequest();
14863
15197
  try {
14864
15198
  this.gate(s);
14865
15199
  this.logger.debug?.(`[autotask] ${method} ${opts.path}`, correlationId);
@@ -14881,10 +15215,11 @@ var HttpClient = class {
14881
15215
  this.onFailure(s, err);
14882
15216
  throw err;
14883
15217
  } finally {
14884
- this.invalidateAfterWrite(opts);
15218
+ if (s.wireAttempts > 0) this.invalidateAfterWrite(opts);
14885
15219
  }
14886
15220
  } finally {
14887
15221
  clearTimeout(s.deadlineTimer);
15222
+ finishRequest();
14888
15223
  if (s.maintenanceProbe !== void 0) releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
14889
15224
  }
14890
15225
  }
@@ -14955,17 +15290,14 @@ async function collectAll(fetchPage, opts = {}) {
14955
15290
  return all;
14956
15291
  }
14957
15292
 
14958
- // src/search/company-names.ts
14959
- var LEGAL_SUFFIXES = /* @__PURE__ */ new Set(["pty", "ltd", "limited", "inc", "llc", "co", "corp", "gmbh"]);
14960
- var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "of"]);
14961
- function normaliseCompanyName(value) {
14962
- return value.normalize("NFKD").replace(new RegExp("\\p{M}+", "gu"), "").toLowerCase().replace(/&/g, " and ").replace(/[^\p{L}\p{N}]+/gu, " ").split(/\s+/).filter((t) => t && t !== "the").join(" ");
15293
+ // src/search/fuzzy-text.ts
15294
+ function normaliseText(value, options = {}) {
15295
+ let folded = value.normalize("NFKD").replace(new RegExp("\\p{M}+", "gu"), "").toLowerCase();
15296
+ if (options.ampersandAsAnd) folded = folded.replace(/&/g, " and ");
15297
+ return folded.replace(/[^\p{L}\p{N}]+/gu, " ").split(/\s+/).filter((term) => term && !options.excludeTerms?.has(term)).join(" ");
14963
15298
  }
14964
- function companyTerms(value) {
14965
- return normaliseCompanyName(value).split(" ").filter((t) => t && !LEGAL_SUFFIXES.has(t) && !STOPWORDS.has(t));
14966
- }
14967
- function companyDedupeName(value) {
14968
- return normaliseCompanyName(value).split(" ").filter((t) => !LEGAL_SUFFIXES.has(t)).join(" ");
15299
+ function textTerms(value, normalise = normaliseText, excludeTerms) {
15300
+ return normalise(value).split(" ").filter((term) => term && !excludeTerms?.has(term));
14969
15301
  }
14970
15302
  function ngramsOf(token) {
14971
15303
  if (token.length < 3) return [token];
@@ -15001,6 +15333,67 @@ function editDistanceAtMost(a, b, k) {
15001
15333
  }
15002
15334
  return previous[b.length];
15003
15335
  }
15336
+ function textFragments(terms) {
15337
+ const pieces = /* @__PURE__ */ new Set();
15338
+ const prefixes = /* @__PURE__ */ new Set();
15339
+ const longest = [...terms].sort((a, b) => b.length - a.length || a.localeCompare(b)).slice(0, 2);
15340
+ for (const word of longest) {
15341
+ const count = Math.max(1, Math.min(editBudget(word) + 1, Math.floor(word.length / 4)));
15342
+ for (let i = 0; i < count; i++) pieces.add(word.slice(Math.floor(i * word.length / count), Math.floor((i + 1) * word.length / count)));
15343
+ if (word.length >= 4 && word.length <= 6) prefixes.add(word.slice(0, 3));
15344
+ }
15345
+ if (terms.length > 1) pieces.add(terms.join(""));
15346
+ return { pieces: [...pieces], prefixes: [...prefixes] };
15347
+ }
15348
+ function scoreTerms(terms, words) {
15349
+ const candidates = [...words, words.join("")];
15350
+ const matchedTerms = [];
15351
+ let distance = 0;
15352
+ for (const term of terms) {
15353
+ const budget = editBudget(term);
15354
+ const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(term, word, budget)));
15355
+ if (best <= budget) {
15356
+ matchedTerms.push(term);
15357
+ distance += best;
15358
+ }
15359
+ }
15360
+ if (terms.length > 1) {
15361
+ const compact = terms.join("");
15362
+ const budget = editBudget(compact);
15363
+ const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(compact, word, budget)));
15364
+ if (best <= budget && matchedTerms.length < terms.length) return { coverage: terms.length, distance: best, matchedTerms: [...terms] };
15365
+ }
15366
+ return matchedTerms.length === 0 ? void 0 : { coverage: matchedTerms.length, distance, matchedTerms };
15367
+ }
15368
+ function compareTermScores(a, b) {
15369
+ return b.coverage - a.coverage || a.distance - b.distance;
15370
+ }
15371
+ function vocabularyCandidates(vocabulary, terms) {
15372
+ const keys = /* @__PURE__ */ new Set();
15373
+ for (const term of terms) {
15374
+ const budget = editBudget(term);
15375
+ const words = [...vocabulary.keys()].filter((word) => Math.abs(word.length - term.length) <= budget).map((word) => ({ word, dice: diceCoefficient(term, word) })).sort((a, b) => b.dice - a.dice);
15376
+ for (const { word } of words) if (editDistanceAtMost(term, word, budget) <= budget) {
15377
+ for (const key of vocabulary.get(word)) keys.add(key);
15378
+ }
15379
+ }
15380
+ return keys;
15381
+ }
15382
+
15383
+ // src/search/company-names.ts
15384
+ var LEGAL_SUFFIXES = /* @__PURE__ */ new Set(["pty", "ltd", "limited", "inc", "llc", "co", "corp", "gmbh"]);
15385
+ var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "of"]);
15386
+ var NAME_EXCLUSIONS = /* @__PURE__ */ new Set(["the"]);
15387
+ var SCORE_EXCLUSIONS = /* @__PURE__ */ new Set([...LEGAL_SUFFIXES, ...STOPWORDS]);
15388
+ function normaliseCompanyName(value) {
15389
+ return normaliseText(value, { ampersandAsAnd: true, excludeTerms: NAME_EXCLUSIONS });
15390
+ }
15391
+ function companyTerms(value) {
15392
+ return textTerms(value, normaliseCompanyName, SCORE_EXCLUSIONS);
15393
+ }
15394
+ function companyDedupeName(value) {
15395
+ return textTerms(value, normaliseCompanyName, LEGAL_SUFFIXES).join(" ");
15396
+ }
15004
15397
 
15005
15398
  // src/search/company-index.ts
15006
15399
  var COMPANY_INDEX_WRITE_DEBOUNCE_MS = 1e3;
@@ -15074,18 +15467,9 @@ var CompanyNameIndex = class {
15074
15467
  if (this.timer) clearTimeout(this.timer);
15075
15468
  if (this.started) this.start(COMPANY_INDEX_WRITE_DEBOUNCE_MS);
15076
15469
  }
15077
- /** Candidate generation uses n-gram Dice order, then the edit bound as authority.
15078
- * A Dice floor would lose valid short-word swaps, so zero-overlap vocabulary
15079
- * remains eligible when its length is within the edit budget. */
15470
+ /** The index owns company rows; the shared engine selects vocabulary keys. */
15080
15471
  candidates(terms) {
15081
- const ids2 = /* @__PURE__ */ new Set();
15082
- for (const term of terms) {
15083
- const budget = editBudget(term);
15084
- const words = [...this.vocabulary.keys()].filter((word) => Math.abs(word.length - term.length) <= budget).map((word) => ({ word, dice: diceCoefficient(term, word) })).sort((a, b) => b.dice - a.dice);
15085
- for (const { word } of words) if (editDistanceAtMost(term, word, budget) <= budget) {
15086
- for (const id of this.vocabulary.get(word)) ids2.add(id);
15087
- }
15088
- }
15472
+ const ids2 = vocabularyCandidates(this.vocabulary, terms);
15089
15473
  return [...ids2].map((id) => ({ ...this.rows.get(id) }));
15090
15474
  }
15091
15475
  schedule(delay, fn) {
@@ -15254,7 +15638,7 @@ async function capabilitySets() {
15254
15638
  const fieldOps = /* @__PURE__ */ new Map();
15255
15639
  const udfCapable = /* @__PURE__ */ new Set();
15256
15640
  const resources = /* @__PURE__ */ new Set();
15257
- for (const rec of await chunkSGH7F2CH_cjs.loadCapabilityRecords()) {
15641
+ for (const rec of await chunkKAZE4WC7_cjs.loadCapabilityRecords()) {
15258
15642
  if (rec.resource === "operations") continue;
15259
15643
  resources.add(rec.resource);
15260
15644
  if (rec.operation === "getFieldInfo") fieldOps.set(rec.resource, rec);
@@ -15265,7 +15649,7 @@ async function capabilitySets() {
15265
15649
  var derivedIndexPromise = null;
15266
15650
  function derivedIndexLoad() {
15267
15651
  if (derivedIndexPromise === null) {
15268
- derivedIndexPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => {
15652
+ derivedIndexPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => {
15269
15653
  const index = /* @__PURE__ */ new Map();
15270
15654
  for (const rec of records) {
15271
15655
  const declared = rec.metadata?.derivedFields;
@@ -15746,6 +16130,64 @@ function entityNameFromPath(resourcePath) {
15746
16130
  return snake;
15747
16131
  }
15748
16132
 
16133
+ // src/utils/bounded.ts
16134
+ async function runBounded(fn, items, opts) {
16135
+ const { concurrency, signal, settle } = opts;
16136
+ if (!Number.isInteger(concurrency) || concurrency <= 0) {
16137
+ throw new AutotaskConfigError("batch concurrency must be a positive integer");
16138
+ }
16139
+ const results = new Array(items.length);
16140
+ let next = 0;
16141
+ let failure;
16142
+ const fail = (error, index) => {
16143
+ if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
16144
+ };
16145
+ const worker = async () => {
16146
+ while (failure === void 0 && next < items.length) {
16147
+ if (signal?.aborted) {
16148
+ fail(signal.reason, -1);
16149
+ return;
16150
+ }
16151
+ const i = next++;
16152
+ try {
16153
+ const item = items[i];
16154
+ const value = await (signal === void 0 ? fn(item) : runWithSignal(signal, () => fn(item)));
16155
+ results[i] = settle ? { status: "fulfilled", value } : value;
16156
+ } catch (error) {
16157
+ if (settle) results[i] = { status: "rejected", reason: error };
16158
+ else fail(error, i);
16159
+ }
16160
+ }
16161
+ };
16162
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
16163
+ if (failure !== void 0) throw failure.error;
16164
+ return results;
16165
+ }
16166
+ async function mapReadTasks(http, items, fn) {
16167
+ const signal = ambientCallerSignal();
16168
+ const abort = () => new AutotaskAbortError("Read fan-out aborted by the caller");
16169
+ if (signal?.aborted) throw abort();
16170
+ try {
16171
+ const results = await runBounded(fn, items, { concurrency: http.maxConcurrent, orderedErrors: true, ...signal === void 0 ? {} : { signal } });
16172
+ if (signal?.aborted) throw abort();
16173
+ return results;
16174
+ } catch (error) {
16175
+ if (signal?.aborted && !(error instanceof AutotaskAbortError)) throw abort();
16176
+ throw error;
16177
+ }
16178
+ }
16179
+ function readTasks(http, tasks) {
16180
+ return mapReadTasks(http, tasks, (task) => task());
16181
+ }
16182
+
16183
+ // src/operations/nameSnapshot.ts
16184
+ function nameRecordSnapshot(cache, path, id, operation) {
16185
+ const body = cache?.get(path);
16186
+ if (body === void 0) return void 0;
16187
+ const entity = path.split("/").at(-2);
16188
+ return () => unwrapItem(body, id, operation, entity);
16189
+ }
16190
+
15749
16191
  // src/operations/expandResourceNames.ts
15750
16192
  var EXPAND_RESOURCE_NAMES_MAX_IDS = 500;
15751
16193
  function composeName(record) {
@@ -15756,6 +16198,27 @@ function composeName(record) {
15756
16198
  }
15757
16199
  return parts.length > 0 ? parts.join(" ") : null;
15758
16200
  }
16201
+ function resourceNameFailure(err) {
16202
+ if (err instanceof NotFoundError) return { name: null, blind: true };
16203
+ if (isAutotaskError(err) && err.code !== "ABORTED") {
16204
+ const error = { code: err.code, message: err.message };
16205
+ if (err.httpStatus !== void 0) error.httpStatus = err.httpStatus;
16206
+ return { name: null, blind: false, error };
16207
+ }
16208
+ throw err;
16209
+ }
16210
+ function resourceNameSnapshot(cache, id) {
16211
+ if (cache === void 0) return void 0;
16212
+ const path = `/V1.0/Resources/${id}`;
16213
+ if (cache.get(contextAbsentKey(path)) !== void 0) return { name: null, blind: true };
16214
+ const record = nameRecordSnapshot(cache, path, id, "resources.get");
16215
+ if (record === void 0) return void 0;
16216
+ try {
16217
+ return { name: composeName(record()), blind: false };
16218
+ } catch (err) {
16219
+ return resourceNameFailure(err);
16220
+ }
16221
+ }
15759
16222
  async function expandResourceNames(client, ids2, opts = {}) {
15760
16223
  if (opts.maxIds !== void 0 && (!Number.isInteger(opts.maxIds) || opts.maxIds < 1)) {
15761
16224
  throw new AutotaskConfigError(`expandResourceNames: maxIds must be an integer >= 1 (got ${String(opts.maxIds)})`);
@@ -15808,13 +16271,21 @@ async function expandResourceNames(client, ids2, opts = {}) {
15808
16271
  const holder = client.resources;
15809
16272
  const cache = client.http.readCache;
15810
16273
  const fresh = opts.fresh === true;
16274
+ const warm = /* @__PURE__ */ new Map();
16275
+ if (!fresh) {
16276
+ for (const id of unique) {
16277
+ const snapshot = resourceNameSnapshot(cache, id);
16278
+ if (snapshot !== void 0) warm.set(String(id), snapshot);
16279
+ }
16280
+ }
15811
16281
  const byId2 = /* @__PURE__ */ new Map();
15812
- for (const id of unique) {
16282
+ await mapReadTasks(client.http, unique, async (id) => {
15813
16283
  const k = String(id);
15814
16284
  const absentKey = contextAbsentKey(`/V1.0/Resources/${k}`);
15815
- if (cache !== void 0 && !fresh && cache.get(absentKey) !== void 0) {
15816
- byId2.set(k, { name: null, blind: true });
15817
- continue;
16285
+ const snapshot = warm.get(k);
16286
+ if (snapshot !== void 0) {
16287
+ byId2.set(k, snapshot);
16288
+ return;
15818
16289
  }
15819
16290
  const epoch = cache?.epoch ?? 0;
15820
16291
  try {
@@ -15825,17 +16296,11 @@ async function expandResourceNames(client, ids2, opts = {}) {
15825
16296
  if (err instanceof NotFoundError) {
15826
16297
  cache?.set(absentKey, CONTEXT_ABSENT_MARKER, epoch);
15827
16298
  byId2.set(k, { name: null, blind: true });
15828
- continue;
15829
- }
15830
- if (isAutotaskError(err) && err.code !== "ABORTED") {
15831
- const e = { code: err.code, message: err.message };
15832
- if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
15833
- byId2.set(k, { name: null, blind: false, error: e });
15834
- continue;
16299
+ return;
15835
16300
  }
15836
- throw err;
16301
+ byId2.set(k, resourceNameFailure(err));
15837
16302
  }
15838
- }
16303
+ });
15839
16304
  const results = [];
15840
16305
  for (const id of canonical) {
15841
16306
  const out = byId2.get(String(id));
@@ -16000,6 +16465,13 @@ var FK_TABLE_PATH = {
16000
16465
  company: "/V1.0/Companies",
16001
16466
  ticket: "/V1.0/Tickets"
16002
16467
  };
16468
+ var FK_GET_OPERATION = {
16469
+ role: "roles.get",
16470
+ billingCode: "billing_codes.get",
16471
+ contract: "contracts.get",
16472
+ company: "companies.get",
16473
+ ticket: "tickets.get"
16474
+ };
16003
16475
  var FK_NAME_FIELD = {
16004
16476
  role: "name",
16005
16477
  billingCode: "name",
@@ -16031,13 +16503,15 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16031
16503
  const readCache = http.readCache;
16032
16504
  const section = { truncated: false, rows: {}, reasons: {} };
16033
16505
  let remaining = budget;
16506
+ const tasks = [];
16034
16507
  let contractLobPointer;
16035
16508
  let contractLobUnread;
16036
16509
  const coldResource = [];
16510
+ const warmResources = /* @__PURE__ */ new Map();
16037
16511
  for (const id of plan.resourceIds) {
16038
- const path = `/V1.0/Resources/${id}`;
16039
- if (readCache !== void 0 && (readCache.peek(path).hit || readCache.peek(contextAbsentKey(path)).hit)) continue;
16040
- coldResource.push(id);
16512
+ const snapshot = resourceNameSnapshot(readCache, id);
16513
+ if (snapshot === void 0) coldResource.push(id);
16514
+ else warmResources.set(String(id), snapshot);
16041
16515
  }
16042
16516
  const withinBudget = coldResource.slice(0, remaining);
16043
16517
  const overBudgetResource = coldResource.slice(remaining);
@@ -16057,12 +16531,21 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16057
16531
  }
16058
16532
  pass = pass.slice(0, 500);
16059
16533
  }
16060
- const res = await expandResourceNames(client, pass);
16061
- for (const r of res.results) {
16062
- const row = { name: r.name, blind: r.blind };
16063
- if (r.error !== void 0) row.error = faultRow(r.error);
16064
- section.rows[`resource:${r.id}`] = row;
16065
- }
16534
+ tasks.push(async () => {
16535
+ const cold = pass.filter((id) => !warmResources.has(String(id)));
16536
+ const outcomes = new Map(warmResources);
16537
+ if (cold.length > 0) {
16538
+ for (const row of (await expandResourceNames(client, cold)).results) outcomes.set(String(row.id), row);
16539
+ }
16540
+ return () => {
16541
+ for (const id of pass) {
16542
+ const r = outcomes.get(String(id));
16543
+ const row = { name: r.name, blind: r.blind };
16544
+ if (r.error !== void 0) row.error = faultRow(r.error);
16545
+ section.rows[`resource:${id}`] = row;
16546
+ }
16547
+ };
16548
+ });
16066
16549
  }
16067
16550
  const holders = {
16068
16551
  role: client.roles,
@@ -16073,10 +16556,13 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16073
16556
  };
16074
16557
  for (const fk2 of plan.recordFks) {
16075
16558
  const key = `${fk2.table}:${fk2.id}`;
16076
- const cold = readCache === void 0 || readCache.get(`${FK_TABLE_PATH[fk2.table]}/${fk2.id}`) === void 0;
16559
+ const snapshot = nameRecordSnapshot(readCache, `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`, fk2.id, FK_GET_OPERATION[fk2.table]);
16560
+ const cold = snapshot === void 0;
16077
16561
  if (cold) {
16078
16562
  if (remaining < 1) {
16079
- section.rows[key] = { name: null, blind: false };
16563
+ tasks.push(async () => () => {
16564
+ section.rows[key] = { name: null, blind: false };
16565
+ });
16080
16566
  section.truncated = true;
16081
16567
  if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16082
16568
  contractLobUnread = "capped";
@@ -16085,41 +16571,51 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16085
16571
  }
16086
16572
  remaining -= 1;
16087
16573
  }
16088
- try {
16089
- const record = await holders[fk2.table].get(fk2.id);
16090
- if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16091
- contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16092
- }
16093
- section.rows[key] = { name: fkName(record, fk2.table), blind: false };
16094
- } catch (err) {
16095
- if (err instanceof NotFoundError) {
16096
- section.rows[key] = { name: null, blind: true };
16097
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16098
- section.rows[key] = { name: null, blind: false, error: faultRow(err) };
16099
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16100
- contractLobUnread = "unresolved";
16574
+ tasks.push(async () => {
16575
+ let row;
16576
+ try {
16577
+ const record = snapshot !== void 0 ? snapshot() : await holders[fk2.table].get(fk2.id);
16578
+ if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16579
+ contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16580
+ }
16581
+ row = { name: fkName(record, fk2.table), blind: false };
16582
+ } catch (err) {
16583
+ if (err instanceof NotFoundError) {
16584
+ row = { name: null, blind: true };
16585
+ } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16586
+ row = { name: null, blind: false, error: faultRow(err) };
16587
+ if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16588
+ contractLobUnread = "unresolved";
16589
+ }
16590
+ } else {
16591
+ throw err;
16101
16592
  }
16102
- } else {
16103
- throw err;
16104
16593
  }
16105
- }
16594
+ return () => {
16595
+ section.rows[key] = row;
16596
+ };
16597
+ });
16106
16598
  }
16107
16599
  const picklists = {};
16108
16600
  if (plan.labelFields.length > 0) {
16109
- try {
16110
- const labelResource = plan.labelResource ?? "tickets";
16111
- const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16112
- const row = catalog.rows.find((r) => r.resource === labelResource);
16113
- if (row !== void 0 && row.error === null && row.fields !== void 0) {
16114
- for (const f of plan.labelFields) {
16115
- const frow = row.fields.find((x) => x.name === f);
16116
- picklists[f] = frow?.picklistValues;
16601
+ tasks.push(async () => {
16602
+ try {
16603
+ const labelResource = plan.labelResource ?? "tickets";
16604
+ const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16605
+ const row = catalog.rows.find((r) => r.resource === labelResource);
16606
+ if (row !== void 0 && row.error === null && row.fields !== void 0) {
16607
+ for (const f of plan.labelFields) {
16608
+ const frow = row.fields.find((x) => x.name === f);
16609
+ picklists[f] = frow?.picklistValues;
16610
+ }
16117
16611
  }
16612
+ } catch (err) {
16613
+ if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16118
16614
  }
16119
- } catch (err) {
16120
- if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16121
- }
16615
+ return () => void 0;
16616
+ });
16122
16617
  }
16618
+ for (const merge of await readTasks(http, tasks)) merge();
16123
16619
  let lineOfBusiness2 = null;
16124
16620
  const lobId = plan.lineOfBusinessId ?? contractLobPointer;
16125
16621
  if (lobId !== void 0) {
@@ -16194,6 +16690,61 @@ var BOUNDED_QUERY_MAX_LIMIT = 2500;
16194
16690
  var LATEST_MAX_COUNT_PROBES = 64;
16195
16691
  var MARKER_RECOVERY_LIMIT = 5;
16196
16692
 
16693
+ // src/read-cache.ts
16694
+ var READ_FAILURE_OBSERVER = /* @__PURE__ */ Symbol("record read failure observer");
16695
+ function observeRecordReadFailures(http, observer) {
16696
+ Object.defineProperty(http, READ_FAILURE_OBSERVER, { value: observer });
16697
+ }
16698
+ function subscriberError(error, operation) {
16699
+ const copies = /* @__PURE__ */ new Map();
16700
+ const copyValue = (value) => {
16701
+ if (value === null || typeof value !== "object") return value;
16702
+ if (!(value instanceof Error) && !isRecord(value) && !Array.isArray(value)) return value;
16703
+ const prior = copies.get(value);
16704
+ if (prior !== void 0) return prior;
16705
+ const copy = value instanceof Error ? Object.setPrototypeOf(new Error(value.message), Object.getPrototypeOf(value)) : Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
16706
+ copies.set(value, copy);
16707
+ const descriptors = Object.getOwnPropertyDescriptors(value);
16708
+ if (value === error) descriptors.operation = { ...descriptors.operation, value: operation };
16709
+ for (const key of Reflect.ownKeys(descriptors)) {
16710
+ const descriptor2 = descriptors[key];
16711
+ if ("value" in descriptor2) descriptor2.value = copyValue(descriptor2.value);
16712
+ }
16713
+ Object.defineProperties(copy, descriptors);
16714
+ if (value instanceof Error && descriptors.stack?.set !== void 0) descriptors.stack.set.call(copy, value.stack);
16715
+ return copy;
16716
+ };
16717
+ return copyValue(error);
16718
+ }
16719
+ function cachedRecordGet(http, path, operation, fresh = false) {
16720
+ const cache = http.readCache;
16721
+ if (cache === void 0) return http.request({ method: "GET", path, operation });
16722
+ let ownsLoader = false;
16723
+ const loader = (signal) => {
16724
+ ownsLoader = true;
16725
+ return http.request({ method: "GET", path, operation, signal });
16726
+ };
16727
+ const options = {
16728
+ signal: ambientCallerSignal(),
16729
+ fresh,
16730
+ abortError: () => new AutotaskAbortError(`Request aborted: GET ${path}`, {
16731
+ operation,
16732
+ suggestedAction: "The caller aborted; re-issue the call if still needed."
16733
+ })
16734
+ };
16735
+ return cache.load(path, loader, options).catch((error) => {
16736
+ if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
16737
+ if (options.signal?.aborted) throw options.abortError();
16738
+ const warm = cache.get(path);
16739
+ return warm !== void 0 ? warm : cache.load(path, loader, { ...options, fresh: true });
16740
+ }).catch((error) => {
16741
+ if (!(error instanceof AutotaskError)) throw error;
16742
+ const failure = subscriberError(error, operation);
16743
+ http[READ_FAILURE_OBSERVER]?.(failure);
16744
+ throw failure;
16745
+ });
16746
+ }
16747
+
16197
16748
  // src/field-sets.ts
16198
16749
  var MODEL_FIELD_SETS = {
16199
16750
  "appointments": ["id", "createDateTime", "creatorResourceID", "description", "endDateTime", "resourceID", "startDateTime", "title", "updateDateTime"],
@@ -16606,14 +17157,14 @@ async function labelRows(client, resourceKey, rows) {
16606
17157
  return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
16607
17158
  }
16608
17159
  async function labelFetchResults(client, result) {
16609
- const byResource = /* @__PURE__ */ new Map();
17160
+ const byResource2 = /* @__PURE__ */ new Map();
16610
17161
  result.results.forEach((r, i) => {
16611
- if (r.found && r.value !== null) byResource.set(r.resource, [...byResource.get(r.resource) ?? [], i]);
17162
+ if (r.found && r.value !== null) byResource2.set(r.resource, [...byResource2.get(r.resource) ?? [], i]);
16612
17163
  });
16613
17164
  const results = [...result.results];
16614
17165
  const notes = [];
16615
17166
  const reasons = {};
16616
- for (const [resource, indices] of byResource) {
17167
+ for (const [resource, indices] of byResource2) {
16617
17168
  const labelled = await labelRows(client, resource, indices.map((i) => results[i].value));
16618
17169
  indices.forEach((idx, j) => {
16619
17170
  results[idx] = { ...results[idx], value: labelled.rows[j] };
@@ -16683,7 +17234,7 @@ var QueryBase = class {
16683
17234
  // Query walk (wired to the G3 walker; cursor-follow per the pinned wire)
16684
17235
  // ------------------------------------------------------------------
16685
17236
  /** One page fetch: page 1 POSTs the QueryModel body; later pages POST the same body (`buildQueryBody`) to the absolute cursor (issue #118). */
16686
- async fetchPage(params, page, pageSize, state) {
17237
+ async fetchPage(params, page, pageSize, state2) {
16687
17238
  if (params.includeFields !== void 0) {
16688
17239
  params = { ...params, includeFields: params.includeFields.map((field) => normalizeOwnField(this.config.key, field)) };
16689
17240
  }
@@ -16691,9 +17242,9 @@ var QueryBase = class {
16691
17242
  if (page === 1) {
16692
17243
  const req = buildQueryRequest(this.http.baseUrl, this.resourcePath, { ...params, maxRecords: pageSize });
16693
17244
  const body2 = await this.http.request({ ...req, operation });
16694
- return this.readPage(body2, page, pageSize, state);
17245
+ return this.readPage(body2, page, pageSize, state2);
16695
17246
  }
16696
- const cursor = state.cursor;
17247
+ const cursor = state2.cursor;
16697
17248
  if (cursor === null) {
16698
17249
  throw new AutotaskError(`No pagination cursor available for page ${page} of ${operation}`, {
16699
17250
  code: "INVALID_RESPONSE",
@@ -16709,13 +17260,13 @@ var QueryBase = class {
16709
17260
  operation,
16710
17261
  idempotent: true
16711
17262
  });
16712
- return this.readPage(res, page, pageSize, state);
17263
+ return this.readPage(res, page, pageSize, state2);
16713
17264
  }
16714
17265
  /** @internal */
16715
- readPage(body, page, pageSize, state) {
17266
+ readPage(body, page, pageSize, state2) {
16716
17267
  const { items, pageDetails } = unwrapItems(body, `${this.config.key}.query`);
16717
- state.cursor = pageDetails.nextPageUrl ?? null;
16718
- const hasMore = state.cursor !== null;
17268
+ state2.cursor = pageDetails.nextPageUrl ?? null;
17269
+ const hasMore = state2.cursor !== null;
16719
17270
  return {
16720
17271
  items,
16721
17272
  page,
@@ -16729,9 +17280,9 @@ var QueryBase = class {
16729
17280
  }
16730
17281
  /** Build the per-walk fetcher (closure keeps cursor state private to this walk). */
16731
17282
  pageFetcher(params) {
16732
- const state = { cursor: null };
17283
+ const state2 = { cursor: null };
16733
17284
  const p = params ?? {};
16734
- return (page, pageSize) => this.fetchPage(p, page, pageSize, state);
17285
+ return (page, pageSize) => this.fetchPage(p, page, pageSize, state2);
16735
17286
  }
16736
17287
  /** @internal */
16737
17288
  walkPageSize(params) {
@@ -16896,7 +17447,7 @@ var QueryBase = class {
16896
17447
  * state).
16897
17448
  * @internal */
16898
17449
  async walkBounded(p, limit, pageSizeBase, labelPages = false) {
16899
- const state = { cursor: null };
17450
+ const state2 = { cursor: null };
16900
17451
  const items = [];
16901
17452
  let pages2 = 0;
16902
17453
  let sliced = 0;
@@ -16909,7 +17460,7 @@ var QueryBase = class {
16909
17460
  guard = true;
16910
17461
  break;
16911
17462
  }
16912
- const page = await this.fetchPage(p, pages2 + 1, pageSize, state);
17463
+ const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
16913
17464
  pages2 += 1;
16914
17465
  if (labelPages && this.http.client !== void 0) {
16915
17466
  const labelled = await labelRows(this.http.client, this.config.key, page.items);
@@ -16930,7 +17481,7 @@ var QueryBase = class {
16930
17481
  note: [...nameNotes].join("; "),
16931
17482
  ...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
16932
17483
  };
16933
- return { items, pages: pages2, guard, sliced, cursor: state.cursor, ...names === void 0 ? {} : { names } };
17484
+ return { items, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
16934
17485
  }
16935
17486
  /** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
16936
17487
  * was met with a live next cursor (or a sliced final page): rows exist
@@ -17203,17 +17754,11 @@ var MetaBase = class extends QueryBase {
17203
17754
  * and the composite ROOT read of a hot resource (issue #36 — the
17204
17755
  * ticket-composite root) must see the live record, never a snapshot.
17205
17756
  * The entry's TTL follows the path (`readTtlFor`: reference tables 1 h).
17757
+ * Equivalent non-fresh misses share one request through the cache loader;
17758
+ * the ambient signal belongs to this subscriber, never to the shared wire.
17206
17759
  * @internal */
17207
17760
  async cachedGet(path, operation, fresh = false) {
17208
- const cache = this.http.readCache;
17209
- if (cache !== void 0 && !fresh) {
17210
- const hit = cache.get(path);
17211
- if (hit !== void 0) return hit;
17212
- }
17213
- const epoch = cache?.epoch;
17214
- const res = await this.http.request({ method: "GET", path, operation });
17215
- cache?.set(path, res, epoch);
17216
- return res;
17761
+ return cachedRecordGet(this.http, path, operation, fresh);
17217
17762
  }
17218
17763
  /**
17219
17764
  * Entity-metadata read through the opt-in field cache (issue #31; off by
@@ -17562,8 +18107,8 @@ var MetaBase = class extends QueryBase {
17562
18107
  );
17563
18108
  }
17564
18109
  const leaf = fields.map((field) => ({ field, op: "eq", value }));
17565
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17566
- const items = await this.queryPage1([root], 2);
18110
+ const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18111
+ const items = await this.queryPage1([root2], 2);
17567
18112
  if (items.length === 1) {
17568
18113
  return { value: items[0], resolutionCost: "server-filter", scanned: 0, scanTruncated: false };
17569
18114
  }
@@ -17669,13 +18214,13 @@ var MetaBase = class extends QueryBase {
17669
18214
  async scanForExactMatch(value, fields) {
17670
18215
  const caps = this.resolutionCaps;
17671
18216
  const pageSize = Math.max(1, Math.floor(caps.maxScanRecords / caps.maxScanPages));
17672
- const state = { cursor: null };
18217
+ const state2 = { cursor: null };
17673
18218
  let scanned = 0;
17674
18219
  let pages2 = 0;
17675
18220
  let found = null;
17676
18221
  let exhausted = false;
17677
18222
  for (; ; ) {
17678
- const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state);
18223
+ const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state2);
17679
18224
  pages2 += 1;
17680
18225
  for (const item of page.items) {
17681
18226
  scanned += 1;
@@ -17730,7 +18275,7 @@ var MetaBase = class extends QueryBase {
17730
18275
  }
17731
18276
  const limit = opts.limit === void 0 ? 25 : clampPageSize(opts.limit);
17732
18277
  const leaf = fields.map((field) => ({ field, op: "contains", value: text }));
17733
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18278
+ const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17734
18279
  for (const key of Object.keys(opts)) {
17735
18280
  if (key !== "limit" && key !== "companyID" && key !== "includeFields") {
17736
18281
  throw new AutotaskConfigError(`search: unknown opts key "${key}" \u2014 the bag is closed: limit, companyID, includeFields`);
@@ -17744,7 +18289,7 @@ var MetaBase = class extends QueryBase {
17744
18289
  }
17745
18290
  const companyID = opts.companyID === void 0 ? void 0 : Number(opts.companyID);
17746
18291
  const includeFields = opts.includeFields === void 0 ? void 0 : opts.includeFields.includes("id") ? opts.includeFields : ["id", ...opts.includeFields];
17747
- const conditions = companyID === void 0 ? [root] : [{ field: "companyID", op: "eq", value: companyID }, root];
18292
+ const conditions = companyID === void 0 ? [root2] : [{ field: "companyID", op: "eq", value: companyID }, root2];
17748
18293
  const rows = await this.queryEntity(`${this.resourcePath}/query`, conditions, {
17749
18294
  maxRecords: limit,
17750
18295
  ...includeFields !== void 0 ? { includeFields } : {}
@@ -20017,20 +20562,20 @@ var GenericResource = class extends BaseResource {
20017
20562
  this.requireHelper("getContext");
20018
20563
  const cfg = this.config;
20019
20564
  const rootField = cfg.contextRootField ?? this.config.key;
20020
- const root = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20021
- const result = { [rootField]: root };
20022
- for (const [name, idField, targetPath] of cfg.contextParts ?? []) {
20023
- result[name] = await this.contextFetch(targetPath, root[idField]);
20024
- }
20565
+ const root2 = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20566
+ const result = { [rootField]: root2 };
20567
+ const parts = cfg.contextParts ?? [];
20568
+ const values = await mapReadTasks(this.http, parts, ([, idField, targetPath]) => this.contextFetch(targetPath, root2[idField]));
20569
+ for (const [i, [name]] of parts.entries()) result[name] = values[i];
20025
20570
  if (opts.names === true) {
20026
20571
  const builder = createNamePlan();
20027
20572
  for (const sib of cfg.nameSiblings ?? []) {
20028
- const fk2 = root[sib.field];
20573
+ const fk2 = root2[sib.field];
20029
20574
  if (sib.kind === "resource") builder.addResource(fk2);
20030
20575
  else builder.addFk(sib.kind, fk2);
20031
20576
  }
20032
20577
  const names = await resolveCompositeNames(this.http, builder.plan(), { maxNameReads: opts.maxNameReads });
20033
- const row = { ...root };
20578
+ const row = { ...root2 };
20034
20579
  for (const sib of cfg.nameSiblings ?? []) {
20035
20580
  addNameSibling(row, sib.field, (v) => sib.kind === "resource" ? names.resourceName(v) : names.recordName(sib.kind, v));
20036
20581
  }
@@ -20182,37 +20727,11 @@ function prepare(query, opts) {
20182
20727
  return { terms, limit };
20183
20728
  }
20184
20729
  function companyPieces(terms) {
20185
- const pieces = /* @__PURE__ */ new Set();
20186
- const prefixes = /* @__PURE__ */ new Set();
20187
- const longest = [...terms].sort((a, b) => b.length - a.length || a.localeCompare(b)).slice(0, 2);
20188
- for (const word of longest) {
20189
- const count = Math.max(1, Math.min(editBudget(word) + 1, Math.floor(word.length / 4)));
20190
- for (let i = 0; i < count; i++) pieces.add(word.slice(Math.floor(i * word.length / count), Math.floor((i + 1) * word.length / count)));
20191
- if (word.length >= 4 && word.length <= 6) prefixes.add(word.slice(0, 3));
20192
- }
20193
- if (terms.length > 1) pieces.add(terms.join(""));
20194
- return { pieces: [...pieces], prefixes: [...prefixes] };
20730
+ return textFragments(terms);
20195
20731
  }
20196
20732
  function score(record, terms, source) {
20197
- const words = companyTerms(record.companyName ?? "");
20198
- const candidates = [...words, words.join("")];
20199
- const matchedTerms = [];
20200
- let distance = 0;
20201
- for (const term of terms) {
20202
- const budget = editBudget(term);
20203
- const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(term, word, budget)));
20204
- if (best <= budget) {
20205
- matchedTerms.push(term);
20206
- distance += best;
20207
- }
20208
- }
20209
- if (terms.length > 1) {
20210
- const compact = terms.join("");
20211
- const budget = editBudget(compact);
20212
- const best = Math.min(budget + 1, ...candidates.map((word) => editDistanceAtMost(compact, word, budget)));
20213
- if (best <= budget && matchedTerms.length < terms.length) return { record, source, coverage: terms.length, distance: best, matchedTerms: [...terms] };
20214
- }
20215
- return matchedTerms.length === 0 ? void 0 : { record, source, coverage: matchedTerms.length, distance, matchedTerms };
20733
+ const match = scoreTerms(terms, companyTerms(record.companyName ?? ""));
20734
+ return match === void 0 ? void 0 : { record, source, ...match };
20216
20735
  }
20217
20736
  async function searchFuzzy(resource, query, opts = {}) {
20218
20737
  const { terms, limit } = prepare(query, opts);
@@ -20225,9 +20744,9 @@ async function searchFuzzy(resource, query, opts = {}) {
20225
20744
  if (!opts.includeInactive) filter.push({ field: "isActive", op: "eq", value: true });
20226
20745
  const index = companyIndex(resource.http);
20227
20746
  index?.ensure();
20228
- const state = index?.state() ?? { state: "off" };
20747
+ const state2 = index?.state() ?? { state: "off" };
20229
20748
  const revision = index?.revision();
20230
- const indexed = state.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20749
+ const indexed = state2.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20231
20750
  const res = await resource.http.request({
20232
20751
  method: "POST",
20233
20752
  idempotent: true,
@@ -20240,13 +20759,13 @@ async function searchFuzzy(resource, query, opts = {}) {
20240
20759
  const validIndex = index?.revision() === revision;
20241
20760
  for (const row of validIndex ? indexed : []) if (typeof row.id === "number") merged.set(row.id, { row, source: "index" });
20242
20761
  for (const row of live) if (typeof row.id === "number") merged.set(row.id, { row: slimCompany(row), source: merged.has(row.id) ? "both" : "live" });
20243
- const ranked = [...merged.values()].filter(({ row }) => opts.includeInactive || row.isActive === true).map(({ row, source }) => score(row, terms, source)).filter((row) => row !== void 0).sort((a, b) => b.coverage - a.coverage || a.distance - b.distance || Number(b.record.isActive === true) - Number(a.record.isActive === true) || (a.record.id ?? 0) - (b.record.id ?? 0));
20762
+ const ranked = [...merged.values()].filter(({ row }) => opts.includeInactive || row.isActive === true).map(({ row, source }) => score(row, terms, source)).filter((row) => row !== void 0).sort((a, b) => compareTermScores(a, b) || Number(b.record.isActive === true) - Number(a.record.isActive === true) || (a.record.id ?? 0) - (b.record.id ?? 0));
20244
20763
  const items = ranked.slice(0, limit);
20245
20764
  if (opts.includeFamily) {
20246
20765
  const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
20247
20766
  for (let i = 0; i < items.length; i++) items[i].record = records[i];
20248
20767
  }
20249
- return { items, tier: state.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state : index.state() };
20768
+ return { items, tier: state2.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state2 : index.state() };
20250
20769
  }
20251
20770
 
20252
20771
  // src/operations/invoke/fieldNames.ts
@@ -20420,13 +20939,17 @@ async function readFields(http, fresh) {
20420
20939
  const hit = cache.get(key);
20421
20940
  if (hit !== void 0) return hit;
20422
20941
  }
20423
- const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
20424
- const fields = res?.fields;
20425
- if (!Array.isArray(fields)) {
20426
- throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20427
- }
20428
- if (fields.length > 0) cache?.set(key, fields);
20429
- return fields;
20942
+ const epoch = cache?.epoch;
20943
+ const work = (async () => {
20944
+ const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
20945
+ const fields = res?.fields;
20946
+ if (!Array.isArray(fields)) {
20947
+ throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20948
+ }
20949
+ if (fields.length > 0) cache?.set(key, fields, epoch);
20950
+ return fields;
20951
+ })();
20952
+ return cache !== void 0 && !fresh ? cache.track(key, work) : work;
20430
20953
  }
20431
20954
  function assumed(allowAssumed, operation) {
20432
20955
  if (!allowAssumed) {
@@ -20648,14 +21171,16 @@ async function fullProfile(resource, id, opts = {}) {
20648
21171
  const proj = validateProjection(opts.fields);
20649
21172
  const companyID = parseIdentifier(id, "id");
20650
21173
  const company = await resource.get(companyID);
20651
- const locations = await scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations);
20652
- const contacts = await scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts);
20653
- const notes = await scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes);
20654
- const projects = await scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects);
20655
- const openTickets = await readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
20656
- ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
20657
- ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
20658
- });
21174
+ const [locations, contacts, notes, projects, openTickets] = await readTasks(http, [
21175
+ () => scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations),
21176
+ () => scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts),
21177
+ () => scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes),
21178
+ () => scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects),
21179
+ () => readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
21180
+ ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
21181
+ ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
21182
+ })
21183
+ ]);
20659
21184
  const result = {
20660
21185
  company,
20661
21186
  locations: { items: locations, capped: locations.length >= locLimit },
@@ -20915,11 +21440,7 @@ async function fetchCompanies(http, ids2, limit) {
20915
21440
  const out = [];
20916
21441
  for (const id of ids2.slice(0, limit)) {
20917
21442
  try {
20918
- const res = await http.request({
20919
- method: "GET",
20920
- path: `/V1.0/Companies/${id}`,
20921
- operation: "companies.searchByDomain"
20922
- });
21443
+ const res = await cachedRecordGet(http, `/V1.0/Companies/${id}`, "companies.searchByDomain");
20923
21444
  const body = res;
20924
21445
  const item = body && "item" in body ? body.item : null;
20925
21446
  if (item) out.push(item);
@@ -21355,9 +21876,11 @@ var CompaniesResource = class extends GenericResource {
21355
21876
  * fetch; no sub-lists; absent/dangling references come back null). */
21356
21877
  async getContext(id) {
21357
21878
  const company = await this.fetchRecordRaw("/V1.0/Companies", id);
21358
- const root = company;
21359
- const ownerResource = await this.contextFetch("/V1.0/Resources", root["ownerResourceID"]);
21360
- const parentCompany = await this.contextFetch("/V1.0/Companies", root["parentCompanyID"]);
21879
+ const root2 = company;
21880
+ const [ownerResource, parentCompany] = await readTasks(this.http, [
21881
+ () => this.contextFetch("/V1.0/Resources", root2["ownerResourceID"]),
21882
+ () => this.contextFetch("/V1.0/Companies", root2["parentCompanyID"])
21883
+ ]);
21361
21884
  return { company, ownerResource, parentCompany };
21362
21885
  }
21363
21886
  /** Node-parity special op (hand-written in src/resources/special/companies/search.ts). */
@@ -21905,7 +22428,7 @@ function dateBucketLabel(value, bucket) {
21905
22428
  var queryResourceKeysPromise = null;
21906
22429
  function queryResourceKeys() {
21907
22430
  if (queryResourceKeysPromise === null) {
21908
- queryResourceKeysPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => {
22431
+ queryResourceKeysPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => {
21909
22432
  const s = /* @__PURE__ */ new Set();
21910
22433
  for (const rec of records) if (rec.operation === "query") s.add(rec.resource);
21911
22434
  return s;
@@ -22027,7 +22550,7 @@ function parseTopAndLimit(opts, problems) {
22027
22550
  return { top, limit };
22028
22551
  }
22029
22552
  async function checkFieldNames(resourceKey, conditions, opts, problems) {
22030
- const records = resourceKey === void 0 ? [] : await chunkSGH7F2CH_cjs.loadCapabilityRecords();
22553
+ const records = resourceKey === void 0 ? [] : await chunkKAZE4WC7_cjs.loadCapabilityRecords();
22031
22554
  const record = resourceKey === void 0 ? void 0 : records.find((r) => r.resource === resourceKey && r.operation === "query");
22032
22555
  if (record === void 0) return void 0;
22033
22556
  const strings = (v) => Array.isArray(v) ? v.filter((f) => typeof f === "string" && f.trim() !== "") : [];
@@ -22437,7 +22960,7 @@ async function fetchByIds(client, items, opts = {}) {
22437
22960
  }
22438
22961
  groups.set(item.resource, g);
22439
22962
  }
22440
- const byKey = /* @__PURE__ */ new Map();
22963
+ const byKey2 = /* @__PURE__ */ new Map();
22441
22964
  for (const [key, group] of groups) {
22442
22965
  const holder = client[camelKey(key)];
22443
22966
  if (holder === void 0) {
@@ -22466,28 +22989,28 @@ async function fetchByIds(client, items, opts = {}) {
22466
22989
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22467
22990
  for (const u of chunk) {
22468
22991
  const q = kOf(u);
22469
- if (!byKey.has(q)) byKey.set(q, { found: false, value: null, error: e });
22992
+ if (!byKey2.has(q)) byKey2.set(q, { found: false, value: null, error: e });
22470
22993
  }
22471
22994
  return true;
22472
22995
  }
22473
22996
  });
22474
22997
  for (const [k, row] of foundRows) {
22475
22998
  const q = kOf(k);
22476
- if (!byKey.has(q)) byKey.set(q, { found: true, value: row });
22999
+ if (!byKey2.has(q)) byKey2.set(q, { found: true, value: row });
22477
23000
  }
22478
23001
  for (const id of unique) {
22479
23002
  const k = kOf(id);
22480
- if (byKey.has(k)) continue;
23003
+ if (byKey2.has(k)) continue;
22481
23004
  try {
22482
23005
  const value = await holder.get(id);
22483
- byKey.set(k, { found: true, value });
23006
+ byKey2.set(k, { found: true, value });
22484
23007
  } catch (err) {
22485
23008
  if (err instanceof NotFoundError) {
22486
- byKey.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
23009
+ byKey2.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
22487
23010
  } else if (isAutotaskError(err) && err.code !== "ABORTED") {
22488
23011
  const e = { code: err.code, message: err.message };
22489
23012
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22490
- byKey.set(k, { found: false, value: null, error: e });
23013
+ byKey2.set(k, { found: false, value: null, error: e });
22491
23014
  } else {
22492
23015
  throw err;
22493
23016
  }
@@ -22498,7 +23021,7 @@ async function fetchByIds(client, items, opts = {}) {
22498
23021
  for (let i = 0; i < items.length; i += 1) {
22499
23022
  const item = items[i];
22500
23023
  const id = canonical[i];
22501
- const out = byKey.get(`${item.resource}:${String(id)}`);
23024
+ const out = byKey2.get(`${item.resource}:${String(id)}`);
22502
23025
  const value = out.found ? item.fields !== void 0 ? project2(out.value, item.fields) : out.value : null;
22503
23026
  results.push(
22504
23027
  out.found ? { resource: item.resource, id, found: true, value } : { resource: item.resource, id, found: false, value: null, error: out.error }
@@ -22667,7 +23190,7 @@ async function uiLink(client, input) {
22667
23190
  var indexPromise = null;
22668
23191
  function operationIndex() {
22669
23192
  if (indexPromise === null) {
22670
- indexPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
23193
+ indexPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
22671
23194
  }
22672
23195
  return indexPromise;
22673
23196
  }
@@ -23026,7 +23549,10 @@ async function revenueRollup(client, opts) {
23026
23549
  const groupDims = v.groupBy.map((d) => DIMENSIONS[d]);
23027
23550
  const paths = [.../* @__PURE__ */ new Set([CONTRACTS_PATH, ...groupDims.flatMap((d) => d.picklist ? [d.picklist] : [])])];
23028
23551
  const labels = {};
23029
- for (const p of paths) labels[p] = await readPicklists(http, p, OP4);
23552
+ const labelValues = await mapReadTasks(http, paths, (path) => readPicklists(http, path, OP4));
23553
+ paths.forEach((path, index) => {
23554
+ labels[path] = labelValues[index];
23555
+ });
23030
23556
  const contractLabels = labels[CONTRACTS_PATH];
23031
23557
  const typeValues = contractLabels.get("contractType") ?? /* @__PURE__ */ new Map();
23032
23558
  const inTypes = v.contractTypes ? resolveSelector(OP4, "contractTypes", v.contractTypes, typeValues) : new Map([...typeValues].filter(([, l]) => DEFAULT_CONTRACT_TYPE_RE.test(l)));
@@ -23055,10 +23581,12 @@ async function revenueRollup(client, opts) {
23055
23581
  const invoiceFilter = (voided2) => [...windowOn("invoiceDateTime"), { field: "isVoided", op: "eq", value: voided2 }];
23056
23582
  const withVoided = v.scopeKind !== "contractIDs";
23057
23583
  const voidedFilter = [...invoiceFilter(true), ...scopeIds !== void 0 && withVoided ? [{ field: "companyID", op: "in", value: scopeIds }] : []];
23058
- const nInvoices = await invoices.count({ filter: invoiceFilter(false) });
23059
- const nLines = await billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] });
23060
23584
  const uninvoicedFilter = [{ field: "invoiceID", op: "notExist" }, ...windowOn("itemDate"), ...scopeCond];
23061
- const nUninvoiced = v.nonChargeable ? await billingItems.count({ filter: uninvoicedFilter }) : 0;
23585
+ const [nInvoices, nLines, nUninvoiced] = await readTasks(http, [
23586
+ () => invoices.count({ filter: invoiceFilter(false) }),
23587
+ () => billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] }),
23588
+ () => v.nonChargeable ? billingItems.count({ filter: uninvoicedFilter }) : Promise.resolve(0)
23589
+ ]);
23062
23590
  if (typeof nInvoices !== "number" || typeof nLines !== "number" || typeof nUninvoiced !== "number") throw blindCountError(OP4, "the roll-up", BLIND_ACTION);
23063
23591
  const joinsNeeded = Object.keys(JOINS).filter((j) => j === "contracts" || groupDims.some((d) => d.joins?.[j]));
23064
23592
  const chunks4 = pages(nInvoices);
@@ -23103,14 +23631,17 @@ async function revenueRollup(client, opts) {
23103
23631
  if (v.nonChargeable && uninvoiced.length !== nUninvoiced) throw countMismatchError(OP4, "uninvoiced line", uninvoiced.length, nUninvoiced);
23104
23632
  const all = uninvoiced.length > 0 ? [...lines, ...uninvoiced] : lines;
23105
23633
  const joined = Object.fromEntries(Object.keys(JOINS).map((j) => [j, /* @__PURE__ */ new Map()]));
23106
- for (const j of joinsNeeded) {
23634
+ const fetchJoin = async (j) => {
23107
23635
  const spec = JOINS[j];
23108
23636
  const res = spec.make(http);
23109
23637
  const fields = [.../* @__PURE__ */ new Set([...spec.fields, ...groupDims.flatMap((d) => d.joins?.[j] ?? [])])];
23110
23638
  const want = [...new Set(spec.ids(all, joined))].filter((id) => id > 0).sort((a, b) => a - b);
23111
23639
  const rows = await client.batch((c) => collectRows(res, [{ field: "id", op: "in", value: c }], fields, PAGE), idChunks(want, PAGE), { concurrency: CONCURRENCY });
23112
23640
  for (const r of rows.flat()) joined[j].set(num(r["id"]), r);
23113
- }
23641
+ };
23642
+ const levels = ["organizationalLevel1s", "organizationalLevel2s"];
23643
+ await mapReadTasks(http, joinsNeeded.filter((j) => !levels.includes(j)), fetchJoin);
23644
+ await mapReadTasks(http, joinsNeeded.filter((j) => levels.includes(j)), fetchJoin);
23114
23645
  return fold(v, { invoiceById, voided, lines, uninvoiced, joined, labels, inTypes, inCategories, scopeIds, calls: budget.spent(), estimate });
23115
23646
  }
23116
23647
  function refusal(v, estimate, fixed, scopeIds, joinCount) {
@@ -23492,7 +24023,7 @@ function capJoinSet2(ids2, cap) {
23492
24023
  }
23493
24024
  async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity) {
23494
24025
  const unique = [...new Set(ids2)].sort((a, b) => a - b);
23495
- const byKey = /* @__PURE__ */ new Map();
24026
+ const byKey2 = /* @__PURE__ */ new Map();
23496
24027
  const misses = [];
23497
24028
  const notes = [];
23498
24029
  const found = await fetchIdChunks(http, entityPath, unique, fields, operation, {
@@ -23502,17 +24033,17 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23502
24033
  const code = err instanceof AutotaskError ? err.code : "SERVER_ERROR";
23503
24034
  for (const k of chunk) {
23504
24035
  const id = Number(k);
23505
- if (!byKey.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
24036
+ if (!byKey2.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
23506
24037
  }
23507
24038
  return true;
23508
24039
  }
23509
24040
  });
23510
- for (const [k, row] of found) byKey.set(Number(k), row);
23511
- const queryMissed = unique.filter((k) => !byKey.has(k) && !misses.some((m) => m.id === k));
24041
+ for (const [k, row] of found) byKey2.set(Number(k), row);
24042
+ const queryMissed = unique.filter((k) => !byKey2.has(k) && !misses.some((m) => m.id === k));
23512
24043
  for (const k of queryMissed) {
23513
24044
  try {
23514
24045
  const res = await http.request({ method: "GET", path: `${entityPath}/${k}`, operation });
23515
- byKey.set(k, unwrapItem(res, k, operation, entity));
24046
+ byKey2.set(k, unwrapItem(res, k, operation, entity));
23516
24047
  } catch (err) {
23517
24048
  if (err instanceof NotFoundError) {
23518
24049
  misses.push({ id: k, code: "NOT_FOUND", message: err.message });
@@ -23523,14 +24054,14 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23523
24054
  }
23524
24055
  }
23525
24056
  }
23526
- const items = unique.map((k) => byKey.get(k)).filter((r) => r !== void 0);
24057
+ const items = unique.map((k) => byKey2.get(k)).filter((r) => r !== void 0);
23527
24058
  const gotByQuery = unique.length - queryMissed.length;
23528
- if (queryMissed.length > 0 && gotByQuery === 0 && byKey.size > 0) {
24059
+ if (queryMissed.length > 0 && gotByQuery === 0 && byKey2.size > 0) {
23529
24060
  notes.push(
23530
- `the chunk \`id in\` query returned 0 rows for ${byKey.size} id(s) \u2014 the per-id get fallback resolved them (the list-scoping quirk: get-by-id is the authority)`
24061
+ `the chunk \`id in\` query returned 0 rows for ${byKey2.size} id(s) \u2014 the per-id get fallback resolved them (the list-scoping quirk: get-by-id is the authority)`
23531
24062
  );
23532
24063
  }
23533
- const foundIds = new Set(byKey.keys());
24064
+ const foundIds = new Set(byKey2.keys());
23534
24065
  if (misses.length > 0) {
23535
24066
  const byCode = /* @__PURE__ */ new Map();
23536
24067
  for (const m of misses) byCode.set(m.code, (byCode.get(m.code) ?? 0) + 1);
@@ -23622,6 +24153,17 @@ function makeFetchCtx(rawHttp, v, contractId, budget, sharedExpenses) {
23622
24153
  };
23623
24154
  return { v, OP: OP14, id, idNum, rawHttp, http, wires, windowOn, readPart, windowedPart, truncatedMonths, ...sharedExpenses ? { sharedExpenses } : {} };
23624
24155
  }
24156
+ function forkFetchCtx(ctx) {
24157
+ return makeFetchCtx(ctx.rawHttp, ctx.v, ctx.id, ctx.wires.budget, ctx.sharedExpenses);
24158
+ }
24159
+ function mergeFetchContexts(ctx, branches) {
24160
+ for (const branch of branches) {
24161
+ ctx.wires.issued += branch.wires.issued;
24162
+ ctx.wires.requests += branch.wires.requests;
24163
+ if (branch.wires.note) appendWiresNote(ctx.wires, branch.wires.note);
24164
+ Object.assign(ctx.truncatedMonths, branch.truncatedMonths);
24165
+ }
24166
+ }
23625
24167
 
23626
24168
  // src/resources/special/contracts/profitability.util.ts
23627
24169
  function dateToDay(v) {
@@ -23770,11 +24312,7 @@ async function fetchCustomer(ctx, companyID) {
23770
24312
  let customerAbsent;
23771
24313
  if (companyID > 0) {
23772
24314
  try {
23773
- const res = await ctx.http.request({
23774
- method: "GET",
23775
- path: `/V1.0/Companies/${companyID}`,
23776
- operation: ctx.OP
23777
- });
24315
+ const res = await cachedRecordGet(ctx.http, `/V1.0/Companies/${companyID}`, ctx.OP);
23778
24316
  const item = unwrapItem(res, companyID, ctx.OP, "company");
23779
24317
  customer = item ?? null;
23780
24318
  customerStatus = "ok";
@@ -23804,16 +24342,17 @@ async function resolveContractType(ctx, contractType) {
23804
24342
  const isTimeAndMaterials = contractTypeKnown && TIME_AND_MATERIALS_LABEL_RE.test(contractTypeLabel);
23805
24343
  return { contractTypeLabel, contractTypeKnown, isBlockHours, isTimeAndMaterials };
23806
24344
  }
23807
- async function fetchRoot(ctx, resource) {
23808
- const contractCached = ctx.rawHttp.readCache?.get(`/V1.0/Contracts/${ctx.id}`) !== void 0;
23809
- const contract = await resource.get(ctx.id);
24345
+ async function fetchRoot(ctx) {
24346
+ const body = await cachedRecordGet(ctx.http, `/V1.0/Contracts/${ctx.id}`, "contracts.get");
24347
+ const contract = unwrapItem(body, ctx.id, "contracts.get", "contract");
23810
24348
  ctx.wires.issued += 1;
23811
- if (!contractCached) ctx.wires.requests += 1;
23812
24349
  const contractRow = contract;
23813
24350
  const companyID = num(contractRow["companyID"]);
23814
24351
  const contractType = num(contractRow["contractType"]);
23815
- const customerStage = await fetchCustomer(ctx, companyID);
23816
- const typeStage = await resolveContractType(ctx, contractType);
24352
+ const [customerStage, typeStage] = await readTasks(ctx.http, [
24353
+ () => fetchCustomer(ctx, companyID),
24354
+ () => resolveContractType(ctx, contractType)
24355
+ ]);
23817
24356
  return { contract, contractRow, contractType, ...customerStage, ...typeStage };
23818
24357
  }
23819
24358
  async function fetchCharges(ctx) {
@@ -23824,27 +24363,29 @@ async function fetchCharges(ctx) {
23824
24363
  const raw = await ctx.readPart("/V1.0/ContractCharges/query", chargesCond, ["id", "chargeType", "billableAmount", "extendedCost", "unitCost", "unitPrice", "unitQuantity", "datePurchased", "isBilled", "status", "contractServiceID"]);
23825
24364
  return { charges: raw.items, chargesPart: stampPart("contract_charges", raw, chargesCond) };
23826
24365
  }
23827
- async function fetchBlocks(ctx, root) {
23828
- if (!root.isBlockHours) {
24366
+ async function fetchBlocks(ctx, root2) {
24367
+ if (!root2.isBlockHours) {
23829
24368
  return skipPart(
23830
- root.contractTypeKnown ? `skipped: not a Block Hours contract (contractType ${root.contractType} "${root.contractTypeLabel}") \u2014 included hours apply to hour blocks only (zero wire)` : `skipped: the contract type is unknown (contractType ${root.contractType || "absent"}; label unresolved) \u2014 included hours are not evaluable (zero wire)`
24369
+ root2.contractTypeKnown ? `skipped: not a Block Hours contract (contractType ${root2.contractType} "${root2.contractTypeLabel}") \u2014 included hours apply to hour blocks only (zero wire)` : `skipped: the contract type is unknown (contractType ${root2.contractType || "absent"}; label unresolved) \u2014 included hours are not evaluable (zero wire)`
23831
24370
  );
23832
24371
  }
23833
24372
  const blocksCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23834
24373
  const raw = await ctx.readPart("/V1.0/ContractBlocks/query", blocksCond, ["id", "datePurchased", "startDate", "endDate", "hours", "hoursApproved", "status", "isPaid"]);
23835
24374
  return stampPart("contract_blocks", raw, blocksCond);
23836
24375
  }
23837
- async function fetchContractState(ctx, root) {
24376
+ async function fetchContractState(ctx, root2) {
23838
24377
  const servicesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23839
- const servicesRaw = await ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]);
23840
24378
  const unitsCond = [{ field: "contractID", op: "eq", value: ctx.id }, ...ctx.windowOn("startDate")];
23841
- const units = await ctx.windowedPart("contractServiceUnits", "contract_service_units", "/V1.0/ContractServiceUnits/query", unitsCond, ["id", "contractServiceID", "serviceID", "units", "price", "cost", "internalCurrencyPrice", "startDate", "endDate", "approveAndPostDate"], "startDate");
23842
- const { chargesPart, charges } = await fetchCharges(ctx);
23843
24379
  const roleCostsCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23844
- const roleCostsRaw = await ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]);
23845
24380
  const ratesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23846
- const ratesRaw = await ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]);
23847
- const blocksPart = await fetchBlocks(ctx, root);
24381
+ const [servicesRaw, units, { chargesPart, charges }, roleCostsRaw, ratesRaw, blocksPart] = await readTasks(ctx.http, [
24382
+ () => ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]),
24383
+ () => ctx.windowedPart("contractServiceUnits", "contract_service_units", "/V1.0/ContractServiceUnits/query", unitsCond, ["id", "contractServiceID", "serviceID", "units", "price", "cost", "internalCurrencyPrice", "startDate", "endDate", "approveAndPostDate"], "startDate"),
24384
+ () => fetchCharges(ctx),
24385
+ () => ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]),
24386
+ () => ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]),
24387
+ () => fetchBlocks(ctx, root2)
24388
+ ]);
23848
24389
  return { servicesRaw, servicesCond, unitRows: units.rows, unitsPartRaw: units.part, chargesPart, charges, roleCostsRaw, roleCostsCond, ratesRaw, ratesCond, blocksPart };
23849
24390
  }
23850
24391
  async function fetchBillingItems(ctx) {
@@ -24207,25 +24748,46 @@ async function fetchSubscriptionsJoin(ctx) {
24207
24748
  }
24208
24749
 
24209
24750
  // src/resources/special/contracts/profitability.data.ts
24210
- async function gather(ctx, resource) {
24211
- const root = await fetchRoot(ctx, resource);
24212
- const state = await fetchContractState(ctx, root);
24213
- const billing = await fetchBilling(ctx);
24214
- const time = await fetchTime(ctx);
24215
- const activity = await fetchTicketActivity(ctx, time.entries);
24216
- const open = await fetchOpenTickets(ctx);
24217
- const res = await fetchResources(ctx, time.entries);
24218
- const join = await fetchTicketJoinParts(ctx, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
24219
- const subs = await fetchSubscriptionsJoin(ctx);
24220
- return { root, state, billing, time, activity, open, res, join, subs };
24751
+ async function gather(ctx) {
24752
+ const root2 = await fetchRoot(ctx);
24753
+ const stages = Object.fromEntries(
24754
+ ["state", "billing", "time", "activity", "open", "res", "join", "subs"].map((name) => [name, forkFetchCtx(ctx)])
24755
+ );
24756
+ let timeRead;
24757
+ const timeTask = () => timeRead ??= fetchTime(stages.time);
24758
+ let activityRead;
24759
+ const activityTask = () => activityRead ??= timeTask().then((time) => fetchTicketActivity(stages.activity, time.entries));
24760
+ let openRead;
24761
+ const openTask = () => openRead ??= fetchOpenTickets(stages.open);
24762
+ const tasks = {
24763
+ state: () => fetchContractState(stages.state, root2),
24764
+ billing: () => fetchBilling(stages.billing),
24765
+ time: timeTask,
24766
+ activity: activityTask,
24767
+ open: openTask,
24768
+ res: async () => fetchResources(stages.res, (await timeTask()).entries),
24769
+ join: async () => {
24770
+ const activity = await activityTask();
24771
+ const open = await openTask();
24772
+ const time = await timeTask();
24773
+ Object.assign(stages.join.truncatedMonths, stages.time.truncatedMonths);
24774
+ return fetchTicketJoinParts(stages.join, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
24775
+ },
24776
+ subs: () => fetchSubscriptionsJoin(stages.subs)
24777
+ };
24778
+ const order = ctx.http.maxConcurrent === 1 ? ["state", "billing", "time", "activity", "open", "res", "join", "subs"] : ["state", "billing", "time", "open", "subs", "activity", "res", "join"];
24779
+ const completed = await mapReadTasks(ctx.http, order, async (name) => [name, await tasks[name]()]);
24780
+ const parts = Object.fromEntries(completed);
24781
+ mergeFetchContexts(ctx, Object.values(stages));
24782
+ return { root: root2, ...parts };
24221
24783
  }
24222
24784
  function stampListParts(v, f) {
24223
- const { state, activity, join } = f;
24785
+ const { state: state2, activity, join } = f;
24224
24786
  return {
24225
- servicesPart: stampPart("contract_services", state.servicesRaw, state.servicesCond),
24226
- unitsPart: state.unitsPartRaw,
24227
- roleCostsPart: stampPart("contract_role_costs", state.roleCostsRaw, state.roleCostsCond),
24228
- ratesPart: stampPart("contract_rates", state.ratesRaw, state.ratesCond),
24787
+ servicesPart: stampPart("contract_services", state2.servicesRaw, state2.servicesCond),
24788
+ unitsPart: state2.unitsPartRaw,
24789
+ roleCostsPart: stampPart("contract_role_costs", state2.roleCostsRaw, state2.roleCostsCond),
24790
+ ratesPart: stampPart("contract_rates", state2.ratesRaw, state2.ratesCond),
24229
24791
  ticketsActivityPart: stampPart("tickets", activity.ticketsActRaw, activity.ticketsActCond, [
24230
24792
  ...activity.ticketsActRaw.hasMore ? [`${join.fetchedTickets.size} ticket(s) returned of possibly more \u2014 the checks cover the returned set only`] : [],
24231
24793
  ...activity.refTicketIds.truncated ? [`the time-referenced ticket ids are capped at ${v.maxTicketsForJoin} of ${activity.refTicketIds.total} \u2014 the rest read as ticket_not_in_fetched_set`] : []
@@ -24866,7 +25428,7 @@ async function profitability(resource, contractId, opts, sharedExpenses) {
24866
25428
  const v = validateProfitabilityOptions(contractId, opts);
24867
25429
  const ctx = makeFetchCtx(resource.http, v, contractId, PROFITABILITY_WIRE_BUDGET, sharedExpenses);
24868
25430
  const asOf = (/* @__PURE__ */ new Date()).toISOString();
24869
- const f = await gather(ctx, resource);
25431
+ const f = await gather(ctx);
24870
25432
  const fc = makeFoldCtx(ctx, f, stampListParts(v, f), Date.parse(asOf));
24871
25433
  return assemble(ctx, fc, asOf);
24872
25434
  }
@@ -24953,17 +25515,30 @@ function validate2(opts) {
24953
25515
  function latchingHttp(raw, spend) {
24954
25516
  const counted = countingHttp(raw, spend);
24955
25517
  let fatal;
25518
+ const controller = new AbortController();
25519
+ const caller = ambientCallerSignal();
25520
+ const signal = caller === void 0 ? controller.signal : AbortSignal.any([caller, controller.signal]);
24956
25521
  const http = Object.create(counted);
24957
- http.request = async (o) => {
25522
+ const latch = (err) => {
25523
+ if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") {
25524
+ fatal ??= err;
25525
+ controller.abort(fatal);
25526
+ }
25527
+ };
25528
+ observeRecordReadFailures(http, latch);
25529
+ const fail = (err) => {
25530
+ latch(err);
25531
+ throw err;
25532
+ };
25533
+ http.request = (o) => {
24958
25534
  if (fatal) throw fatal;
24959
25535
  try {
24960
- return await counted.request(o);
25536
+ return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail);
24961
25537
  } catch (err) {
24962
- if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") fatal ??= err;
24963
- throw err;
25538
+ return fail(err);
24964
25539
  }
24965
25540
  };
24966
- return { http, fatal: () => fatal };
25541
+ return { http, fatal: () => fatal, signal };
24967
25542
  }
24968
25543
  async function portfolioMargin(client, opts) {
24969
25544
  const v = validate2(opts);
@@ -24974,7 +25549,7 @@ async function portfolioMargin(client, opts) {
24974
25549
  { phase: estimate === 0 ? "estimate" : "walk", budget: v.budget, vendorCalls: spent, ...estimate > 0 ? { estimate } : {} },
24975
25550
  `Pass maxVendorCalls > ${v.budget} (cap ${BUDGET_CAP2}) or fewer contracts.`
24976
25551
  ));
24977
- const { http, fatal } = latchingHttp(client.http, budget.spend);
25552
+ const { http, fatal, signal } = latchingHttp(client.http, budget.spend);
24978
25553
  const contracts = new ContractsResource(http, PAGE2);
24979
25554
  let typeMap;
24980
25555
  if (v.contractTypes) {
@@ -25021,7 +25596,7 @@ async function portfolioMargin(client, opts) {
25021
25596
  let results;
25022
25597
  try {
25023
25598
  const shared = countFault ?? (expenseCount === 0 ? { rows: [], contractOf: /* @__PURE__ */ new Map(), misses: 0 } : await readTicketExpenses(http, expenseItems, expenseFilter, expenseCount));
25024
- results = await client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 });
25599
+ results = await client.withSignal(signal, () => client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 }));
25025
25600
  } catch (err) {
25026
25601
  throw fatal() ?? err;
25027
25602
  }
@@ -25264,8 +25839,10 @@ async function recurringRevenue(client, opts) {
25264
25839
  ];
25265
25840
  const subsRes = res("subscriptions");
25266
25841
  const subFilter = [{ field: "effectiveDate", op: "lt", value: next }, { field: "expirationDate", op: "gte", value: v.asOf }];
25267
- const nContracts = await countOf(contractsRes, "contract", contractFilter);
25268
- const nSubs = await countOf(subsRes, "subscription", subFilter);
25842
+ const [nContracts, nSubs] = await readTasks(http, [
25843
+ () => countOf(contractsRes, "contract", contractFilter),
25844
+ () => countOf(subsRes, "subscription", subFilter)
25845
+ ]);
25269
25846
  const chunks4 = Math.ceil(nContracts / CHUNK);
25270
25847
  const subCalls = Math.ceil(nSubs / PAGE3) + (nSubs > 0 ? 1 : 0) + Math.ceil(nSubs / CHUNK) + (v.scopeIds ? 1 : Math.ceil((nContracts + nSubs) / CHUNK));
25271
25848
  const refuse3 = (calls, sets2) => {
@@ -25304,26 +25881,35 @@ async function recurringRevenue(client, opts) {
25304
25881
  nCharges: 0
25305
25882
  };
25306
25883
  });
25307
- for (const x of sets) {
25308
- x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
25309
- x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
25310
- }
25884
+ await mapReadTasks(http, sets.flatMap((x) => [
25885
+ async () => {
25886
+ x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
25887
+ },
25888
+ async () => {
25889
+ x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
25890
+ }
25891
+ ]), (task) => task());
25311
25892
  const nUnits = sets.reduce((a, x) => a + x.nUnits, 0);
25312
25893
  const nCharges = sets.reduce((a, x) => a + x.nCharges, 0);
25313
25894
  estimate = budget.spent() + sets.reduce((a, x) => a + Math.ceil(x.nUnits / PAGE3) + Math.ceil(x.nCharges / PAGE3), 0) + subCalls;
25314
25895
  if (estimate > v.budget) {
25315
25896
  throw refuse3(estimate, { contracts: nContracts, serviceUnits: nUnits, charges: nCharges, subscriptions: nSubs });
25316
25897
  }
25317
- const units = [];
25318
- const charges = [];
25319
- for (const x of sets) {
25320
- units.push(...await gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits));
25321
- charges.push(...await gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges));
25322
- }
25323
- const subs = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
25324
- const labels = subs.length > 0 ? await readPicklists(http, "/V1.0/Subscriptions", OP6) : /* @__PURE__ */ new Map();
25325
- const ciIds = [...new Set(subs.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
25326
- const cis = ciIds.length > 0 ? await fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : /* @__PURE__ */ new Map();
25898
+ const [unitSets, chargeSets, { subs, labels, cis }] = await readTasks(http, [
25899
+ () => mapReadTasks(http, sets, (x) => gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits)),
25900
+ () => mapReadTasks(http, sets, (x) => gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges)),
25901
+ async () => {
25902
+ const subs2 = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
25903
+ const ciIds = [...new Set(subs2.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
25904
+ const [labels2, cis2] = await readTasks(http, [
25905
+ () => subs2.length > 0 ? readPicklists(http, "/V1.0/Subscriptions", OP6) : Promise.resolve(/* @__PURE__ */ new Map()),
25906
+ () => ciIds.length > 0 ? fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : Promise.resolve(/* @__PURE__ */ new Map())
25907
+ ]);
25908
+ return { subs: subs2, labels: labels2, cis: cis2 };
25909
+ }
25910
+ ]);
25911
+ const units = unitSets.flat();
25912
+ const charges = chargeSets.flat();
25327
25913
  const contractOf = new Map(contracts.map((c) => [num(c["id"]), c]));
25328
25914
  const latest = /* @__PURE__ */ new Map();
25329
25915
  for (const u of units) {
@@ -26036,7 +26622,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26036
26622
  suggestedAction: "Narrow the dateWorked window, or page it with cursor (rows mode reports unconfirmed entries via truncated)."
26037
26623
  });
26038
26624
  }
26039
- for (const [id, state] of joined.states) states.set(id, state);
26625
+ for (const [id, state2] of joined.states) states.set(id, state2);
26040
26626
  cursor = page.items.length === 0 ? null : page.pageDetails.nextPageUrl ?? null;
26041
26627
  } while (cursor !== null);
26042
26628
  spend();
@@ -26054,7 +26640,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26054
26640
  });
26055
26641
  }
26056
26642
  let postedCount = 0;
26057
- for (const state of states.values()) if (state === "posted") postedCount += 1;
26643
+ for (const state2 of states.values()) if (state2 === "posted") postedCount += 1;
26058
26644
  return { window, total: states.size, postedCount, unpostedCount: states.size - postedCount, vendorCalls: callBudget.spent(), estimate, budget };
26059
26645
  }
26060
26646
  async function dateWorkedWindow(resource, from, to, opts) {
@@ -26075,8 +26661,8 @@ async function dateWorkedWindow(resource, from, to, opts) {
26075
26661
  const { states, incomplete } = await postedStateOf(http, items, OP14);
26076
26662
  let postedCount = 0;
26077
26663
  let unpostedCount = 0;
26078
- for (const state of states.values()) {
26079
- if (state === "posted") postedCount += 1;
26664
+ for (const state2 of states.values()) {
26665
+ if (state2 === "posted") postedCount += 1;
26080
26666
  else unpostedCount += 1;
26081
26667
  }
26082
26668
  return {
@@ -26360,12 +26946,14 @@ async function wipHours(client, opts) {
26360
26946
  } else {
26361
26947
  const contractIds = positiveIds2(wipIn.map((e) => e["contractID"]));
26362
26948
  gate(chunks2(contractIds.length) + (contractIds.length > 0 ? 1 : 0), "before label reads", { contracts: contractIds.length });
26363
- const contracts = await readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]);
26949
+ const [contracts, types] = await readTasks(http, [
26950
+ () => readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]),
26951
+ async () => contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0
26952
+ ]);
26364
26953
  const typeOf = (id) => contracts.get(String(id))?.["contractType"];
26365
26954
  const bad = contractIds.filter((id) => typeof typeOf(id) !== "number");
26366
26955
  if (bad.length > 0) throw unresolved("contracts", bad);
26367
26956
  keyOfEntry = (e) => num(e["contractID"]) > 0 ? typeOf(num(e["contractID"])) : null;
26368
- const types = contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0;
26369
26957
  for (const [id, label] of types ?? []) labels.set(id, { label });
26370
26958
  }
26371
26959
  const approvalData = entries.some((e) => isApproved(e));
@@ -26557,8 +27145,10 @@ async function nonChargeableWork(client, opts) {
26557
27145
  const contractIds = distinctIds(ncLines.map((x) => x.line["contractID"]), 1);
26558
27146
  const typed = v.groupBy === "contractType";
26559
27147
  gate(chunks3(contractIds.length) + (typed && contractIds.length > 0 ? 1 : 0) + (v.includeUnpostedTime ? 1 : 0), "before label reads", { contracts: contractIds.length });
26560
- const contracts = await readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]);
26561
- const types = typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0;
27148
+ const [contracts, types] = await readTasks(http, [
27149
+ () => readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]),
27150
+ async () => typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0
27151
+ ]);
26562
27152
  keyOfLine = (line) => {
26563
27153
  if (num(line["contractID"]) === 0) return null;
26564
27154
  const c = contracts.get(String(line["contractID"]));
@@ -27040,6 +27630,10 @@ async function openTicketsOfPart(client, field, id, limit) {
27040
27630
  const filter = [{ field, op: "eq", value: id }, ...closed.map((v) => ({ field: "status", op: "noteq", value: v }))];
27041
27631
  return { ...await compositePart(client, "tickets.query", [{ filter, limit }]), closedStatus };
27042
27632
  }
27633
+ async function joinedCompositePart(client, source, idField, targetOp, targetField, limit, absent) {
27634
+ const ids2 = numericIds(source.value?.items ?? [], idField).slice(0, IN_FILTER_CAP);
27635
+ return ids2.length === 0 ? { value: null, absent } : await compositePart(client, targetOp, [{ filter: [{ field: targetField, op: "in", value: ids2 }], limit }]);
27636
+ }
27043
27637
 
27044
27638
  // src/resources/special/contracts/fullProfile.ts
27045
27639
  var OP12 = "contracts.fullProfile";
@@ -27050,21 +27644,23 @@ async function fullProfile2(resource, id, opts = {}) {
27050
27644
  const serviceLimit = compositePartLimit(opts.serviceLimit, "serviceLimit", OP12);
27051
27645
  const billingRuleLimit = compositePartLimit(opts.billingRuleLimit, "billingRuleLimit", OP12);
27052
27646
  const contractId = parseIdentifier(id, "id");
27053
- const root = await invokeRead(client, "contracts.get", [contractId]);
27054
- const services = await compositePart(client, "contract_services.query", [
27055
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27056
- ]);
27057
- const billingRules = await compositePart(client, "contract_billing_rules.query", [
27058
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27059
- ]);
27060
- const charges = await compositePart(client, "contract_charges.query", [
27061
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27062
- ]);
27063
- const units = await compositePart(client, "contract_service_units.query", [
27064
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
27647
+ const root2 = await invokeRead(client, "contracts.get", [contractId]);
27648
+ const [services, billingRules, charges, units] = await readTasks(resource.http, [
27649
+ () => compositePart(client, "contract_services.query", [
27650
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27651
+ ]),
27652
+ () => compositePart(client, "contract_billing_rules.query", [
27653
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27654
+ ]),
27655
+ () => compositePart(client, "contract_charges.query", [
27656
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27657
+ ]),
27658
+ () => compositePart(client, "contract_service_units.query", [
27659
+ { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
27660
+ ])
27065
27661
  ]);
27066
27662
  return {
27067
- root,
27663
+ root: root2,
27068
27664
  parts: {
27069
27665
  services,
27070
27666
  billing_rules: billingRules,
@@ -27171,7 +27767,6 @@ exports.GenericResource = GenericResource;
27171
27767
  exports.HostPolicyDeniedError = HostPolicyDeniedError;
27172
27768
  exports.HttpClient = HttpClient;
27173
27769
  exports.INVOKE_OPTION_KEYS = INVOKE_OPTION_KEYS;
27174
- exports.IN_FILTER_CAP = IN_FILTER_CAP;
27175
27770
  exports.InvoicesResource = InvoicesResource;
27176
27771
  exports.MAX_FIELD_CATALOG_WIRE = MAX_FIELD_CATALOG_WIRE;
27177
27772
  exports.MIN_FIELD_CATALOG_MAX_BYTES = MIN_FIELD_CATALOG_MAX_BYTES;
@@ -27209,6 +27804,7 @@ exports.buildDryRunResult = buildDryRunResult;
27209
27804
  exports.buildQueryRequest = buildQueryRequest;
27210
27805
  exports.buildReadCache = buildReadCache;
27211
27806
  exports.buildUiLink = buildUiLink;
27807
+ exports.cachedRecordGet = cachedRecordGet;
27212
27808
  exports.clientOf = clientOf;
27213
27809
  exports.compositePart = compositePart;
27214
27810
  exports.compositePartLimit = compositePartLimit;
@@ -27232,19 +27828,20 @@ exports.invokeWrite = invokeWrite;
27232
27828
  exports.isAutotaskError = isAutotaskError;
27233
27829
  exports.isClosedStatus = isClosedStatus;
27234
27830
  exports.isDeterministicVendor500 = isDeterministicVendor500;
27831
+ exports.joinedCompositePart = joinedCompositePart;
27235
27832
  exports.mergeDetails = mergeDetails;
27236
27833
  exports.mergePartialBody = mergePartialBody;
27237
27834
  exports.needsConfirmation = needsConfirmation;
27238
27835
  exports.nextActionFor = nextActionFor;
27239
27836
  exports.nonChargeableWork = nonChargeableWork;
27240
27837
  exports.notPersistedFields = notPersistedFields;
27241
- exports.numericIds = numericIds;
27242
27838
  exports.openStatusFilter = openStatusFilter;
27243
27839
  exports.openTicketsOfPart = openTicketsOfPart;
27244
27840
  exports.parseIdentifier = parseIdentifier;
27245
27841
  exports.parseVendorErrors = parseVendorErrors;
27246
27842
  exports.portfolioMargin = portfolioMargin;
27247
27843
  exports.queryRows = queryRows;
27844
+ exports.readTasks = readTasks;
27248
27845
  exports.recurringRevenue = recurringRevenue;
27249
27846
  exports.refuse = refuse2;
27250
27847
  exports.relationshipMap = relationshipMap;
@@ -27256,6 +27853,7 @@ exports.resolveLineOfBusinessChain = resolveLineOfBusinessChain;
27256
27853
  exports.resolveStaff = resolveStaff;
27257
27854
  exports.resolveTicketStatusSemantics = resolveTicketStatusSemantics;
27258
27855
  exports.revenueRollup = revenueRollup;
27856
+ exports.runBounded = runBounded;
27259
27857
  exports.runMove = runMove;
27260
27858
  exports.runWithSignal = runWithSignal;
27261
27859
  exports.sanitiseResult = sanitiseResult;