node-autotask 0.68.1 → 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 +12 -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-2D2KJOX2.cjs → chunk-24GRFW55.cjs} +236 -222
  9. package/dist/{chunk-LOLWHPTJ.js → chunk-2BB7OASJ.js} +3 -30
  10. package/dist/{chunk-S6HEIGGM.js → chunk-AH6WAGPS.js} +80 -66
  11. package/dist/{chunk-KRQONGLD.cjs → chunk-DPRY3CUJ.cjs} +30 -57
  12. package/dist/{chunk-XKIRTR37.cjs → chunk-JLBSUZ5B.cjs} +919 -344
  13. package/dist/{chunk-SGH7F2CH.cjs → chunk-KAZE4WC7.cjs} +3 -3
  14. package/dist/{chunk-YYHCZRUH.js → chunk-QDBJCGQD.js} +912 -339
  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 +39 -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;
14211
- try {
14212
- text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
14213
- } catch {
14214
- return void 0;
14215
- }
14216
- let body;
14480
+ if (signal.aborted) return void 0;
14481
+ const admission = admitHourlyAttempt(discoveryUrl, void 0, Date.now());
14482
+ if (!admission.admitted) return void 0;
14217
14483
  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
  }
@@ -15303,7 +15638,7 @@ async function capabilitySets() {
15303
15638
  const fieldOps = /* @__PURE__ */ new Map();
15304
15639
  const udfCapable = /* @__PURE__ */ new Set();
15305
15640
  const resources = /* @__PURE__ */ new Set();
15306
- for (const rec of await chunkSGH7F2CH_cjs.loadCapabilityRecords()) {
15641
+ for (const rec of await chunkKAZE4WC7_cjs.loadCapabilityRecords()) {
15307
15642
  if (rec.resource === "operations") continue;
15308
15643
  resources.add(rec.resource);
15309
15644
  if (rec.operation === "getFieldInfo") fieldOps.set(rec.resource, rec);
@@ -15314,7 +15649,7 @@ async function capabilitySets() {
15314
15649
  var derivedIndexPromise = null;
15315
15650
  function derivedIndexLoad() {
15316
15651
  if (derivedIndexPromise === null) {
15317
- derivedIndexPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => {
15652
+ derivedIndexPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => {
15318
15653
  const index = /* @__PURE__ */ new Map();
15319
15654
  for (const rec of records) {
15320
15655
  const declared = rec.metadata?.derivedFields;
@@ -15795,6 +16130,64 @@ function entityNameFromPath(resourcePath) {
15795
16130
  return snake;
15796
16131
  }
15797
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
+
15798
16191
  // src/operations/expandResourceNames.ts
15799
16192
  var EXPAND_RESOURCE_NAMES_MAX_IDS = 500;
15800
16193
  function composeName(record) {
@@ -15805,6 +16198,27 @@ function composeName(record) {
15805
16198
  }
15806
16199
  return parts.length > 0 ? parts.join(" ") : null;
15807
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
+ }
15808
16222
  async function expandResourceNames(client, ids2, opts = {}) {
15809
16223
  if (opts.maxIds !== void 0 && (!Number.isInteger(opts.maxIds) || opts.maxIds < 1)) {
15810
16224
  throw new AutotaskConfigError(`expandResourceNames: maxIds must be an integer >= 1 (got ${String(opts.maxIds)})`);
@@ -15857,13 +16271,21 @@ async function expandResourceNames(client, ids2, opts = {}) {
15857
16271
  const holder = client.resources;
15858
16272
  const cache = client.http.readCache;
15859
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
+ }
15860
16281
  const byId2 = /* @__PURE__ */ new Map();
15861
- for (const id of unique) {
16282
+ await mapReadTasks(client.http, unique, async (id) => {
15862
16283
  const k = String(id);
15863
16284
  const absentKey = contextAbsentKey(`/V1.0/Resources/${k}`);
15864
- if (cache !== void 0 && !fresh && cache.get(absentKey) !== void 0) {
15865
- byId2.set(k, { name: null, blind: true });
15866
- continue;
16285
+ const snapshot = warm.get(k);
16286
+ if (snapshot !== void 0) {
16287
+ byId2.set(k, snapshot);
16288
+ return;
15867
16289
  }
15868
16290
  const epoch = cache?.epoch ?? 0;
15869
16291
  try {
@@ -15874,17 +16296,11 @@ async function expandResourceNames(client, ids2, opts = {}) {
15874
16296
  if (err instanceof NotFoundError) {
15875
16297
  cache?.set(absentKey, CONTEXT_ABSENT_MARKER, epoch);
15876
16298
  byId2.set(k, { name: null, blind: true });
15877
- continue;
15878
- }
15879
- if (isAutotaskError(err) && err.code !== "ABORTED") {
15880
- const e = { code: err.code, message: err.message };
15881
- if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
15882
- byId2.set(k, { name: null, blind: false, error: e });
15883
- continue;
16299
+ return;
15884
16300
  }
15885
- throw err;
16301
+ byId2.set(k, resourceNameFailure(err));
15886
16302
  }
15887
- }
16303
+ });
15888
16304
  const results = [];
15889
16305
  for (const id of canonical) {
15890
16306
  const out = byId2.get(String(id));
@@ -16049,6 +16465,13 @@ var FK_TABLE_PATH = {
16049
16465
  company: "/V1.0/Companies",
16050
16466
  ticket: "/V1.0/Tickets"
16051
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
+ };
16052
16475
  var FK_NAME_FIELD = {
16053
16476
  role: "name",
16054
16477
  billingCode: "name",
@@ -16080,13 +16503,15 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16080
16503
  const readCache = http.readCache;
16081
16504
  const section = { truncated: false, rows: {}, reasons: {} };
16082
16505
  let remaining = budget;
16506
+ const tasks = [];
16083
16507
  let contractLobPointer;
16084
16508
  let contractLobUnread;
16085
16509
  const coldResource = [];
16510
+ const warmResources = /* @__PURE__ */ new Map();
16086
16511
  for (const id of plan.resourceIds) {
16087
- const path = `/V1.0/Resources/${id}`;
16088
- if (readCache !== void 0 && (readCache.peek(path).hit || readCache.peek(contextAbsentKey(path)).hit)) continue;
16089
- coldResource.push(id);
16512
+ const snapshot = resourceNameSnapshot(readCache, id);
16513
+ if (snapshot === void 0) coldResource.push(id);
16514
+ else warmResources.set(String(id), snapshot);
16090
16515
  }
16091
16516
  const withinBudget = coldResource.slice(0, remaining);
16092
16517
  const overBudgetResource = coldResource.slice(remaining);
@@ -16106,12 +16531,21 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16106
16531
  }
16107
16532
  pass = pass.slice(0, 500);
16108
16533
  }
16109
- const res = await expandResourceNames(client, pass);
16110
- for (const r of res.results) {
16111
- const row = { name: r.name, blind: r.blind };
16112
- if (r.error !== void 0) row.error = faultRow(r.error);
16113
- section.rows[`resource:${r.id}`] = row;
16114
- }
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
+ });
16115
16549
  }
16116
16550
  const holders = {
16117
16551
  role: client.roles,
@@ -16122,10 +16556,13 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16122
16556
  };
16123
16557
  for (const fk2 of plan.recordFks) {
16124
16558
  const key = `${fk2.table}:${fk2.id}`;
16125
- 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;
16126
16561
  if (cold) {
16127
16562
  if (remaining < 1) {
16128
- section.rows[key] = { name: null, blind: false };
16563
+ tasks.push(async () => () => {
16564
+ section.rows[key] = { name: null, blind: false };
16565
+ });
16129
16566
  section.truncated = true;
16130
16567
  if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16131
16568
  contractLobUnread = "capped";
@@ -16134,41 +16571,51 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16134
16571
  }
16135
16572
  remaining -= 1;
16136
16573
  }
16137
- try {
16138
- const record = await holders[fk2.table].get(fk2.id);
16139
- if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16140
- contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
16141
- }
16142
- section.rows[key] = { name: fkName(record, fk2.table), blind: false };
16143
- } catch (err) {
16144
- if (err instanceof NotFoundError) {
16145
- section.rows[key] = { name: null, blind: true };
16146
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
16147
- section.rows[key] = { name: null, blind: false, error: faultRow(err) };
16148
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
16149
- 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;
16150
16592
  }
16151
- } else {
16152
- throw err;
16153
16593
  }
16154
- }
16594
+ return () => {
16595
+ section.rows[key] = row;
16596
+ };
16597
+ });
16155
16598
  }
16156
16599
  const picklists = {};
16157
16600
  if (plan.labelFields.length > 0) {
16158
- try {
16159
- const labelResource = plan.labelResource ?? "tickets";
16160
- const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16161
- const row = catalog.rows.find((r) => r.resource === labelResource);
16162
- if (row !== void 0 && row.error === null && row.fields !== void 0) {
16163
- for (const f of plan.labelFields) {
16164
- const frow = row.fields.find((x) => x.name === f);
16165
- 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
+ }
16166
16611
  }
16612
+ } catch (err) {
16613
+ if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16167
16614
  }
16168
- } catch (err) {
16169
- if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16170
- }
16615
+ return () => void 0;
16616
+ });
16171
16617
  }
16618
+ for (const merge of await readTasks(http, tasks)) merge();
16172
16619
  let lineOfBusiness2 = null;
16173
16620
  const lobId = plan.lineOfBusinessId ?? contractLobPointer;
16174
16621
  if (lobId !== void 0) {
@@ -16243,6 +16690,61 @@ var BOUNDED_QUERY_MAX_LIMIT = 2500;
16243
16690
  var LATEST_MAX_COUNT_PROBES = 64;
16244
16691
  var MARKER_RECOVERY_LIMIT = 5;
16245
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
+
16246
16748
  // src/field-sets.ts
16247
16749
  var MODEL_FIELD_SETS = {
16248
16750
  "appointments": ["id", "createDateTime", "creatorResourceID", "description", "endDateTime", "resourceID", "startDateTime", "title", "updateDateTime"],
@@ -16655,14 +17157,14 @@ async function labelRows(client, resourceKey, rows) {
16655
17157
  return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
16656
17158
  }
16657
17159
  async function labelFetchResults(client, result) {
16658
- const byResource = /* @__PURE__ */ new Map();
17160
+ const byResource2 = /* @__PURE__ */ new Map();
16659
17161
  result.results.forEach((r, i) => {
16660
- 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]);
16661
17163
  });
16662
17164
  const results = [...result.results];
16663
17165
  const notes = [];
16664
17166
  const reasons = {};
16665
- for (const [resource, indices] of byResource) {
17167
+ for (const [resource, indices] of byResource2) {
16666
17168
  const labelled = await labelRows(client, resource, indices.map((i) => results[i].value));
16667
17169
  indices.forEach((idx, j) => {
16668
17170
  results[idx] = { ...results[idx], value: labelled.rows[j] };
@@ -16732,7 +17234,7 @@ var QueryBase = class {
16732
17234
  // Query walk (wired to the G3 walker; cursor-follow per the pinned wire)
16733
17235
  // ------------------------------------------------------------------
16734
17236
  /** One page fetch: page 1 POSTs the QueryModel body; later pages POST the same body (`buildQueryBody`) to the absolute cursor (issue #118). */
16735
- async fetchPage(params, page, pageSize, state) {
17237
+ async fetchPage(params, page, pageSize, state2) {
16736
17238
  if (params.includeFields !== void 0) {
16737
17239
  params = { ...params, includeFields: params.includeFields.map((field) => normalizeOwnField(this.config.key, field)) };
16738
17240
  }
@@ -16740,9 +17242,9 @@ var QueryBase = class {
16740
17242
  if (page === 1) {
16741
17243
  const req = buildQueryRequest(this.http.baseUrl, this.resourcePath, { ...params, maxRecords: pageSize });
16742
17244
  const body2 = await this.http.request({ ...req, operation });
16743
- return this.readPage(body2, page, pageSize, state);
17245
+ return this.readPage(body2, page, pageSize, state2);
16744
17246
  }
16745
- const cursor = state.cursor;
17247
+ const cursor = state2.cursor;
16746
17248
  if (cursor === null) {
16747
17249
  throw new AutotaskError(`No pagination cursor available for page ${page} of ${operation}`, {
16748
17250
  code: "INVALID_RESPONSE",
@@ -16758,13 +17260,13 @@ var QueryBase = class {
16758
17260
  operation,
16759
17261
  idempotent: true
16760
17262
  });
16761
- return this.readPage(res, page, pageSize, state);
17263
+ return this.readPage(res, page, pageSize, state2);
16762
17264
  }
16763
17265
  /** @internal */
16764
- readPage(body, page, pageSize, state) {
17266
+ readPage(body, page, pageSize, state2) {
16765
17267
  const { items, pageDetails } = unwrapItems(body, `${this.config.key}.query`);
16766
- state.cursor = pageDetails.nextPageUrl ?? null;
16767
- const hasMore = state.cursor !== null;
17268
+ state2.cursor = pageDetails.nextPageUrl ?? null;
17269
+ const hasMore = state2.cursor !== null;
16768
17270
  return {
16769
17271
  items,
16770
17272
  page,
@@ -16778,9 +17280,9 @@ var QueryBase = class {
16778
17280
  }
16779
17281
  /** Build the per-walk fetcher (closure keeps cursor state private to this walk). */
16780
17282
  pageFetcher(params) {
16781
- const state = { cursor: null };
17283
+ const state2 = { cursor: null };
16782
17284
  const p = params ?? {};
16783
- return (page, pageSize) => this.fetchPage(p, page, pageSize, state);
17285
+ return (page, pageSize) => this.fetchPage(p, page, pageSize, state2);
16784
17286
  }
16785
17287
  /** @internal */
16786
17288
  walkPageSize(params) {
@@ -16945,7 +17447,7 @@ var QueryBase = class {
16945
17447
  * state).
16946
17448
  * @internal */
16947
17449
  async walkBounded(p, limit, pageSizeBase, labelPages = false) {
16948
- const state = { cursor: null };
17450
+ const state2 = { cursor: null };
16949
17451
  const items = [];
16950
17452
  let pages2 = 0;
16951
17453
  let sliced = 0;
@@ -16958,7 +17460,7 @@ var QueryBase = class {
16958
17460
  guard = true;
16959
17461
  break;
16960
17462
  }
16961
- const page = await this.fetchPage(p, pages2 + 1, pageSize, state);
17463
+ const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
16962
17464
  pages2 += 1;
16963
17465
  if (labelPages && this.http.client !== void 0) {
16964
17466
  const labelled = await labelRows(this.http.client, this.config.key, page.items);
@@ -16979,7 +17481,7 @@ var QueryBase = class {
16979
17481
  note: [...nameNotes].join("; "),
16980
17482
  ...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
16981
17483
  };
16982
- 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 } };
16983
17485
  }
16984
17486
  /** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
16985
17487
  * was met with a live next cursor (or a sliced final page): rows exist
@@ -17252,17 +17754,11 @@ var MetaBase = class extends QueryBase {
17252
17754
  * and the composite ROOT read of a hot resource (issue #36 — the
17253
17755
  * ticket-composite root) must see the live record, never a snapshot.
17254
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.
17255
17759
  * @internal */
17256
17760
  async cachedGet(path, operation, fresh = false) {
17257
- const cache = this.http.readCache;
17258
- if (cache !== void 0 && !fresh) {
17259
- const hit = cache.get(path);
17260
- if (hit !== void 0) return hit;
17261
- }
17262
- const epoch = cache?.epoch;
17263
- const res = await this.http.request({ method: "GET", path, operation });
17264
- cache?.set(path, res, epoch);
17265
- return res;
17761
+ return cachedRecordGet(this.http, path, operation, fresh);
17266
17762
  }
17267
17763
  /**
17268
17764
  * Entity-metadata read through the opt-in field cache (issue #31; off by
@@ -17611,8 +18107,8 @@ var MetaBase = class extends QueryBase {
17611
18107
  );
17612
18108
  }
17613
18109
  const leaf = fields.map((field) => ({ field, op: "eq", value }));
17614
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17615
- 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);
17616
18112
  if (items.length === 1) {
17617
18113
  return { value: items[0], resolutionCost: "server-filter", scanned: 0, scanTruncated: false };
17618
18114
  }
@@ -17718,13 +18214,13 @@ var MetaBase = class extends QueryBase {
17718
18214
  async scanForExactMatch(value, fields) {
17719
18215
  const caps = this.resolutionCaps;
17720
18216
  const pageSize = Math.max(1, Math.floor(caps.maxScanRecords / caps.maxScanPages));
17721
- const state = { cursor: null };
18217
+ const state2 = { cursor: null };
17722
18218
  let scanned = 0;
17723
18219
  let pages2 = 0;
17724
18220
  let found = null;
17725
18221
  let exhausted = false;
17726
18222
  for (; ; ) {
17727
- const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state);
18223
+ const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state2);
17728
18224
  pages2 += 1;
17729
18225
  for (const item of page.items) {
17730
18226
  scanned += 1;
@@ -17779,7 +18275,7 @@ var MetaBase = class extends QueryBase {
17779
18275
  }
17780
18276
  const limit = opts.limit === void 0 ? 25 : clampPageSize(opts.limit);
17781
18277
  const leaf = fields.map((field) => ({ field, op: "contains", value: text }));
17782
- const root = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18278
+ const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
17783
18279
  for (const key of Object.keys(opts)) {
17784
18280
  if (key !== "limit" && key !== "companyID" && key !== "includeFields") {
17785
18281
  throw new AutotaskConfigError(`search: unknown opts key "${key}" \u2014 the bag is closed: limit, companyID, includeFields`);
@@ -17793,7 +18289,7 @@ var MetaBase = class extends QueryBase {
17793
18289
  }
17794
18290
  const companyID = opts.companyID === void 0 ? void 0 : Number(opts.companyID);
17795
18291
  const includeFields = opts.includeFields === void 0 ? void 0 : opts.includeFields.includes("id") ? opts.includeFields : ["id", ...opts.includeFields];
17796
- 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];
17797
18293
  const rows = await this.queryEntity(`${this.resourcePath}/query`, conditions, {
17798
18294
  maxRecords: limit,
17799
18295
  ...includeFields !== void 0 ? { includeFields } : {}
@@ -20066,20 +20562,20 @@ var GenericResource = class extends BaseResource {
20066
20562
  this.requireHelper("getContext");
20067
20563
  const cfg = this.config;
20068
20564
  const rootField = cfg.contextRootField ?? this.config.key;
20069
- const root = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20070
- const result = { [rootField]: root };
20071
- for (const [name, idField, targetPath] of cfg.contextParts ?? []) {
20072
- result[name] = await this.contextFetch(targetPath, root[idField]);
20073
- }
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];
20074
20570
  if (opts.names === true) {
20075
20571
  const builder = createNamePlan();
20076
20572
  for (const sib of cfg.nameSiblings ?? []) {
20077
- const fk2 = root[sib.field];
20573
+ const fk2 = root2[sib.field];
20078
20574
  if (sib.kind === "resource") builder.addResource(fk2);
20079
20575
  else builder.addFk(sib.kind, fk2);
20080
20576
  }
20081
20577
  const names = await resolveCompositeNames(this.http, builder.plan(), { maxNameReads: opts.maxNameReads });
20082
- const row = { ...root };
20578
+ const row = { ...root2 };
20083
20579
  for (const sib of cfg.nameSiblings ?? []) {
20084
20580
  addNameSibling(row, sib.field, (v) => sib.kind === "resource" ? names.resourceName(v) : names.recordName(sib.kind, v));
20085
20581
  }
@@ -20248,9 +20744,9 @@ async function searchFuzzy(resource, query, opts = {}) {
20248
20744
  if (!opts.includeInactive) filter.push({ field: "isActive", op: "eq", value: true });
20249
20745
  const index = companyIndex(resource.http);
20250
20746
  index?.ensure();
20251
- const state = index?.state() ?? { state: "off" };
20747
+ const state2 = index?.state() ?? { state: "off" };
20252
20748
  const revision = index?.revision();
20253
- const indexed = state.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20749
+ const indexed = state2.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
20254
20750
  const res = await resource.http.request({
20255
20751
  method: "POST",
20256
20752
  idempotent: true,
@@ -20269,7 +20765,7 @@ async function searchFuzzy(resource, query, opts = {}) {
20269
20765
  const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
20270
20766
  for (let i = 0; i < items.length; i++) items[i].record = records[i];
20271
20767
  }
20272
- 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() };
20273
20769
  }
20274
20770
 
20275
20771
  // src/operations/invoke/fieldNames.ts
@@ -20443,13 +20939,17 @@ async function readFields(http, fresh) {
20443
20939
  const hit = cache.get(key);
20444
20940
  if (hit !== void 0) return hit;
20445
20941
  }
20446
- const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
20447
- const fields = res?.fields;
20448
- if (!Array.isArray(fields)) {
20449
- throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20450
- }
20451
- if (fields.length > 0) cache?.set(key, fields);
20452
- 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;
20453
20953
  }
20454
20954
  function assumed(allowAssumed, operation) {
20455
20955
  if (!allowAssumed) {
@@ -20671,14 +21171,16 @@ async function fullProfile(resource, id, opts = {}) {
20671
21171
  const proj = validateProjection(opts.fields);
20672
21172
  const companyID = parseIdentifier(id, "id");
20673
21173
  const company = await resource.get(companyID);
20674
- const locations = await scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations);
20675
- const contacts = await scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts);
20676
- const notes = await scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes);
20677
- const projects = await scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects);
20678
- const openTickets = await readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
20679
- ...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
20680
- ...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
20681
- });
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
+ ]);
20682
21184
  const result = {
20683
21185
  company,
20684
21186
  locations: { items: locations, capped: locations.length >= locLimit },
@@ -20938,11 +21440,7 @@ async function fetchCompanies(http, ids2, limit) {
20938
21440
  const out = [];
20939
21441
  for (const id of ids2.slice(0, limit)) {
20940
21442
  try {
20941
- const res = await http.request({
20942
- method: "GET",
20943
- path: `/V1.0/Companies/${id}`,
20944
- operation: "companies.searchByDomain"
20945
- });
21443
+ const res = await cachedRecordGet(http, `/V1.0/Companies/${id}`, "companies.searchByDomain");
20946
21444
  const body = res;
20947
21445
  const item = body && "item" in body ? body.item : null;
20948
21446
  if (item) out.push(item);
@@ -21378,9 +21876,11 @@ var CompaniesResource = class extends GenericResource {
21378
21876
  * fetch; no sub-lists; absent/dangling references come back null). */
21379
21877
  async getContext(id) {
21380
21878
  const company = await this.fetchRecordRaw("/V1.0/Companies", id);
21381
- const root = company;
21382
- const ownerResource = await this.contextFetch("/V1.0/Resources", root["ownerResourceID"]);
21383
- 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
+ ]);
21384
21884
  return { company, ownerResource, parentCompany };
21385
21885
  }
21386
21886
  /** Node-parity special op (hand-written in src/resources/special/companies/search.ts). */
@@ -21928,7 +22428,7 @@ function dateBucketLabel(value, bucket) {
21928
22428
  var queryResourceKeysPromise = null;
21929
22429
  function queryResourceKeys() {
21930
22430
  if (queryResourceKeysPromise === null) {
21931
- queryResourceKeysPromise = chunkSGH7F2CH_cjs.loadCapabilityRecords().then((records) => {
22431
+ queryResourceKeysPromise = chunkKAZE4WC7_cjs.loadCapabilityRecords().then((records) => {
21932
22432
  const s = /* @__PURE__ */ new Set();
21933
22433
  for (const rec of records) if (rec.operation === "query") s.add(rec.resource);
21934
22434
  return s;
@@ -22050,7 +22550,7 @@ function parseTopAndLimit(opts, problems) {
22050
22550
  return { top, limit };
22051
22551
  }
22052
22552
  async function checkFieldNames(resourceKey, conditions, opts, problems) {
22053
- const records = resourceKey === void 0 ? [] : await chunkSGH7F2CH_cjs.loadCapabilityRecords();
22553
+ const records = resourceKey === void 0 ? [] : await chunkKAZE4WC7_cjs.loadCapabilityRecords();
22054
22554
  const record = resourceKey === void 0 ? void 0 : records.find((r) => r.resource === resourceKey && r.operation === "query");
22055
22555
  if (record === void 0) return void 0;
22056
22556
  const strings = (v) => Array.isArray(v) ? v.filter((f) => typeof f === "string" && f.trim() !== "") : [];
@@ -22460,7 +22960,7 @@ async function fetchByIds(client, items, opts = {}) {
22460
22960
  }
22461
22961
  groups.set(item.resource, g);
22462
22962
  }
22463
- const byKey = /* @__PURE__ */ new Map();
22963
+ const byKey2 = /* @__PURE__ */ new Map();
22464
22964
  for (const [key, group] of groups) {
22465
22965
  const holder = client[camelKey(key)];
22466
22966
  if (holder === void 0) {
@@ -22489,28 +22989,28 @@ async function fetchByIds(client, items, opts = {}) {
22489
22989
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22490
22990
  for (const u of chunk) {
22491
22991
  const q = kOf(u);
22492
- 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 });
22493
22993
  }
22494
22994
  return true;
22495
22995
  }
22496
22996
  });
22497
22997
  for (const [k, row] of foundRows) {
22498
22998
  const q = kOf(k);
22499
- if (!byKey.has(q)) byKey.set(q, { found: true, value: row });
22999
+ if (!byKey2.has(q)) byKey2.set(q, { found: true, value: row });
22500
23000
  }
22501
23001
  for (const id of unique) {
22502
23002
  const k = kOf(id);
22503
- if (byKey.has(k)) continue;
23003
+ if (byKey2.has(k)) continue;
22504
23004
  try {
22505
23005
  const value = await holder.get(id);
22506
- byKey.set(k, { found: true, value });
23006
+ byKey2.set(k, { found: true, value });
22507
23007
  } catch (err) {
22508
23008
  if (err instanceof NotFoundError) {
22509
- 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 } });
22510
23010
  } else if (isAutotaskError(err) && err.code !== "ABORTED") {
22511
23011
  const e = { code: err.code, message: err.message };
22512
23012
  if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
22513
- byKey.set(k, { found: false, value: null, error: e });
23013
+ byKey2.set(k, { found: false, value: null, error: e });
22514
23014
  } else {
22515
23015
  throw err;
22516
23016
  }
@@ -22521,7 +23021,7 @@ async function fetchByIds(client, items, opts = {}) {
22521
23021
  for (let i = 0; i < items.length; i += 1) {
22522
23022
  const item = items[i];
22523
23023
  const id = canonical[i];
22524
- const out = byKey.get(`${item.resource}:${String(id)}`);
23024
+ const out = byKey2.get(`${item.resource}:${String(id)}`);
22525
23025
  const value = out.found ? item.fields !== void 0 ? project2(out.value, item.fields) : out.value : null;
22526
23026
  results.push(
22527
23027
  out.found ? { resource: item.resource, id, found: true, value } : { resource: item.resource, id, found: false, value: null, error: out.error }
@@ -22690,7 +23190,7 @@ async function uiLink(client, input) {
22690
23190
  var indexPromise = null;
22691
23191
  function operationIndex() {
22692
23192
  if (indexPromise === null) {
22693
- 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])));
22694
23194
  }
22695
23195
  return indexPromise;
22696
23196
  }
@@ -23049,7 +23549,10 @@ async function revenueRollup(client, opts) {
23049
23549
  const groupDims = v.groupBy.map((d) => DIMENSIONS[d]);
23050
23550
  const paths = [.../* @__PURE__ */ new Set([CONTRACTS_PATH, ...groupDims.flatMap((d) => d.picklist ? [d.picklist] : [])])];
23051
23551
  const labels = {};
23052
- 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
+ });
23053
23556
  const contractLabels = labels[CONTRACTS_PATH];
23054
23557
  const typeValues = contractLabels.get("contractType") ?? /* @__PURE__ */ new Map();
23055
23558
  const inTypes = v.contractTypes ? resolveSelector(OP4, "contractTypes", v.contractTypes, typeValues) : new Map([...typeValues].filter(([, l]) => DEFAULT_CONTRACT_TYPE_RE.test(l)));
@@ -23078,10 +23581,12 @@ async function revenueRollup(client, opts) {
23078
23581
  const invoiceFilter = (voided2) => [...windowOn("invoiceDateTime"), { field: "isVoided", op: "eq", value: voided2 }];
23079
23582
  const withVoided = v.scopeKind !== "contractIDs";
23080
23583
  const voidedFilter = [...invoiceFilter(true), ...scopeIds !== void 0 && withVoided ? [{ field: "companyID", op: "in", value: scopeIds }] : []];
23081
- const nInvoices = await invoices.count({ filter: invoiceFilter(false) });
23082
- const nLines = await billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] });
23083
23584
  const uninvoicedFilter = [{ field: "invoiceID", op: "notExist" }, ...windowOn("itemDate"), ...scopeCond];
23084
- 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
+ ]);
23085
23590
  if (typeof nInvoices !== "number" || typeof nLines !== "number" || typeof nUninvoiced !== "number") throw blindCountError(OP4, "the roll-up", BLIND_ACTION);
23086
23591
  const joinsNeeded = Object.keys(JOINS).filter((j) => j === "contracts" || groupDims.some((d) => d.joins?.[j]));
23087
23592
  const chunks4 = pages(nInvoices);
@@ -23126,14 +23631,17 @@ async function revenueRollup(client, opts) {
23126
23631
  if (v.nonChargeable && uninvoiced.length !== nUninvoiced) throw countMismatchError(OP4, "uninvoiced line", uninvoiced.length, nUninvoiced);
23127
23632
  const all = uninvoiced.length > 0 ? [...lines, ...uninvoiced] : lines;
23128
23633
  const joined = Object.fromEntries(Object.keys(JOINS).map((j) => [j, /* @__PURE__ */ new Map()]));
23129
- for (const j of joinsNeeded) {
23634
+ const fetchJoin = async (j) => {
23130
23635
  const spec = JOINS[j];
23131
23636
  const res = spec.make(http);
23132
23637
  const fields = [.../* @__PURE__ */ new Set([...spec.fields, ...groupDims.flatMap((d) => d.joins?.[j] ?? [])])];
23133
23638
  const want = [...new Set(spec.ids(all, joined))].filter((id) => id > 0).sort((a, b) => a - b);
23134
23639
  const rows = await client.batch((c) => collectRows(res, [{ field: "id", op: "in", value: c }], fields, PAGE), idChunks(want, PAGE), { concurrency: CONCURRENCY });
23135
23640
  for (const r of rows.flat()) joined[j].set(num(r["id"]), r);
23136
- }
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);
23137
23645
  return fold(v, { invoiceById, voided, lines, uninvoiced, joined, labels, inTypes, inCategories, scopeIds, calls: budget.spent(), estimate });
23138
23646
  }
23139
23647
  function refusal(v, estimate, fixed, scopeIds, joinCount) {
@@ -23515,7 +24023,7 @@ function capJoinSet2(ids2, cap) {
23515
24023
  }
23516
24024
  async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity) {
23517
24025
  const unique = [...new Set(ids2)].sort((a, b) => a - b);
23518
- const byKey = /* @__PURE__ */ new Map();
24026
+ const byKey2 = /* @__PURE__ */ new Map();
23519
24027
  const misses = [];
23520
24028
  const notes = [];
23521
24029
  const found = await fetchIdChunks(http, entityPath, unique, fields, operation, {
@@ -23525,17 +24033,17 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23525
24033
  const code = err instanceof AutotaskError ? err.code : "SERVER_ERROR";
23526
24034
  for (const k of chunk) {
23527
24035
  const id = Number(k);
23528
- 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) });
23529
24037
  }
23530
24038
  return true;
23531
24039
  }
23532
24040
  });
23533
- for (const [k, row] of found) byKey.set(Number(k), row);
23534
- 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));
23535
24043
  for (const k of queryMissed) {
23536
24044
  try {
23537
24045
  const res = await http.request({ method: "GET", path: `${entityPath}/${k}`, operation });
23538
- byKey.set(k, unwrapItem(res, k, operation, entity));
24046
+ byKey2.set(k, unwrapItem(res, k, operation, entity));
23539
24047
  } catch (err) {
23540
24048
  if (err instanceof NotFoundError) {
23541
24049
  misses.push({ id: k, code: "NOT_FOUND", message: err.message });
@@ -23546,14 +24054,14 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
23546
24054
  }
23547
24055
  }
23548
24056
  }
23549
- 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);
23550
24058
  const gotByQuery = unique.length - queryMissed.length;
23551
- if (queryMissed.length > 0 && gotByQuery === 0 && byKey.size > 0) {
24059
+ if (queryMissed.length > 0 && gotByQuery === 0 && byKey2.size > 0) {
23552
24060
  notes.push(
23553
- `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)`
23554
24062
  );
23555
24063
  }
23556
- const foundIds = new Set(byKey.keys());
24064
+ const foundIds = new Set(byKey2.keys());
23557
24065
  if (misses.length > 0) {
23558
24066
  const byCode = /* @__PURE__ */ new Map();
23559
24067
  for (const m of misses) byCode.set(m.code, (byCode.get(m.code) ?? 0) + 1);
@@ -23645,6 +24153,17 @@ function makeFetchCtx(rawHttp, v, contractId, budget, sharedExpenses) {
23645
24153
  };
23646
24154
  return { v, OP: OP14, id, idNum, rawHttp, http, wires, windowOn, readPart, windowedPart, truncatedMonths, ...sharedExpenses ? { sharedExpenses } : {} };
23647
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
+ }
23648
24167
 
23649
24168
  // src/resources/special/contracts/profitability.util.ts
23650
24169
  function dateToDay(v) {
@@ -23793,11 +24312,7 @@ async function fetchCustomer(ctx, companyID) {
23793
24312
  let customerAbsent;
23794
24313
  if (companyID > 0) {
23795
24314
  try {
23796
- const res = await ctx.http.request({
23797
- method: "GET",
23798
- path: `/V1.0/Companies/${companyID}`,
23799
- operation: ctx.OP
23800
- });
24315
+ const res = await cachedRecordGet(ctx.http, `/V1.0/Companies/${companyID}`, ctx.OP);
23801
24316
  const item = unwrapItem(res, companyID, ctx.OP, "company");
23802
24317
  customer = item ?? null;
23803
24318
  customerStatus = "ok";
@@ -23827,16 +24342,17 @@ async function resolveContractType(ctx, contractType) {
23827
24342
  const isTimeAndMaterials = contractTypeKnown && TIME_AND_MATERIALS_LABEL_RE.test(contractTypeLabel);
23828
24343
  return { contractTypeLabel, contractTypeKnown, isBlockHours, isTimeAndMaterials };
23829
24344
  }
23830
- async function fetchRoot(ctx, resource) {
23831
- const contractCached = ctx.rawHttp.readCache?.get(`/V1.0/Contracts/${ctx.id}`) !== void 0;
23832
- 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");
23833
24348
  ctx.wires.issued += 1;
23834
- if (!contractCached) ctx.wires.requests += 1;
23835
24349
  const contractRow = contract;
23836
24350
  const companyID = num(contractRow["companyID"]);
23837
24351
  const contractType = num(contractRow["contractType"]);
23838
- const customerStage = await fetchCustomer(ctx, companyID);
23839
- const typeStage = await resolveContractType(ctx, contractType);
24352
+ const [customerStage, typeStage] = await readTasks(ctx.http, [
24353
+ () => fetchCustomer(ctx, companyID),
24354
+ () => resolveContractType(ctx, contractType)
24355
+ ]);
23840
24356
  return { contract, contractRow, contractType, ...customerStage, ...typeStage };
23841
24357
  }
23842
24358
  async function fetchCharges(ctx) {
@@ -23847,27 +24363,29 @@ async function fetchCharges(ctx) {
23847
24363
  const raw = await ctx.readPart("/V1.0/ContractCharges/query", chargesCond, ["id", "chargeType", "billableAmount", "extendedCost", "unitCost", "unitPrice", "unitQuantity", "datePurchased", "isBilled", "status", "contractServiceID"]);
23848
24364
  return { charges: raw.items, chargesPart: stampPart("contract_charges", raw, chargesCond) };
23849
24365
  }
23850
- async function fetchBlocks(ctx, root) {
23851
- if (!root.isBlockHours) {
24366
+ async function fetchBlocks(ctx, root2) {
24367
+ if (!root2.isBlockHours) {
23852
24368
  return skipPart(
23853
- 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)`
23854
24370
  );
23855
24371
  }
23856
24372
  const blocksCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23857
24373
  const raw = await ctx.readPart("/V1.0/ContractBlocks/query", blocksCond, ["id", "datePurchased", "startDate", "endDate", "hours", "hoursApproved", "status", "isPaid"]);
23858
24374
  return stampPart("contract_blocks", raw, blocksCond);
23859
24375
  }
23860
- async function fetchContractState(ctx, root) {
24376
+ async function fetchContractState(ctx, root2) {
23861
24377
  const servicesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23862
- const servicesRaw = await ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]);
23863
24378
  const unitsCond = [{ field: "contractID", op: "eq", value: ctx.id }, ...ctx.windowOn("startDate")];
23864
- 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");
23865
- const { chargesPart, charges } = await fetchCharges(ctx);
23866
24379
  const roleCostsCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23867
- const roleCostsRaw = await ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]);
23868
24380
  const ratesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
23869
- const ratesRaw = await ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]);
23870
- 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
+ ]);
23871
24389
  return { servicesRaw, servicesCond, unitRows: units.rows, unitsPartRaw: units.part, chargesPart, charges, roleCostsRaw, roleCostsCond, ratesRaw, ratesCond, blocksPart };
23872
24390
  }
23873
24391
  async function fetchBillingItems(ctx) {
@@ -24230,25 +24748,46 @@ async function fetchSubscriptionsJoin(ctx) {
24230
24748
  }
24231
24749
 
24232
24750
  // src/resources/special/contracts/profitability.data.ts
24233
- async function gather(ctx, resource) {
24234
- const root = await fetchRoot(ctx, resource);
24235
- const state = await fetchContractState(ctx, root);
24236
- const billing = await fetchBilling(ctx);
24237
- const time = await fetchTime(ctx);
24238
- const activity = await fetchTicketActivity(ctx, time.entries);
24239
- const open = await fetchOpenTickets(ctx);
24240
- const res = await fetchResources(ctx, time.entries);
24241
- const join = await fetchTicketJoinParts(ctx, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
24242
- const subs = await fetchSubscriptionsJoin(ctx);
24243
- 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 };
24244
24783
  }
24245
24784
  function stampListParts(v, f) {
24246
- const { state, activity, join } = f;
24785
+ const { state: state2, activity, join } = f;
24247
24786
  return {
24248
- servicesPart: stampPart("contract_services", state.servicesRaw, state.servicesCond),
24249
- unitsPart: state.unitsPartRaw,
24250
- roleCostsPart: stampPart("contract_role_costs", state.roleCostsRaw, state.roleCostsCond),
24251
- 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),
24252
24791
  ticketsActivityPart: stampPart("tickets", activity.ticketsActRaw, activity.ticketsActCond, [
24253
24792
  ...activity.ticketsActRaw.hasMore ? [`${join.fetchedTickets.size} ticket(s) returned of possibly more \u2014 the checks cover the returned set only`] : [],
24254
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`] : []
@@ -24889,7 +25428,7 @@ async function profitability(resource, contractId, opts, sharedExpenses) {
24889
25428
  const v = validateProfitabilityOptions(contractId, opts);
24890
25429
  const ctx = makeFetchCtx(resource.http, v, contractId, PROFITABILITY_WIRE_BUDGET, sharedExpenses);
24891
25430
  const asOf = (/* @__PURE__ */ new Date()).toISOString();
24892
- const f = await gather(ctx, resource);
25431
+ const f = await gather(ctx);
24893
25432
  const fc = makeFoldCtx(ctx, f, stampListParts(v, f), Date.parse(asOf));
24894
25433
  return assemble(ctx, fc, asOf);
24895
25434
  }
@@ -24976,17 +25515,30 @@ function validate2(opts) {
24976
25515
  function latchingHttp(raw, spend) {
24977
25516
  const counted = countingHttp(raw, spend);
24978
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]);
24979
25521
  const http = Object.create(counted);
24980
- 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) => {
24981
25534
  if (fatal) throw fatal;
24982
25535
  try {
24983
- return await counted.request(o);
25536
+ return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail);
24984
25537
  } catch (err) {
24985
- if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") fatal ??= err;
24986
- throw err;
25538
+ return fail(err);
24987
25539
  }
24988
25540
  };
24989
- return { http, fatal: () => fatal };
25541
+ return { http, fatal: () => fatal, signal };
24990
25542
  }
24991
25543
  async function portfolioMargin(client, opts) {
24992
25544
  const v = validate2(opts);
@@ -24997,7 +25549,7 @@ async function portfolioMargin(client, opts) {
24997
25549
  { phase: estimate === 0 ? "estimate" : "walk", budget: v.budget, vendorCalls: spent, ...estimate > 0 ? { estimate } : {} },
24998
25550
  `Pass maxVendorCalls > ${v.budget} (cap ${BUDGET_CAP2}) or fewer contracts.`
24999
25551
  ));
25000
- const { http, fatal } = latchingHttp(client.http, budget.spend);
25552
+ const { http, fatal, signal } = latchingHttp(client.http, budget.spend);
25001
25553
  const contracts = new ContractsResource(http, PAGE2);
25002
25554
  let typeMap;
25003
25555
  if (v.contractTypes) {
@@ -25044,7 +25596,7 @@ async function portfolioMargin(client, opts) {
25044
25596
  let results;
25045
25597
  try {
25046
25598
  const shared = countFault ?? (expenseCount === 0 ? { rows: [], contractOf: /* @__PURE__ */ new Map(), misses: 0 } : await readTicketExpenses(http, expenseItems, expenseFilter, expenseCount));
25047
- 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 }));
25048
25600
  } catch (err) {
25049
25601
  throw fatal() ?? err;
25050
25602
  }
@@ -25287,8 +25839,10 @@ async function recurringRevenue(client, opts) {
25287
25839
  ];
25288
25840
  const subsRes = res("subscriptions");
25289
25841
  const subFilter = [{ field: "effectiveDate", op: "lt", value: next }, { field: "expirationDate", op: "gte", value: v.asOf }];
25290
- const nContracts = await countOf(contractsRes, "contract", contractFilter);
25291
- 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
+ ]);
25292
25846
  const chunks4 = Math.ceil(nContracts / CHUNK);
25293
25847
  const subCalls = Math.ceil(nSubs / PAGE3) + (nSubs > 0 ? 1 : 0) + Math.ceil(nSubs / CHUNK) + (v.scopeIds ? 1 : Math.ceil((nContracts + nSubs) / CHUNK));
25294
25848
  const refuse3 = (calls, sets2) => {
@@ -25327,26 +25881,35 @@ async function recurringRevenue(client, opts) {
25327
25881
  nCharges: 0
25328
25882
  };
25329
25883
  });
25330
- for (const x of sets) {
25331
- x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
25332
- x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
25333
- }
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());
25334
25892
  const nUnits = sets.reduce((a, x) => a + x.nUnits, 0);
25335
25893
  const nCharges = sets.reduce((a, x) => a + x.nCharges, 0);
25336
25894
  estimate = budget.spent() + sets.reduce((a, x) => a + Math.ceil(x.nUnits / PAGE3) + Math.ceil(x.nCharges / PAGE3), 0) + subCalls;
25337
25895
  if (estimate > v.budget) {
25338
25896
  throw refuse3(estimate, { contracts: nContracts, serviceUnits: nUnits, charges: nCharges, subscriptions: nSubs });
25339
25897
  }
25340
- const units = [];
25341
- const charges = [];
25342
- for (const x of sets) {
25343
- units.push(...await gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits));
25344
- charges.push(...await gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges));
25345
- }
25346
- const subs = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
25347
- const labels = subs.length > 0 ? await readPicklists(http, "/V1.0/Subscriptions", OP6) : /* @__PURE__ */ new Map();
25348
- const ciIds = [...new Set(subs.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
25349
- 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();
25350
25913
  const contractOf = new Map(contracts.map((c) => [num(c["id"]), c]));
25351
25914
  const latest = /* @__PURE__ */ new Map();
25352
25915
  for (const u of units) {
@@ -26059,7 +26622,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26059
26622
  suggestedAction: "Narrow the dateWorked window, or page it with cursor (rows mode reports unconfirmed entries via truncated)."
26060
26623
  });
26061
26624
  }
26062
- for (const [id, state] of joined.states) states.set(id, state);
26625
+ for (const [id, state2] of joined.states) states.set(id, state2);
26063
26626
  cursor = page.items.length === 0 ? null : page.pageDetails.nextPageUrl ?? null;
26064
26627
  } while (cursor !== null);
26065
26628
  spend();
@@ -26077,7 +26640,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
26077
26640
  });
26078
26641
  }
26079
26642
  let postedCount = 0;
26080
- for (const state of states.values()) if (state === "posted") postedCount += 1;
26643
+ for (const state2 of states.values()) if (state2 === "posted") postedCount += 1;
26081
26644
  return { window, total: states.size, postedCount, unpostedCount: states.size - postedCount, vendorCalls: callBudget.spent(), estimate, budget };
26082
26645
  }
26083
26646
  async function dateWorkedWindow(resource, from, to, opts) {
@@ -26098,8 +26661,8 @@ async function dateWorkedWindow(resource, from, to, opts) {
26098
26661
  const { states, incomplete } = await postedStateOf(http, items, OP14);
26099
26662
  let postedCount = 0;
26100
26663
  let unpostedCount = 0;
26101
- for (const state of states.values()) {
26102
- if (state === "posted") postedCount += 1;
26664
+ for (const state2 of states.values()) {
26665
+ if (state2 === "posted") postedCount += 1;
26103
26666
  else unpostedCount += 1;
26104
26667
  }
26105
26668
  return {
@@ -26383,12 +26946,14 @@ async function wipHours(client, opts) {
26383
26946
  } else {
26384
26947
  const contractIds = positiveIds2(wipIn.map((e) => e["contractID"]));
26385
26948
  gate(chunks2(contractIds.length) + (contractIds.length > 0 ? 1 : 0), "before label reads", { contracts: contractIds.length });
26386
- 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
+ ]);
26387
26953
  const typeOf = (id) => contracts.get(String(id))?.["contractType"];
26388
26954
  const bad = contractIds.filter((id) => typeof typeOf(id) !== "number");
26389
26955
  if (bad.length > 0) throw unresolved("contracts", bad);
26390
26956
  keyOfEntry = (e) => num(e["contractID"]) > 0 ? typeOf(num(e["contractID"])) : null;
26391
- const types = contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0;
26392
26957
  for (const [id, label] of types ?? []) labels.set(id, { label });
26393
26958
  }
26394
26959
  const approvalData = entries.some((e) => isApproved(e));
@@ -26580,8 +27145,10 @@ async function nonChargeableWork(client, opts) {
26580
27145
  const contractIds = distinctIds(ncLines.map((x) => x.line["contractID"]), 1);
26581
27146
  const typed = v.groupBy === "contractType";
26582
27147
  gate(chunks3(contractIds.length) + (typed && contractIds.length > 0 ? 1 : 0) + (v.includeUnpostedTime ? 1 : 0), "before label reads", { contracts: contractIds.length });
26583
- const contracts = await readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]);
26584
- 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
+ ]);
26585
27152
  keyOfLine = (line) => {
26586
27153
  if (num(line["contractID"]) === 0) return null;
26587
27154
  const c = contracts.get(String(line["contractID"]));
@@ -27063,6 +27630,10 @@ async function openTicketsOfPart(client, field, id, limit) {
27063
27630
  const filter = [{ field, op: "eq", value: id }, ...closed.map((v) => ({ field: "status", op: "noteq", value: v }))];
27064
27631
  return { ...await compositePart(client, "tickets.query", [{ filter, limit }]), closedStatus };
27065
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
+ }
27066
27637
 
27067
27638
  // src/resources/special/contracts/fullProfile.ts
27068
27639
  var OP12 = "contracts.fullProfile";
@@ -27073,21 +27644,23 @@ async function fullProfile2(resource, id, opts = {}) {
27073
27644
  const serviceLimit = compositePartLimit(opts.serviceLimit, "serviceLimit", OP12);
27074
27645
  const billingRuleLimit = compositePartLimit(opts.billingRuleLimit, "billingRuleLimit", OP12);
27075
27646
  const contractId = parseIdentifier(id, "id");
27076
- const root = await invokeRead(client, "contracts.get", [contractId]);
27077
- const services = await compositePart(client, "contract_services.query", [
27078
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
27079
- ]);
27080
- const billingRules = await compositePart(client, "contract_billing_rules.query", [
27081
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
27082
- ]);
27083
- const charges = await compositePart(client, "contract_charges.query", [
27084
- { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
27085
- ]);
27086
- const units = await compositePart(client, "contract_service_units.query", [
27087
- { 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
+ ])
27088
27661
  ]);
27089
27662
  return {
27090
- root,
27663
+ root: root2,
27091
27664
  parts: {
27092
27665
  services,
27093
27666
  billing_rules: billingRules,
@@ -27194,7 +27767,6 @@ exports.GenericResource = GenericResource;
27194
27767
  exports.HostPolicyDeniedError = HostPolicyDeniedError;
27195
27768
  exports.HttpClient = HttpClient;
27196
27769
  exports.INVOKE_OPTION_KEYS = INVOKE_OPTION_KEYS;
27197
- exports.IN_FILTER_CAP = IN_FILTER_CAP;
27198
27770
  exports.InvoicesResource = InvoicesResource;
27199
27771
  exports.MAX_FIELD_CATALOG_WIRE = MAX_FIELD_CATALOG_WIRE;
27200
27772
  exports.MIN_FIELD_CATALOG_MAX_BYTES = MIN_FIELD_CATALOG_MAX_BYTES;
@@ -27232,6 +27804,7 @@ exports.buildDryRunResult = buildDryRunResult;
27232
27804
  exports.buildQueryRequest = buildQueryRequest;
27233
27805
  exports.buildReadCache = buildReadCache;
27234
27806
  exports.buildUiLink = buildUiLink;
27807
+ exports.cachedRecordGet = cachedRecordGet;
27235
27808
  exports.clientOf = clientOf;
27236
27809
  exports.compositePart = compositePart;
27237
27810
  exports.compositePartLimit = compositePartLimit;
@@ -27255,19 +27828,20 @@ exports.invokeWrite = invokeWrite;
27255
27828
  exports.isAutotaskError = isAutotaskError;
27256
27829
  exports.isClosedStatus = isClosedStatus;
27257
27830
  exports.isDeterministicVendor500 = isDeterministicVendor500;
27831
+ exports.joinedCompositePart = joinedCompositePart;
27258
27832
  exports.mergeDetails = mergeDetails;
27259
27833
  exports.mergePartialBody = mergePartialBody;
27260
27834
  exports.needsConfirmation = needsConfirmation;
27261
27835
  exports.nextActionFor = nextActionFor;
27262
27836
  exports.nonChargeableWork = nonChargeableWork;
27263
27837
  exports.notPersistedFields = notPersistedFields;
27264
- exports.numericIds = numericIds;
27265
27838
  exports.openStatusFilter = openStatusFilter;
27266
27839
  exports.openTicketsOfPart = openTicketsOfPart;
27267
27840
  exports.parseIdentifier = parseIdentifier;
27268
27841
  exports.parseVendorErrors = parseVendorErrors;
27269
27842
  exports.portfolioMargin = portfolioMargin;
27270
27843
  exports.queryRows = queryRows;
27844
+ exports.readTasks = readTasks;
27271
27845
  exports.recurringRevenue = recurringRevenue;
27272
27846
  exports.refuse = refuse2;
27273
27847
  exports.relationshipMap = relationshipMap;
@@ -27279,6 +27853,7 @@ exports.resolveLineOfBusinessChain = resolveLineOfBusinessChain;
27279
27853
  exports.resolveStaff = resolveStaff;
27280
27854
  exports.resolveTicketStatusSemantics = resolveTicketStatusSemantics;
27281
27855
  exports.revenueRollup = revenueRollup;
27856
+ exports.runBounded = runBounded;
27282
27857
  exports.runMove = runMove;
27283
27858
  exports.runWithSignal = runWithSignal;
27284
27859
  exports.sanitiseResult = sanitiseResult;