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.
- package/CHANGELOG.md +12 -0
- package/MCP_TOOL_CATALOG.json +2 -2
- package/README.md +51 -10
- package/capabilities.json +7 -7
- package/dist/capabilities-data.js +6 -6
- package/dist/capabilities.cjs +4 -4
- package/dist/capabilities.js +1 -1
- package/dist/{chunk-2D2KJOX2.cjs → chunk-24GRFW55.cjs} +236 -222
- package/dist/{chunk-LOLWHPTJ.js → chunk-2BB7OASJ.js} +3 -30
- package/dist/{chunk-S6HEIGGM.js → chunk-AH6WAGPS.js} +80 -66
- package/dist/{chunk-KRQONGLD.cjs → chunk-DPRY3CUJ.cjs} +30 -57
- package/dist/{chunk-XKIRTR37.cjs → chunk-JLBSUZ5B.cjs} +919 -344
- package/dist/{chunk-SGH7F2CH.cjs → chunk-KAZE4WC7.cjs} +3 -3
- package/dist/{chunk-YYHCZRUH.js → chunk-QDBJCGQD.js} +912 -339
- package/dist/{chunk-JCMXQUIC.js → chunk-SCFB5MF3.js} +3 -3
- package/dist/{index-DQ08uOH0.d.ts → index-CxBU31jT.d.ts} +16 -9
- package/dist/{index-mIsdpO5d.d.cts → index-WZ3A8nG6.d.cts} +16 -9
- package/dist/index.cjs +92 -85
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +14 -7
- package/dist/operations/index.cjs +50 -50
- package/dist/operations/index.d.cts +2 -2
- package/dist/operations/index.d.ts +2 -2
- package/dist/operations/index.js +2 -2
- package/dist/pool.cjs +12 -12
- package/dist/pool.js +4 -4
- package/dist/resources/index.cjs +27 -27
- package/dist/resources/index.d.cts +1 -1
- package/dist/resources/index.d.ts +1 -1
- package/dist/resources/index.js +3 -3
- package/docs/API.md +77 -16
- package/docs/LIVE-TESTING.md +16 -2
- package/docs/VENDOR-QUIRKS.md +39 -0
- package/docs/performance-finance.md +35 -0
- package/examples/mcp-env-config.ts +3 -4
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { loadCapabilityRecords } from './chunk-
|
|
1
|
+
import { loadCapabilityRecords } from './chunk-SCFB5MF3.js';
|
|
2
2
|
import { NoopLogger, REDACTED, deepMarkUntrusted, wrapUntrusted } from './chunk-7NKB4UXV.js';
|
|
3
|
-
import { randomUUID } from 'crypto';
|
|
3
|
+
import { randomUUID, createHash } from 'crypto';
|
|
4
4
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
5
5
|
|
|
6
6
|
// src/errors/base.ts
|
|
@@ -114,7 +114,7 @@ var ConflictError = class extends AutotaskError {
|
|
|
114
114
|
var RateLimitError = class extends AutotaskError {
|
|
115
115
|
/** Seconds the server asked the client to wait (`Retry-After`), when present. */
|
|
116
116
|
retryAfter;
|
|
117
|
-
/** True when the call was refused locally (
|
|
117
|
+
/** True when the call was refused locally (cooldown or hourly admission) and never sent. */
|
|
118
118
|
notSent;
|
|
119
119
|
constructor(message, options = {}) {
|
|
120
120
|
super(message, { code: "RATE_LIMITED", category: "rate_limit", retryable: true, ...options });
|
|
@@ -634,6 +634,7 @@ var TtlCache = class {
|
|
|
634
634
|
ttlFor;
|
|
635
635
|
store = /* @__PURE__ */ new Map();
|
|
636
636
|
inflightMap = /* @__PURE__ */ new Map();
|
|
637
|
+
loads = /* @__PURE__ */ new Map();
|
|
637
638
|
epochCounter = 0;
|
|
638
639
|
constructor(ttlMs, options = {}) {
|
|
639
640
|
if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
|
|
@@ -657,6 +658,85 @@ var TtlCache = class {
|
|
|
657
658
|
}
|
|
658
659
|
return structuredClone(entry.value);
|
|
659
660
|
}
|
|
661
|
+
/**
|
|
662
|
+
* Load one record once for concurrent callers. Each subscriber owns its
|
|
663
|
+
* cancellation and receives a copy. The wire read is cancelled only when
|
|
664
|
+
* its last subscriber leaves. A fresh load starts a new flight and prevents
|
|
665
|
+
* an older flight from replacing its result; invalidation detaches flights
|
|
666
|
+
* without changing the answer owed to their existing subscribers.
|
|
667
|
+
* @internal
|
|
668
|
+
*/
|
|
669
|
+
async load(key, loader, opts) {
|
|
670
|
+
const { signal } = opts;
|
|
671
|
+
if (signal?.aborted) throw opts.abortError();
|
|
672
|
+
if (!opts.fresh) {
|
|
673
|
+
const hit = this.get(key);
|
|
674
|
+
if (hit !== void 0) return hit;
|
|
675
|
+
}
|
|
676
|
+
let flight = opts.fresh ? void 0 : this.loads.get(key);
|
|
677
|
+
let start;
|
|
678
|
+
if (flight === void 0) {
|
|
679
|
+
const epoch = this.epoch;
|
|
680
|
+
const controller = new AbortController();
|
|
681
|
+
const created = { controller, promise: Promise.resolve(), subscribers: 0, settled: false };
|
|
682
|
+
created.promise = new Promise((resolve, reject) => {
|
|
683
|
+
start = () => {
|
|
684
|
+
try {
|
|
685
|
+
resolve(loader(controller.signal));
|
|
686
|
+
} catch (error) {
|
|
687
|
+
if (this.loads.get(key) === created) this.loads.delete(key);
|
|
688
|
+
reject(error);
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
}).then((value) => {
|
|
692
|
+
if (this.loads.get(key) === created && !controller.signal.aborted) this.set(key, value, epoch);
|
|
693
|
+
return value;
|
|
694
|
+
});
|
|
695
|
+
const settled = () => {
|
|
696
|
+
created.settled = true;
|
|
697
|
+
if (this.loads.get(key) === created) this.loads.delete(key);
|
|
698
|
+
};
|
|
699
|
+
created.promise.then(settled, settled);
|
|
700
|
+
this.loads.set(key, created);
|
|
701
|
+
flight = created;
|
|
702
|
+
}
|
|
703
|
+
const shared = flight;
|
|
704
|
+
shared.subscribers += 1;
|
|
705
|
+
const result = new Promise((resolve, reject) => {
|
|
706
|
+
let active = true;
|
|
707
|
+
const leave = () => {
|
|
708
|
+
if (!active) return false;
|
|
709
|
+
active = false;
|
|
710
|
+
signal?.removeEventListener("abort", aborted);
|
|
711
|
+
shared.subscribers -= 1;
|
|
712
|
+
if (shared.subscribers === 0 && !shared.settled) {
|
|
713
|
+
if (this.loads.get(key) === shared) this.loads.delete(key);
|
|
714
|
+
shared.controller.abort();
|
|
715
|
+
}
|
|
716
|
+
return true;
|
|
717
|
+
};
|
|
718
|
+
const aborted = () => {
|
|
719
|
+
if (leave()) reject(opts.abortError());
|
|
720
|
+
};
|
|
721
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
722
|
+
shared.promise.then(
|
|
723
|
+
(value) => {
|
|
724
|
+
if (leave()) {
|
|
725
|
+
try {
|
|
726
|
+
resolve(structuredClone(value));
|
|
727
|
+
} catch (error) {
|
|
728
|
+
reject(error);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
(error) => {
|
|
733
|
+
if (leave()) reject(error);
|
|
734
|
+
}
|
|
735
|
+
);
|
|
736
|
+
});
|
|
737
|
+
start?.();
|
|
738
|
+
return result;
|
|
739
|
+
}
|
|
660
740
|
/** Store `value` under `key`. `epoch` is the value the caller read BEFORE its
|
|
661
741
|
* wire request: a read that straddled a `clear()` (a write) is dropped. */
|
|
662
742
|
set(key, value, epoch = this.epochCounter) {
|
|
@@ -691,12 +771,14 @@ var TtlCache = class {
|
|
|
691
771
|
/** Drop one key. */
|
|
692
772
|
delete(key) {
|
|
693
773
|
this.inflightMap.delete(key);
|
|
774
|
+
this.loads.delete(key);
|
|
694
775
|
return this.store.delete(key);
|
|
695
776
|
}
|
|
696
777
|
/** Drop every stored and in-flight key that starts with `prefix`. */
|
|
697
778
|
invalidate(prefix) {
|
|
698
779
|
for (const key of [...this.store.keys()]) if (key.startsWith(prefix)) this.store.delete(key);
|
|
699
780
|
for (const key of [...this.inflightMap.keys()]) if (key.startsWith(prefix)) this.inflightMap.delete(key);
|
|
781
|
+
for (const key of [...this.loads.keys()]) if (key.startsWith(prefix)) this.loads.delete(key);
|
|
700
782
|
}
|
|
701
783
|
/** Drop every expired entry (returns the number removed). */
|
|
702
784
|
purgeExpired() {
|
|
@@ -723,6 +805,7 @@ var TtlCache = class {
|
|
|
723
805
|
this.epochCounter += 1;
|
|
724
806
|
this.store.clear();
|
|
725
807
|
this.inflightMap.clear();
|
|
808
|
+
this.loads.clear();
|
|
726
809
|
}
|
|
727
810
|
};
|
|
728
811
|
|
|
@@ -801,9 +884,10 @@ function cooldownDurationMs(retryAfterSecs, opts) {
|
|
|
801
884
|
}
|
|
802
885
|
return Math.min(retryAfterSecs !== void 0 ? retryAfterSecs * 1e3 : opts.defaultMs, opts.maxMs);
|
|
803
886
|
}
|
|
804
|
-
function admitMaintenance(host, ctx) {
|
|
887
|
+
function admitMaintenance(host, ctx, owned) {
|
|
805
888
|
const gate = maintenance.get(host);
|
|
806
889
|
if (gate === void 0) return "send";
|
|
890
|
+
if (gate === owned && gate.probing) return gate;
|
|
807
891
|
const now = Date.now();
|
|
808
892
|
if (!gate.probing && now >= gate.nextProbeAt) {
|
|
809
893
|
gate.probing = true;
|
|
@@ -1445,8 +1529,8 @@ function buildFilter(conditions) {
|
|
|
1445
1529
|
if (list.length === 0) {
|
|
1446
1530
|
throw new AutotaskConfigError("buildFilter requires at least one condition");
|
|
1447
1531
|
}
|
|
1448
|
-
const
|
|
1449
|
-
const filter = { filter: [
|
|
1532
|
+
const root2 = list.length === 1 ? list[0] : { op: "and", items: list };
|
|
1533
|
+
const filter = { filter: [root2] };
|
|
1450
1534
|
validateFilter(filter);
|
|
1451
1535
|
return filter;
|
|
1452
1536
|
}
|
|
@@ -1715,41 +1799,48 @@ function bodySnippet(text, redactPersonalData) {
|
|
|
1715
1799
|
|
|
1716
1800
|
// src/http/limits.ts
|
|
1717
1801
|
var HourlyBudget = class {
|
|
1718
|
-
constructor(perHour, profile) {
|
|
1802
|
+
constructor(perHour, profile, scope = "local", stamps = []) {
|
|
1719
1803
|
this.perHour = perHour;
|
|
1720
1804
|
this.profile = profile;
|
|
1805
|
+
this.scope = scope;
|
|
1806
|
+
this.stamps = stamps;
|
|
1721
1807
|
}
|
|
1722
1808
|
perHour;
|
|
1723
1809
|
profile;
|
|
1724
|
-
|
|
1725
|
-
stamps
|
|
1810
|
+
scope;
|
|
1811
|
+
stamps;
|
|
1726
1812
|
prune(now) {
|
|
1727
|
-
|
|
1813
|
+
let expired = 0;
|
|
1814
|
+
while (expired < this.stamps.length && this.stamps[expired] <= now - HOUR_MS) expired += 1;
|
|
1815
|
+
if (expired > 0) this.stamps.splice(0, expired);
|
|
1728
1816
|
}
|
|
1729
1817
|
snapshot() {
|
|
1730
1818
|
this.prune(Date.now());
|
|
1731
1819
|
return { perHour: this.perHour, used: this.stamps.length, remaining: Math.max(0, this.perHour - this.stamps.length) };
|
|
1732
1820
|
}
|
|
1733
|
-
/**
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1821
|
+
/** Non-mutating admission check (apart from pruning); callers can inspect several quotas atomically. */
|
|
1822
|
+
waitMs(now) {
|
|
1823
|
+
this.prune(now);
|
|
1824
|
+
return this.stamps.length < this.perHour ? 0 : Math.max(0, this.stamps[0] + HOUR_MS - now);
|
|
1825
|
+
}
|
|
1826
|
+
/** Record an actual attempt immediately after every applicable quota was checked, without awaiting. */
|
|
1827
|
+
record(now) {
|
|
1828
|
+
this.stamps.push(now);
|
|
1829
|
+
}
|
|
1830
|
+
/** The typed local refusal. Its scope determines advice; the shared ceiling cannot be raised. */
|
|
1831
|
+
exhausted(waitMs, ctx) {
|
|
1832
|
+
const shared = this.scope === "origin";
|
|
1833
|
+
const err = new RateLimitError(
|
|
1834
|
+
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`,
|
|
1835
|
+
{
|
|
1836
|
+
...ctx,
|
|
1837
|
+
details: { budgetScope: shared ? "process_origin" : "client" },
|
|
1838
|
+
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."
|
|
1750
1839
|
}
|
|
1751
|
-
|
|
1752
|
-
|
|
1840
|
+
);
|
|
1841
|
+
err.retryAfter = Math.ceil(waitMs / 1e3);
|
|
1842
|
+
err.notSent = true;
|
|
1843
|
+
return err;
|
|
1753
1844
|
}
|
|
1754
1845
|
};
|
|
1755
1846
|
var Semaphore = class {
|
|
@@ -1758,65 +1849,95 @@ var Semaphore = class {
|
|
|
1758
1849
|
}
|
|
1759
1850
|
maxConcurrent;
|
|
1760
1851
|
inFlight = 0;
|
|
1761
|
-
waitQueue =
|
|
1762
|
-
acquire() {
|
|
1852
|
+
waitQueue = /* @__PURE__ */ new Set();
|
|
1853
|
+
acquire(signal) {
|
|
1854
|
+
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
1763
1855
|
if (this.inFlight < this.maxConcurrent) {
|
|
1764
1856
|
this.inFlight += 1;
|
|
1765
1857
|
return Promise.resolve();
|
|
1766
1858
|
}
|
|
1767
|
-
return new Promise((resolve) => {
|
|
1768
|
-
|
|
1859
|
+
return new Promise((resolve, reject) => {
|
|
1860
|
+
const aborted = () => {
|
|
1861
|
+
this.waitQueue.delete(grant);
|
|
1862
|
+
signal?.removeEventListener("abort", aborted);
|
|
1863
|
+
reject(signal?.reason);
|
|
1864
|
+
};
|
|
1865
|
+
const grant = () => {
|
|
1866
|
+
signal?.removeEventListener("abort", aborted);
|
|
1769
1867
|
this.inFlight += 1;
|
|
1770
1868
|
resolve();
|
|
1771
|
-
}
|
|
1869
|
+
};
|
|
1870
|
+
this.waitQueue.add(grant);
|
|
1871
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
1772
1872
|
});
|
|
1773
1873
|
}
|
|
1774
1874
|
release() {
|
|
1775
1875
|
this.inFlight -= 1;
|
|
1776
|
-
const next = this.waitQueue.
|
|
1777
|
-
if (next
|
|
1876
|
+
const next = this.waitQueue.values().next();
|
|
1877
|
+
if (!next.done) {
|
|
1878
|
+
this.waitQueue.delete(next.value);
|
|
1879
|
+
next.value();
|
|
1880
|
+
}
|
|
1778
1881
|
}
|
|
1779
1882
|
};
|
|
1780
1883
|
|
|
1781
|
-
// src/http/
|
|
1782
|
-
var
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1884
|
+
// src/http/hourly-gates.ts
|
|
1885
|
+
var ORIGIN_HOURLY_CEILING = 1e4;
|
|
1886
|
+
var REGISTRY = /* @__PURE__ */ Symbol.for("node-autotask.origin-hourly-gates.v1");
|
|
1887
|
+
var root = globalThis;
|
|
1888
|
+
var registry = root[REGISTRY] ??= { budgets: /* @__PURE__ */ new Map(), active: 0, waiting: 0, requests: 0 };
|
|
1889
|
+
function budgetFor(url) {
|
|
1890
|
+
const origin = new URL(url).origin.toLowerCase();
|
|
1891
|
+
let entry = registry.budgets.get(origin);
|
|
1892
|
+
if (entry === void 0) {
|
|
1893
|
+
for (const [key, previous] of registry.budgets) {
|
|
1894
|
+
if (new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", previous.stamps).snapshot().used === 0) registry.budgets.delete(key);
|
|
1895
|
+
}
|
|
1896
|
+
entry = { stamps: [] };
|
|
1897
|
+
registry.budgets.set(origin, entry);
|
|
1898
|
+
}
|
|
1899
|
+
return new HourlyBudget(ORIGIN_HOURLY_CEILING, "agent", "origin", entry.stamps);
|
|
1900
|
+
}
|
|
1901
|
+
function admitHourlyAttempt(url, local, now) {
|
|
1902
|
+
const origin = budgetFor(url);
|
|
1903
|
+
const budgets = local === void 0 ? [origin] : [local, origin];
|
|
1904
|
+
let blocked;
|
|
1905
|
+
for (const budget of budgets) {
|
|
1906
|
+
const waitMs = budget.waitMs(now);
|
|
1907
|
+
if (waitMs > (blocked?.waitMs ?? 0)) blocked = { admitted: false, budget, waitMs };
|
|
1908
|
+
}
|
|
1909
|
+
if (blocked !== void 0) return blocked;
|
|
1910
|
+
for (const budget of budgets) budget.record(now);
|
|
1911
|
+
registry.active += 1;
|
|
1912
|
+
let active = true;
|
|
1913
|
+
return { admitted: true, finish: () => {
|
|
1914
|
+
if (active) {
|
|
1915
|
+
active = false;
|
|
1916
|
+
registry.active -= 1;
|
|
1917
|
+
}
|
|
1918
|
+
} };
|
|
1919
|
+
}
|
|
1920
|
+
async function waitHourlyAdmission(blocked, deadlineAt, signal, ctx) {
|
|
1921
|
+
if (signal.aborted) throw signal.reason;
|
|
1922
|
+
const now = Date.now();
|
|
1923
|
+
const waitMs = blocked.budget.waitMs(now);
|
|
1924
|
+
if (waitMs === 0) return;
|
|
1925
|
+
if (waitMs >= deadlineAt - now) throw blocked.budget.exhausted(waitMs, ctx);
|
|
1926
|
+
registry.waiting += 1;
|
|
1927
|
+
try {
|
|
1928
|
+
await sleep(waitMs, signal);
|
|
1929
|
+
} finally {
|
|
1930
|
+
registry.waiting -= 1;
|
|
1803
1931
|
}
|
|
1804
1932
|
}
|
|
1805
|
-
function
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
|
|
1814
|
-
if (problem !== void 0) break;
|
|
1815
|
-
}
|
|
1816
|
-
return {
|
|
1817
|
-
headerNames: names,
|
|
1818
|
-
allValuesClean: problem === void 0,
|
|
1819
|
-
...problem !== void 0 ? { problem } : {}
|
|
1933
|
+
function trackHourlyRequest() {
|
|
1934
|
+
registry.requests += 1;
|
|
1935
|
+
let active = true;
|
|
1936
|
+
return () => {
|
|
1937
|
+
if (active) {
|
|
1938
|
+
active = false;
|
|
1939
|
+
registry.requests -= 1;
|
|
1940
|
+
}
|
|
1820
1941
|
};
|
|
1821
1942
|
}
|
|
1822
1943
|
|
|
@@ -14060,6 +14181,171 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
|
|
|
14060
14181
|
]
|
|
14061
14182
|
};
|
|
14062
14183
|
|
|
14184
|
+
// src/http/object-key.ts
|
|
14185
|
+
var UNKNOWN_OBJECT_KEY = "unknown-object";
|
|
14186
|
+
var roots = /* @__PURE__ */ new Map();
|
|
14187
|
+
var byResource = /* @__PURE__ */ new Map();
|
|
14188
|
+
var byKey = /* @__PURE__ */ new Map();
|
|
14189
|
+
function descriptor(row) {
|
|
14190
|
+
const key = row.apiEntity ?? row.resource;
|
|
14191
|
+
let value = byKey.get(key);
|
|
14192
|
+
if (value === void 0) {
|
|
14193
|
+
value = { key, children: /* @__PURE__ */ new Map() };
|
|
14194
|
+
byKey.set(key, value);
|
|
14195
|
+
}
|
|
14196
|
+
return value;
|
|
14197
|
+
}
|
|
14198
|
+
for (const row of Object.values(RELATIONSHIP_MAP)) {
|
|
14199
|
+
const value = descriptor(row);
|
|
14200
|
+
byResource.set(row.resource, value);
|
|
14201
|
+
const path = row.path?.replace(/^\/?v\d+\.\d+\//i, "").replace(/^\//, "");
|
|
14202
|
+
if (path !== void 0 && !path.includes("/")) roots.set(path.toLowerCase(), value);
|
|
14203
|
+
}
|
|
14204
|
+
for (const [alias, resource] of [["expenses", "expense_reports"], ["userdefinedfields", "user_defined_field_definitions"]]) {
|
|
14205
|
+
const value = byResource.get(resource);
|
|
14206
|
+
if (value !== void 0) roots.set(alias, value);
|
|
14207
|
+
}
|
|
14208
|
+
for (const row of Object.values(RELATIONSHIP_MAP)) {
|
|
14209
|
+
const parent = row.parent === null ? void 0 : byResource.get(row.parent.resource);
|
|
14210
|
+
if (parent !== void 0 && row.parent?.segment != null) {
|
|
14211
|
+
parent.children.set(row.parent.segment.toLowerCase(), byResource.get(row.resource));
|
|
14212
|
+
}
|
|
14213
|
+
}
|
|
14214
|
+
function canonicalObjectKey(url) {
|
|
14215
|
+
let path;
|
|
14216
|
+
if (url instanceof URL) {
|
|
14217
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
|
|
14218
|
+
path = url.pathname;
|
|
14219
|
+
} else {
|
|
14220
|
+
try {
|
|
14221
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(url)) {
|
|
14222
|
+
const parsed = new URL(url);
|
|
14223
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return UNKNOWN_OBJECT_KEY;
|
|
14224
|
+
path = parsed.pathname;
|
|
14225
|
+
} else {
|
|
14226
|
+
if (!url.startsWith("/")) return UNKNOWN_OBJECT_KEY;
|
|
14227
|
+
path = url.split(/[?#]/, 1)[0];
|
|
14228
|
+
}
|
|
14229
|
+
} catch {
|
|
14230
|
+
return UNKNOWN_OBJECT_KEY;
|
|
14231
|
+
}
|
|
14232
|
+
}
|
|
14233
|
+
let parts;
|
|
14234
|
+
try {
|
|
14235
|
+
parts = path.split("/").filter(Boolean).map((part) => decodeURIComponent(part).toLowerCase());
|
|
14236
|
+
} catch {
|
|
14237
|
+
return UNKNOWN_OBJECT_KEY;
|
|
14238
|
+
}
|
|
14239
|
+
if (parts.some((part) => part === "." || part === ".." || /[/\\]/.test(part))) return UNKNOWN_OBJECT_KEY;
|
|
14240
|
+
const version = parts.findIndex((part) => /^v\d+\.\d+$/.test(part));
|
|
14241
|
+
if (version >= 0) {
|
|
14242
|
+
if (parts.slice(0, version).some((part) => roots.has(part))) return UNKNOWN_OBJECT_KEY;
|
|
14243
|
+
parts = parts.slice(version + 1);
|
|
14244
|
+
} else if (parts[0] === "atservicesrest") parts = parts.slice(1);
|
|
14245
|
+
let object = roots.get(parts[0] ?? "");
|
|
14246
|
+
if (object === void 0) return UNKNOWN_OBJECT_KEY;
|
|
14247
|
+
if (object.key === "zone_information") return parts.length === 1 ? void 0 : UNKNOWN_OBJECT_KEY;
|
|
14248
|
+
let offset = 1;
|
|
14249
|
+
while (offset < parts.length) {
|
|
14250
|
+
const part = parts[offset];
|
|
14251
|
+
if (/^\d+$/.test(part)) {
|
|
14252
|
+
offset++;
|
|
14253
|
+
if (offset === parts.length) return object.key;
|
|
14254
|
+
const child = object.children.get(parts[offset]);
|
|
14255
|
+
if (child !== void 0) {
|
|
14256
|
+
object = child;
|
|
14257
|
+
offset++;
|
|
14258
|
+
continue;
|
|
14259
|
+
}
|
|
14260
|
+
}
|
|
14261
|
+
const tail = parts.slice(offset);
|
|
14262
|
+
if (tail[0] === "query") return object.key;
|
|
14263
|
+
if (tail[0] === "entityinformation") return object.key;
|
|
14264
|
+
if (tail.length === 1) return object.key;
|
|
14265
|
+
return UNKNOWN_OBJECT_KEY;
|
|
14266
|
+
}
|
|
14267
|
+
return object.key;
|
|
14268
|
+
}
|
|
14269
|
+
|
|
14270
|
+
// src/http/object-threads.ts
|
|
14271
|
+
var REGISTRY2 = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-gates.v1");
|
|
14272
|
+
var OBJECT_THREAD_LIMIT = 3;
|
|
14273
|
+
var state = globalThis;
|
|
14274
|
+
async function acquireObjectThread(url, trackingIdentifier, signal) {
|
|
14275
|
+
if (signal.aborted) throw signal.reason;
|
|
14276
|
+
const target = new URL(url);
|
|
14277
|
+
const object = canonicalObjectKey(target.pathname);
|
|
14278
|
+
if (object === void 0) return () => void 0;
|
|
14279
|
+
const key = createHash("sha256").update(JSON.stringify([target.origin, trackingIdentifier.trim().toLowerCase(), object])).digest("hex");
|
|
14280
|
+
const registry2 = state[REGISTRY2] ??= /* @__PURE__ */ new Map();
|
|
14281
|
+
let entry = registry2.get(key);
|
|
14282
|
+
if (entry === void 0) {
|
|
14283
|
+
entry = { semaphore: new Semaphore(OBJECT_THREAD_LIMIT), users: 0 };
|
|
14284
|
+
registry2.set(key, entry);
|
|
14285
|
+
}
|
|
14286
|
+
const active = entry;
|
|
14287
|
+
active.users += 1;
|
|
14288
|
+
const leave = () => {
|
|
14289
|
+
active.users -= 1;
|
|
14290
|
+
if (active.users === 0 && registry2.get(key) === active) registry2.delete(key);
|
|
14291
|
+
};
|
|
14292
|
+
try {
|
|
14293
|
+
await active.semaphore.acquire(signal);
|
|
14294
|
+
} catch (error) {
|
|
14295
|
+
leave();
|
|
14296
|
+
throw error;
|
|
14297
|
+
}
|
|
14298
|
+
let released = false;
|
|
14299
|
+
return () => {
|
|
14300
|
+
if (released) return;
|
|
14301
|
+
released = true;
|
|
14302
|
+
active.semaphore.release();
|
|
14303
|
+
leave();
|
|
14304
|
+
};
|
|
14305
|
+
}
|
|
14306
|
+
|
|
14307
|
+
// src/http/credentials.ts
|
|
14308
|
+
var CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
|
|
14309
|
+
"ApiIntegrationCode",
|
|
14310
|
+
"UserName",
|
|
14311
|
+
"Secret",
|
|
14312
|
+
"ImpersonationResourceId"
|
|
14313
|
+
]);
|
|
14314
|
+
function assertCredentialShape(headers, auth) {
|
|
14315
|
+
const owned = new Set(CREDENTIAL_HEADER_NAMES);
|
|
14316
|
+
for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
|
|
14317
|
+
for (const name of Object.keys(headers)) {
|
|
14318
|
+
if (!owned.has(name)) continue;
|
|
14319
|
+
const value = headers[name];
|
|
14320
|
+
const shape = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
|
|
14321
|
+
if (shape === void 0) continue;
|
|
14322
|
+
throw new AutotaskConfigError(
|
|
14323
|
+
`${name} ${CREDENTIAL_ENV_LOAD_ACTION} (${shape})`,
|
|
14324
|
+
{
|
|
14325
|
+
code: "INVALID_CREDENTIAL_SHAPE",
|
|
14326
|
+
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."
|
|
14327
|
+
}
|
|
14328
|
+
);
|
|
14329
|
+
}
|
|
14330
|
+
}
|
|
14331
|
+
function credentialShapeExpectation(headers, auth) {
|
|
14332
|
+
const owned = new Set(CREDENTIAL_HEADER_NAMES);
|
|
14333
|
+
for (const name of Object.keys(buildAuthHeaders(auth))) owned.add(name);
|
|
14334
|
+
const names = Object.keys(headers).filter((name) => owned.has(name));
|
|
14335
|
+
if (names.length === 0) return void 0;
|
|
14336
|
+
let problem;
|
|
14337
|
+
for (const name of names) {
|
|
14338
|
+
const value = headers[name];
|
|
14339
|
+
problem = credentialShapeProblem(value.trim(), { skipEdgeWhitespace: true });
|
|
14340
|
+
if (problem !== void 0) break;
|
|
14341
|
+
}
|
|
14342
|
+
return {
|
|
14343
|
+
headerNames: names,
|
|
14344
|
+
allValuesClean: problem === void 0,
|
|
14345
|
+
...problem !== void 0 ? { problem } : {}
|
|
14346
|
+
};
|
|
14347
|
+
}
|
|
14348
|
+
|
|
14063
14349
|
// src/http/envelope.ts
|
|
14064
14350
|
var INVALID_SHAPE_ACTION = "Report the unexpected response shape; verify baseUrl points at the REST API.";
|
|
14065
14351
|
function attachEmptyReasonDetails(err) {
|
|
@@ -14189,38 +14475,45 @@ function canReResolveZone(reResolveZoneOn401, zone, opts) {
|
|
|
14189
14475
|
}
|
|
14190
14476
|
async function discoverZoneBase(userName, maxResponseBytes, signal, ctx) {
|
|
14191
14477
|
const discoveryUrl = `${ZONE_DISCOVERY_URL}?user=${encodeURIComponent(userName)}`;
|
|
14192
|
-
|
|
14193
|
-
|
|
14194
|
-
|
|
14195
|
-
method: "GET",
|
|
14196
|
-
headers: { Accept: "application/json" },
|
|
14197
|
-
redirect: "manual",
|
|
14198
|
-
// a redirect off the discovery host is a fault, not a target
|
|
14199
|
-
signal
|
|
14200
|
-
});
|
|
14201
|
-
} catch {
|
|
14202
|
-
return void 0;
|
|
14203
|
-
}
|
|
14204
|
-
if (res.status < 200 || res.status >= 300) {
|
|
14205
|
-
await res.body?.cancel().catch(() => void 0);
|
|
14206
|
-
return void 0;
|
|
14207
|
-
}
|
|
14208
|
-
let text;
|
|
14209
|
-
try {
|
|
14210
|
-
text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
|
|
14211
|
-
} catch {
|
|
14212
|
-
return void 0;
|
|
14213
|
-
}
|
|
14214
|
-
let body;
|
|
14478
|
+
if (signal.aborted) return void 0;
|
|
14479
|
+
const admission = admitHourlyAttempt(discoveryUrl, void 0, Date.now());
|
|
14480
|
+
if (!admission.admitted) return void 0;
|
|
14215
14481
|
try {
|
|
14216
|
-
|
|
14217
|
-
|
|
14218
|
-
|
|
14219
|
-
|
|
14220
|
-
|
|
14221
|
-
|
|
14482
|
+
let res;
|
|
14483
|
+
try {
|
|
14484
|
+
res = await fetch(discoveryUrl, {
|
|
14485
|
+
method: "GET",
|
|
14486
|
+
headers: { Accept: "application/json" },
|
|
14487
|
+
redirect: "manual",
|
|
14488
|
+
// a redirect off the discovery host is a fault, not a target
|
|
14489
|
+
signal
|
|
14490
|
+
});
|
|
14491
|
+
} catch {
|
|
14492
|
+
return void 0;
|
|
14493
|
+
}
|
|
14494
|
+
if (res.status < 200 || res.status >= 300) {
|
|
14495
|
+
await res.body?.cancel().catch(() => void 0);
|
|
14496
|
+
return void 0;
|
|
14497
|
+
}
|
|
14498
|
+
let text;
|
|
14499
|
+
try {
|
|
14500
|
+
text = await readBodyText(res, maxResponseBytes, "zone discovery", { ...ctx, httpStatus: res.status });
|
|
14501
|
+
} catch {
|
|
14502
|
+
return void 0;
|
|
14503
|
+
}
|
|
14504
|
+
let body;
|
|
14505
|
+
try {
|
|
14506
|
+
body = JSON.parse(text);
|
|
14507
|
+
} catch {
|
|
14508
|
+
return void 0;
|
|
14509
|
+
}
|
|
14510
|
+
if (!isRecord2(body) || typeof body.url !== "string" || body.url.trim().length === 0) {
|
|
14511
|
+
return void 0;
|
|
14512
|
+
}
|
|
14513
|
+
return normalizeZoneBase(body.url);
|
|
14514
|
+
} finally {
|
|
14515
|
+
admission.finish();
|
|
14222
14516
|
}
|
|
14223
|
-
return normalizeZoneBase(body.url);
|
|
14224
14517
|
}
|
|
14225
14518
|
|
|
14226
14519
|
// src/http/HttpClient.ts
|
|
@@ -14337,8 +14630,9 @@ var HttpClient = class {
|
|
|
14337
14630
|
/**
|
|
14338
14631
|
* The LOCAL hourly-budget state (the sliding window this client counts):
|
|
14339
14632
|
* `{ perHour, used, remaining }` — `undefined` when `rateLimit.perHour`
|
|
14340
|
-
* is off.
|
|
14341
|
-
*
|
|
14633
|
+
* is off. This optional quota is PER CLIENT (issue #4); the separate
|
|
14634
|
+
* always-on origin ceiling is shared within the JavaScript realm. Neither
|
|
14635
|
+
* measures external integrations — the vendor-wide count is
|
|
14342
14636
|
* `thresholdInformation.get()`.
|
|
14343
14637
|
*/
|
|
14344
14638
|
hourlyBudget() {
|
|
@@ -14516,16 +14810,20 @@ var HttpClient = class {
|
|
|
14516
14810
|
* zone maintenance gate (issue #285), which admits one probe per poll
|
|
14517
14811
|
* interval while open. An already-aborted caller still gets the abort error.
|
|
14518
14812
|
*/
|
|
14519
|
-
gate(s) {
|
|
14813
|
+
gate(s, auditRefusal = true) {
|
|
14520
14814
|
const cooldown = this.cooldownEnabled && !s.opts.bypassCooldown ? cooldownRefusal(this.tenantKey, s.ctx) : void 0;
|
|
14521
|
-
const
|
|
14815
|
+
const owned = s.maintenanceProbe?.host === this.hostKey ? s.maintenanceProbe.gate : void 0;
|
|
14816
|
+
const verdict = cooldown ?? admitMaintenance(this.hostKey, s.ctx, owned);
|
|
14522
14817
|
if (verdict === "send") return;
|
|
14523
14818
|
if (!(verdict instanceof AutotaskError)) {
|
|
14819
|
+
if (s.maintenanceProbe !== void 0 && (s.maintenanceProbe.host !== this.hostKey || s.maintenanceProbe.gate !== verdict)) {
|
|
14820
|
+
releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
|
|
14821
|
+
}
|
|
14524
14822
|
s.maintenanceProbe = { host: this.hostKey, gate: verdict };
|
|
14525
14823
|
return;
|
|
14526
14824
|
}
|
|
14527
14825
|
if (s.callerSignal?.aborted) throw this.interrupted(s);
|
|
14528
|
-
this.auditNotSent(s, verdict.code);
|
|
14826
|
+
if (auditRefusal) this.auditNotSent(s, verdict.code);
|
|
14529
14827
|
throw verdict;
|
|
14530
14828
|
}
|
|
14531
14829
|
// ---- the attempt --------------------------------------------------------
|
|
@@ -14536,18 +14834,51 @@ var HttpClient = class {
|
|
|
14536
14834
|
*/
|
|
14537
14835
|
async sendOnce(s) {
|
|
14538
14836
|
const { method, opts, ctx } = s;
|
|
14539
|
-
|
|
14540
|
-
|
|
14541
|
-
|
|
14542
|
-
|
|
14543
|
-
|
|
14837
|
+
let release;
|
|
14838
|
+
for (; ; ) {
|
|
14839
|
+
try {
|
|
14840
|
+
await this.semaphore.acquire(s.signal);
|
|
14841
|
+
} catch (err) {
|
|
14842
|
+
if (s.signal.aborted) throw this.interrupted(s);
|
|
14843
|
+
throw err;
|
|
14844
|
+
}
|
|
14845
|
+
let releaseObject = () => void 0;
|
|
14846
|
+
let finishHourly = () => void 0;
|
|
14847
|
+
let released = false;
|
|
14848
|
+
const releaseCurrent = () => {
|
|
14849
|
+
if (released) return;
|
|
14850
|
+
released = true;
|
|
14851
|
+
finishHourly();
|
|
14852
|
+
releaseObject();
|
|
14853
|
+
this.semaphore.release();
|
|
14854
|
+
};
|
|
14855
|
+
try {
|
|
14856
|
+
releaseObject = await acquireObjectThread(s.url, this.auth.apiIntegrationCode, s.signal);
|
|
14857
|
+
if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
|
|
14858
|
+
this.gate(s, false);
|
|
14859
|
+
if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
|
|
14860
|
+
const admission = admitHourlyAttempt(s.url, this.hourly, Date.now());
|
|
14861
|
+
if (!admission.admitted) {
|
|
14862
|
+
releaseCurrent();
|
|
14863
|
+
await waitHourlyAdmission(admission, s.deadlineAt, s.signal, ctx);
|
|
14864
|
+
continue;
|
|
14865
|
+
}
|
|
14866
|
+
finishHourly = admission.finish;
|
|
14867
|
+
release = releaseCurrent;
|
|
14868
|
+
s.wireAttempts += 1;
|
|
14869
|
+
break;
|
|
14870
|
+
} catch (err) {
|
|
14871
|
+
releaseCurrent();
|
|
14872
|
+
if (s.signal.aborted) throw this.interrupted(s);
|
|
14873
|
+
if ((err instanceof RateLimitError || err instanceof MaintenanceError) && s.wireAttempts > 0) delete err.notSent;
|
|
14874
|
+
throw err;
|
|
14875
|
+
}
|
|
14544
14876
|
}
|
|
14545
|
-
await this.semaphore.acquire();
|
|
14546
14877
|
let res;
|
|
14547
14878
|
try {
|
|
14548
14879
|
res = await fetch(s.url, { method, headers: s.headers, body: s.bodyText, signal: s.signal, redirect: "manual" });
|
|
14549
14880
|
} catch (err) {
|
|
14550
|
-
|
|
14881
|
+
release();
|
|
14551
14882
|
if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
|
|
14552
14883
|
const delay = backoffDelay(s.attempt);
|
|
14553
14884
|
if (s.attempt < s.maxRetries && s.retriable5xx && await this.retryAfterDelay(s, delay, `network error on ${method} ${opts.path}`)) {
|
|
@@ -14571,7 +14902,7 @@ var HttpClient = class {
|
|
|
14571
14902
|
}
|
|
14572
14903
|
text = await readBodyText(res, this.maxResponseBytes, `${method} ${opts.path}`, { ...ctx, httpStatus: status });
|
|
14573
14904
|
} catch (err) {
|
|
14574
|
-
|
|
14905
|
+
release();
|
|
14575
14906
|
if (err instanceof AutotaskError) throw err;
|
|
14576
14907
|
if (s.signal.aborted || isAbortLike(err)) throw this.interrupted(s);
|
|
14577
14908
|
throw new AutotaskNetworkError(
|
|
@@ -14579,7 +14910,7 @@ var HttpClient = class {
|
|
|
14579
14910
|
ctx
|
|
14580
14911
|
);
|
|
14581
14912
|
}
|
|
14582
|
-
|
|
14913
|
+
release();
|
|
14583
14914
|
s.lastStatus = status;
|
|
14584
14915
|
return { retry: false, res, status, text };
|
|
14585
14916
|
}
|
|
@@ -14769,7 +15100,8 @@ var HttpClient = class {
|
|
|
14769
15100
|
status: s.lastStatus,
|
|
14770
15101
|
durationMs: Date.now() - s.started,
|
|
14771
15102
|
body: s.auditBody,
|
|
14772
|
-
errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR"
|
|
15103
|
+
errorCode: err instanceof AutotaskError ? err.code : "NETWORK_ERROR",
|
|
15104
|
+
...s.wireAttempts === 0 ? { notSent: true } : {}
|
|
14773
15105
|
});
|
|
14774
15106
|
if (this.fieldCache !== void 0 && err instanceof AutotaskError) {
|
|
14775
15107
|
const op = typeof opts.operation === "string" ? opts.operation : void 0;
|
|
@@ -14852,12 +15184,14 @@ var HttpClient = class {
|
|
|
14852
15184
|
lastStatus: void 0,
|
|
14853
15185
|
zoneRetry: void 0,
|
|
14854
15186
|
attempt: 0,
|
|
15187
|
+
wireAttempts: 0,
|
|
14855
15188
|
maintenanceProbe: void 0,
|
|
14856
15189
|
maintenancePage: false,
|
|
14857
15190
|
// Armed LAST in the literal: nothing after this can throw, and the single
|
|
14858
15191
|
// try/finally below clears it on every exit path (#190).
|
|
14859
15192
|
deadlineTimer: setTimeout(() => deadline.abort(), timeoutMs)
|
|
14860
15193
|
};
|
|
15194
|
+
const finishRequest = trackHourlyRequest();
|
|
14861
15195
|
try {
|
|
14862
15196
|
this.gate(s);
|
|
14863
15197
|
this.logger.debug?.(`[autotask] ${method} ${opts.path}`, correlationId);
|
|
@@ -14879,10 +15213,11 @@ var HttpClient = class {
|
|
|
14879
15213
|
this.onFailure(s, err);
|
|
14880
15214
|
throw err;
|
|
14881
15215
|
} finally {
|
|
14882
|
-
this.invalidateAfterWrite(opts);
|
|
15216
|
+
if (s.wireAttempts > 0) this.invalidateAfterWrite(opts);
|
|
14883
15217
|
}
|
|
14884
15218
|
} finally {
|
|
14885
15219
|
clearTimeout(s.deadlineTimer);
|
|
15220
|
+
finishRequest();
|
|
14886
15221
|
if (s.maintenanceProbe !== void 0) releaseMaintenanceProbe(s.maintenanceProbe.host, s.maintenanceProbe.gate);
|
|
14887
15222
|
}
|
|
14888
15223
|
}
|
|
@@ -15793,6 +16128,64 @@ function entityNameFromPath(resourcePath) {
|
|
|
15793
16128
|
return snake;
|
|
15794
16129
|
}
|
|
15795
16130
|
|
|
16131
|
+
// src/utils/bounded.ts
|
|
16132
|
+
async function runBounded(fn, items, opts) {
|
|
16133
|
+
const { concurrency, signal, settle } = opts;
|
|
16134
|
+
if (!Number.isInteger(concurrency) || concurrency <= 0) {
|
|
16135
|
+
throw new AutotaskConfigError("batch concurrency must be a positive integer");
|
|
16136
|
+
}
|
|
16137
|
+
const results = new Array(items.length);
|
|
16138
|
+
let next = 0;
|
|
16139
|
+
let failure;
|
|
16140
|
+
const fail = (error, index) => {
|
|
16141
|
+
if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
|
|
16142
|
+
};
|
|
16143
|
+
const worker = async () => {
|
|
16144
|
+
while (failure === void 0 && next < items.length) {
|
|
16145
|
+
if (signal?.aborted) {
|
|
16146
|
+
fail(signal.reason, -1);
|
|
16147
|
+
return;
|
|
16148
|
+
}
|
|
16149
|
+
const i = next++;
|
|
16150
|
+
try {
|
|
16151
|
+
const item = items[i];
|
|
16152
|
+
const value = await (signal === void 0 ? fn(item) : runWithSignal(signal, () => fn(item)));
|
|
16153
|
+
results[i] = settle ? { status: "fulfilled", value } : value;
|
|
16154
|
+
} catch (error) {
|
|
16155
|
+
if (settle) results[i] = { status: "rejected", reason: error };
|
|
16156
|
+
else fail(error, i);
|
|
16157
|
+
}
|
|
16158
|
+
}
|
|
16159
|
+
};
|
|
16160
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
|
|
16161
|
+
if (failure !== void 0) throw failure.error;
|
|
16162
|
+
return results;
|
|
16163
|
+
}
|
|
16164
|
+
async function mapReadTasks(http, items, fn) {
|
|
16165
|
+
const signal = ambientCallerSignal();
|
|
16166
|
+
const abort = () => new AutotaskAbortError("Read fan-out aborted by the caller");
|
|
16167
|
+
if (signal?.aborted) throw abort();
|
|
16168
|
+
try {
|
|
16169
|
+
const results = await runBounded(fn, items, { concurrency: http.maxConcurrent, orderedErrors: true, ...signal === void 0 ? {} : { signal } });
|
|
16170
|
+
if (signal?.aborted) throw abort();
|
|
16171
|
+
return results;
|
|
16172
|
+
} catch (error) {
|
|
16173
|
+
if (signal?.aborted && !(error instanceof AutotaskAbortError)) throw abort();
|
|
16174
|
+
throw error;
|
|
16175
|
+
}
|
|
16176
|
+
}
|
|
16177
|
+
function readTasks(http, tasks) {
|
|
16178
|
+
return mapReadTasks(http, tasks, (task) => task());
|
|
16179
|
+
}
|
|
16180
|
+
|
|
16181
|
+
// src/operations/nameSnapshot.ts
|
|
16182
|
+
function nameRecordSnapshot(cache, path, id, operation) {
|
|
16183
|
+
const body = cache?.get(path);
|
|
16184
|
+
if (body === void 0) return void 0;
|
|
16185
|
+
const entity = path.split("/").at(-2);
|
|
16186
|
+
return () => unwrapItem(body, id, operation, entity);
|
|
16187
|
+
}
|
|
16188
|
+
|
|
15796
16189
|
// src/operations/expandResourceNames.ts
|
|
15797
16190
|
var EXPAND_RESOURCE_NAMES_MAX_IDS = 500;
|
|
15798
16191
|
function composeName(record) {
|
|
@@ -15803,6 +16196,27 @@ function composeName(record) {
|
|
|
15803
16196
|
}
|
|
15804
16197
|
return parts.length > 0 ? parts.join(" ") : null;
|
|
15805
16198
|
}
|
|
16199
|
+
function resourceNameFailure(err) {
|
|
16200
|
+
if (err instanceof NotFoundError) return { name: null, blind: true };
|
|
16201
|
+
if (isAutotaskError(err) && err.code !== "ABORTED") {
|
|
16202
|
+
const error = { code: err.code, message: err.message };
|
|
16203
|
+
if (err.httpStatus !== void 0) error.httpStatus = err.httpStatus;
|
|
16204
|
+
return { name: null, blind: false, error };
|
|
16205
|
+
}
|
|
16206
|
+
throw err;
|
|
16207
|
+
}
|
|
16208
|
+
function resourceNameSnapshot(cache, id) {
|
|
16209
|
+
if (cache === void 0) return void 0;
|
|
16210
|
+
const path = `/V1.0/Resources/${id}`;
|
|
16211
|
+
if (cache.get(contextAbsentKey(path)) !== void 0) return { name: null, blind: true };
|
|
16212
|
+
const record = nameRecordSnapshot(cache, path, id, "resources.get");
|
|
16213
|
+
if (record === void 0) return void 0;
|
|
16214
|
+
try {
|
|
16215
|
+
return { name: composeName(record()), blind: false };
|
|
16216
|
+
} catch (err) {
|
|
16217
|
+
return resourceNameFailure(err);
|
|
16218
|
+
}
|
|
16219
|
+
}
|
|
15806
16220
|
async function expandResourceNames(client, ids2, opts = {}) {
|
|
15807
16221
|
if (opts.maxIds !== void 0 && (!Number.isInteger(opts.maxIds) || opts.maxIds < 1)) {
|
|
15808
16222
|
throw new AutotaskConfigError(`expandResourceNames: maxIds must be an integer >= 1 (got ${String(opts.maxIds)})`);
|
|
@@ -15855,13 +16269,21 @@ async function expandResourceNames(client, ids2, opts = {}) {
|
|
|
15855
16269
|
const holder = client.resources;
|
|
15856
16270
|
const cache = client.http.readCache;
|
|
15857
16271
|
const fresh = opts.fresh === true;
|
|
16272
|
+
const warm = /* @__PURE__ */ new Map();
|
|
16273
|
+
if (!fresh) {
|
|
16274
|
+
for (const id of unique) {
|
|
16275
|
+
const snapshot = resourceNameSnapshot(cache, id);
|
|
16276
|
+
if (snapshot !== void 0) warm.set(String(id), snapshot);
|
|
16277
|
+
}
|
|
16278
|
+
}
|
|
15858
16279
|
const byId2 = /* @__PURE__ */ new Map();
|
|
15859
|
-
|
|
16280
|
+
await mapReadTasks(client.http, unique, async (id) => {
|
|
15860
16281
|
const k = String(id);
|
|
15861
16282
|
const absentKey = contextAbsentKey(`/V1.0/Resources/${k}`);
|
|
15862
|
-
|
|
15863
|
-
|
|
15864
|
-
|
|
16283
|
+
const snapshot = warm.get(k);
|
|
16284
|
+
if (snapshot !== void 0) {
|
|
16285
|
+
byId2.set(k, snapshot);
|
|
16286
|
+
return;
|
|
15865
16287
|
}
|
|
15866
16288
|
const epoch = cache?.epoch ?? 0;
|
|
15867
16289
|
try {
|
|
@@ -15872,17 +16294,11 @@ async function expandResourceNames(client, ids2, opts = {}) {
|
|
|
15872
16294
|
if (err instanceof NotFoundError) {
|
|
15873
16295
|
cache?.set(absentKey, CONTEXT_ABSENT_MARKER, epoch);
|
|
15874
16296
|
byId2.set(k, { name: null, blind: true });
|
|
15875
|
-
|
|
15876
|
-
}
|
|
15877
|
-
if (isAutotaskError(err) && err.code !== "ABORTED") {
|
|
15878
|
-
const e = { code: err.code, message: err.message };
|
|
15879
|
-
if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
|
|
15880
|
-
byId2.set(k, { name: null, blind: false, error: e });
|
|
15881
|
-
continue;
|
|
16297
|
+
return;
|
|
15882
16298
|
}
|
|
15883
|
-
|
|
16299
|
+
byId2.set(k, resourceNameFailure(err));
|
|
15884
16300
|
}
|
|
15885
|
-
}
|
|
16301
|
+
});
|
|
15886
16302
|
const results = [];
|
|
15887
16303
|
for (const id of canonical) {
|
|
15888
16304
|
const out = byId2.get(String(id));
|
|
@@ -16047,6 +16463,13 @@ var FK_TABLE_PATH = {
|
|
|
16047
16463
|
company: "/V1.0/Companies",
|
|
16048
16464
|
ticket: "/V1.0/Tickets"
|
|
16049
16465
|
};
|
|
16466
|
+
var FK_GET_OPERATION = {
|
|
16467
|
+
role: "roles.get",
|
|
16468
|
+
billingCode: "billing_codes.get",
|
|
16469
|
+
contract: "contracts.get",
|
|
16470
|
+
company: "companies.get",
|
|
16471
|
+
ticket: "tickets.get"
|
|
16472
|
+
};
|
|
16050
16473
|
var FK_NAME_FIELD = {
|
|
16051
16474
|
role: "name",
|
|
16052
16475
|
billingCode: "name",
|
|
@@ -16078,13 +16501,15 @@ async function resolveCompositeNames(http, plan, opts = {}) {
|
|
|
16078
16501
|
const readCache = http.readCache;
|
|
16079
16502
|
const section = { truncated: false, rows: {}, reasons: {} };
|
|
16080
16503
|
let remaining = budget;
|
|
16504
|
+
const tasks = [];
|
|
16081
16505
|
let contractLobPointer;
|
|
16082
16506
|
let contractLobUnread;
|
|
16083
16507
|
const coldResource = [];
|
|
16508
|
+
const warmResources = /* @__PURE__ */ new Map();
|
|
16084
16509
|
for (const id of plan.resourceIds) {
|
|
16085
|
-
const
|
|
16086
|
-
if (
|
|
16087
|
-
|
|
16510
|
+
const snapshot = resourceNameSnapshot(readCache, id);
|
|
16511
|
+
if (snapshot === void 0) coldResource.push(id);
|
|
16512
|
+
else warmResources.set(String(id), snapshot);
|
|
16088
16513
|
}
|
|
16089
16514
|
const withinBudget = coldResource.slice(0, remaining);
|
|
16090
16515
|
const overBudgetResource = coldResource.slice(remaining);
|
|
@@ -16104,12 +16529,21 @@ async function resolveCompositeNames(http, plan, opts = {}) {
|
|
|
16104
16529
|
}
|
|
16105
16530
|
pass = pass.slice(0, 500);
|
|
16106
16531
|
}
|
|
16107
|
-
|
|
16108
|
-
|
|
16109
|
-
const
|
|
16110
|
-
if (
|
|
16111
|
-
|
|
16112
|
-
|
|
16532
|
+
tasks.push(async () => {
|
|
16533
|
+
const cold = pass.filter((id) => !warmResources.has(String(id)));
|
|
16534
|
+
const outcomes = new Map(warmResources);
|
|
16535
|
+
if (cold.length > 0) {
|
|
16536
|
+
for (const row of (await expandResourceNames(client, cold)).results) outcomes.set(String(row.id), row);
|
|
16537
|
+
}
|
|
16538
|
+
return () => {
|
|
16539
|
+
for (const id of pass) {
|
|
16540
|
+
const r = outcomes.get(String(id));
|
|
16541
|
+
const row = { name: r.name, blind: r.blind };
|
|
16542
|
+
if (r.error !== void 0) row.error = faultRow(r.error);
|
|
16543
|
+
section.rows[`resource:${id}`] = row;
|
|
16544
|
+
}
|
|
16545
|
+
};
|
|
16546
|
+
});
|
|
16113
16547
|
}
|
|
16114
16548
|
const holders = {
|
|
16115
16549
|
role: client.roles,
|
|
@@ -16120,10 +16554,13 @@ async function resolveCompositeNames(http, plan, opts = {}) {
|
|
|
16120
16554
|
};
|
|
16121
16555
|
for (const fk2 of plan.recordFks) {
|
|
16122
16556
|
const key = `${fk2.table}:${fk2.id}`;
|
|
16123
|
-
const
|
|
16557
|
+
const snapshot = nameRecordSnapshot(readCache, `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`, fk2.id, FK_GET_OPERATION[fk2.table]);
|
|
16558
|
+
const cold = snapshot === void 0;
|
|
16124
16559
|
if (cold) {
|
|
16125
16560
|
if (remaining < 1) {
|
|
16126
|
-
|
|
16561
|
+
tasks.push(async () => () => {
|
|
16562
|
+
section.rows[key] = { name: null, blind: false };
|
|
16563
|
+
});
|
|
16127
16564
|
section.truncated = true;
|
|
16128
16565
|
if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
|
|
16129
16566
|
contractLobUnread = "capped";
|
|
@@ -16132,41 +16569,51 @@ async function resolveCompositeNames(http, plan, opts = {}) {
|
|
|
16132
16569
|
}
|
|
16133
16570
|
remaining -= 1;
|
|
16134
16571
|
}
|
|
16135
|
-
|
|
16136
|
-
|
|
16137
|
-
|
|
16138
|
-
|
|
16139
|
-
|
|
16140
|
-
|
|
16141
|
-
|
|
16142
|
-
|
|
16143
|
-
|
|
16144
|
-
|
|
16145
|
-
|
|
16146
|
-
if (
|
|
16147
|
-
|
|
16572
|
+
tasks.push(async () => {
|
|
16573
|
+
let row;
|
|
16574
|
+
try {
|
|
16575
|
+
const record = snapshot !== void 0 ? snapshot() : await holders[fk2.table].get(fk2.id);
|
|
16576
|
+
if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
|
|
16577
|
+
contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
|
|
16578
|
+
}
|
|
16579
|
+
row = { name: fkName(record, fk2.table), blind: false };
|
|
16580
|
+
} catch (err) {
|
|
16581
|
+
if (err instanceof NotFoundError) {
|
|
16582
|
+
row = { name: null, blind: true };
|
|
16583
|
+
} else if (isAutotaskError(err) && err.code !== "ABORTED") {
|
|
16584
|
+
row = { name: null, blind: false, error: faultRow(err) };
|
|
16585
|
+
if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
|
|
16586
|
+
contractLobUnread = "unresolved";
|
|
16587
|
+
}
|
|
16588
|
+
} else {
|
|
16589
|
+
throw err;
|
|
16148
16590
|
}
|
|
16149
|
-
} else {
|
|
16150
|
-
throw err;
|
|
16151
16591
|
}
|
|
16152
|
-
|
|
16592
|
+
return () => {
|
|
16593
|
+
section.rows[key] = row;
|
|
16594
|
+
};
|
|
16595
|
+
});
|
|
16153
16596
|
}
|
|
16154
16597
|
const picklists = {};
|
|
16155
16598
|
if (plan.labelFields.length > 0) {
|
|
16156
|
-
|
|
16157
|
-
|
|
16158
|
-
|
|
16159
|
-
|
|
16160
|
-
|
|
16161
|
-
|
|
16162
|
-
const
|
|
16163
|
-
|
|
16599
|
+
tasks.push(async () => {
|
|
16600
|
+
try {
|
|
16601
|
+
const labelResource = plan.labelResource ?? "tickets";
|
|
16602
|
+
const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
|
|
16603
|
+
const row = catalog.rows.find((r) => r.resource === labelResource);
|
|
16604
|
+
if (row !== void 0 && row.error === null && row.fields !== void 0) {
|
|
16605
|
+
for (const f of plan.labelFields) {
|
|
16606
|
+
const frow = row.fields.find((x) => x.name === f);
|
|
16607
|
+
picklists[f] = frow?.picklistValues;
|
|
16608
|
+
}
|
|
16164
16609
|
}
|
|
16610
|
+
} catch (err) {
|
|
16611
|
+
if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
|
|
16165
16612
|
}
|
|
16166
|
-
|
|
16167
|
-
|
|
16168
|
-
}
|
|
16613
|
+
return () => void 0;
|
|
16614
|
+
});
|
|
16169
16615
|
}
|
|
16616
|
+
for (const merge of await readTasks(http, tasks)) merge();
|
|
16170
16617
|
let lineOfBusiness2 = null;
|
|
16171
16618
|
const lobId = plan.lineOfBusinessId ?? contractLobPointer;
|
|
16172
16619
|
if (lobId !== void 0) {
|
|
@@ -16241,6 +16688,61 @@ var BOUNDED_QUERY_MAX_LIMIT = 2500;
|
|
|
16241
16688
|
var LATEST_MAX_COUNT_PROBES = 64;
|
|
16242
16689
|
var MARKER_RECOVERY_LIMIT = 5;
|
|
16243
16690
|
|
|
16691
|
+
// src/read-cache.ts
|
|
16692
|
+
var READ_FAILURE_OBSERVER = /* @__PURE__ */ Symbol("record read failure observer");
|
|
16693
|
+
function observeRecordReadFailures(http, observer) {
|
|
16694
|
+
Object.defineProperty(http, READ_FAILURE_OBSERVER, { value: observer });
|
|
16695
|
+
}
|
|
16696
|
+
function subscriberError(error, operation) {
|
|
16697
|
+
const copies = /* @__PURE__ */ new Map();
|
|
16698
|
+
const copyValue = (value) => {
|
|
16699
|
+
if (value === null || typeof value !== "object") return value;
|
|
16700
|
+
if (!(value instanceof Error) && !isRecord(value) && !Array.isArray(value)) return value;
|
|
16701
|
+
const prior = copies.get(value);
|
|
16702
|
+
if (prior !== void 0) return prior;
|
|
16703
|
+
const copy = value instanceof Error ? Object.setPrototypeOf(new Error(value.message), Object.getPrototypeOf(value)) : Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
|
|
16704
|
+
copies.set(value, copy);
|
|
16705
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
16706
|
+
if (value === error) descriptors.operation = { ...descriptors.operation, value: operation };
|
|
16707
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
16708
|
+
const descriptor2 = descriptors[key];
|
|
16709
|
+
if ("value" in descriptor2) descriptor2.value = copyValue(descriptor2.value);
|
|
16710
|
+
}
|
|
16711
|
+
Object.defineProperties(copy, descriptors);
|
|
16712
|
+
if (value instanceof Error && descriptors.stack?.set !== void 0) descriptors.stack.set.call(copy, value.stack);
|
|
16713
|
+
return copy;
|
|
16714
|
+
};
|
|
16715
|
+
return copyValue(error);
|
|
16716
|
+
}
|
|
16717
|
+
function cachedRecordGet(http, path, operation, fresh = false) {
|
|
16718
|
+
const cache = http.readCache;
|
|
16719
|
+
if (cache === void 0) return http.request({ method: "GET", path, operation });
|
|
16720
|
+
let ownsLoader = false;
|
|
16721
|
+
const loader = (signal) => {
|
|
16722
|
+
ownsLoader = true;
|
|
16723
|
+
return http.request({ method: "GET", path, operation, signal });
|
|
16724
|
+
};
|
|
16725
|
+
const options = {
|
|
16726
|
+
signal: ambientCallerSignal(),
|
|
16727
|
+
fresh,
|
|
16728
|
+
abortError: () => new AutotaskAbortError(`Request aborted: GET ${path}`, {
|
|
16729
|
+
operation,
|
|
16730
|
+
suggestedAction: "The caller aborted; re-issue the call if still needed."
|
|
16731
|
+
})
|
|
16732
|
+
};
|
|
16733
|
+
return cache.load(path, loader, options).catch((error) => {
|
|
16734
|
+
if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
|
|
16735
|
+
if (options.signal?.aborted) throw options.abortError();
|
|
16736
|
+
const warm = cache.get(path);
|
|
16737
|
+
return warm !== void 0 ? warm : cache.load(path, loader, { ...options, fresh: true });
|
|
16738
|
+
}).catch((error) => {
|
|
16739
|
+
if (!(error instanceof AutotaskError)) throw error;
|
|
16740
|
+
const failure = subscriberError(error, operation);
|
|
16741
|
+
http[READ_FAILURE_OBSERVER]?.(failure);
|
|
16742
|
+
throw failure;
|
|
16743
|
+
});
|
|
16744
|
+
}
|
|
16745
|
+
|
|
16244
16746
|
// src/field-sets.ts
|
|
16245
16747
|
var MODEL_FIELD_SETS = {
|
|
16246
16748
|
"appointments": ["id", "createDateTime", "creatorResourceID", "description", "endDateTime", "resourceID", "startDateTime", "title", "updateDateTime"],
|
|
@@ -16653,14 +17155,14 @@ async function labelRows(client, resourceKey, rows) {
|
|
|
16653
17155
|
return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
|
|
16654
17156
|
}
|
|
16655
17157
|
async function labelFetchResults(client, result) {
|
|
16656
|
-
const
|
|
17158
|
+
const byResource2 = /* @__PURE__ */ new Map();
|
|
16657
17159
|
result.results.forEach((r, i) => {
|
|
16658
|
-
if (r.found && r.value !== null)
|
|
17160
|
+
if (r.found && r.value !== null) byResource2.set(r.resource, [...byResource2.get(r.resource) ?? [], i]);
|
|
16659
17161
|
});
|
|
16660
17162
|
const results = [...result.results];
|
|
16661
17163
|
const notes = [];
|
|
16662
17164
|
const reasons = {};
|
|
16663
|
-
for (const [resource, indices] of
|
|
17165
|
+
for (const [resource, indices] of byResource2) {
|
|
16664
17166
|
const labelled = await labelRows(client, resource, indices.map((i) => results[i].value));
|
|
16665
17167
|
indices.forEach((idx, j) => {
|
|
16666
17168
|
results[idx] = { ...results[idx], value: labelled.rows[j] };
|
|
@@ -16730,7 +17232,7 @@ var QueryBase = class {
|
|
|
16730
17232
|
// Query walk (wired to the G3 walker; cursor-follow per the pinned wire)
|
|
16731
17233
|
// ------------------------------------------------------------------
|
|
16732
17234
|
/** One page fetch: page 1 POSTs the QueryModel body; later pages POST the same body (`buildQueryBody`) to the absolute cursor (issue #118). */
|
|
16733
|
-
async fetchPage(params, page, pageSize,
|
|
17235
|
+
async fetchPage(params, page, pageSize, state2) {
|
|
16734
17236
|
if (params.includeFields !== void 0) {
|
|
16735
17237
|
params = { ...params, includeFields: params.includeFields.map((field) => normalizeOwnField(this.config.key, field)) };
|
|
16736
17238
|
}
|
|
@@ -16738,9 +17240,9 @@ var QueryBase = class {
|
|
|
16738
17240
|
if (page === 1) {
|
|
16739
17241
|
const req = buildQueryRequest(this.http.baseUrl, this.resourcePath, { ...params, maxRecords: pageSize });
|
|
16740
17242
|
const body2 = await this.http.request({ ...req, operation });
|
|
16741
|
-
return this.readPage(body2, page, pageSize,
|
|
17243
|
+
return this.readPage(body2, page, pageSize, state2);
|
|
16742
17244
|
}
|
|
16743
|
-
const cursor =
|
|
17245
|
+
const cursor = state2.cursor;
|
|
16744
17246
|
if (cursor === null) {
|
|
16745
17247
|
throw new AutotaskError(`No pagination cursor available for page ${page} of ${operation}`, {
|
|
16746
17248
|
code: "INVALID_RESPONSE",
|
|
@@ -16756,13 +17258,13 @@ var QueryBase = class {
|
|
|
16756
17258
|
operation,
|
|
16757
17259
|
idempotent: true
|
|
16758
17260
|
});
|
|
16759
|
-
return this.readPage(res, page, pageSize,
|
|
17261
|
+
return this.readPage(res, page, pageSize, state2);
|
|
16760
17262
|
}
|
|
16761
17263
|
/** @internal */
|
|
16762
|
-
readPage(body, page, pageSize,
|
|
17264
|
+
readPage(body, page, pageSize, state2) {
|
|
16763
17265
|
const { items, pageDetails } = unwrapItems(body, `${this.config.key}.query`);
|
|
16764
|
-
|
|
16765
|
-
const hasMore =
|
|
17266
|
+
state2.cursor = pageDetails.nextPageUrl ?? null;
|
|
17267
|
+
const hasMore = state2.cursor !== null;
|
|
16766
17268
|
return {
|
|
16767
17269
|
items,
|
|
16768
17270
|
page,
|
|
@@ -16776,9 +17278,9 @@ var QueryBase = class {
|
|
|
16776
17278
|
}
|
|
16777
17279
|
/** Build the per-walk fetcher (closure keeps cursor state private to this walk). */
|
|
16778
17280
|
pageFetcher(params) {
|
|
16779
|
-
const
|
|
17281
|
+
const state2 = { cursor: null };
|
|
16780
17282
|
const p = params ?? {};
|
|
16781
|
-
return (page, pageSize) => this.fetchPage(p, page, pageSize,
|
|
17283
|
+
return (page, pageSize) => this.fetchPage(p, page, pageSize, state2);
|
|
16782
17284
|
}
|
|
16783
17285
|
/** @internal */
|
|
16784
17286
|
walkPageSize(params) {
|
|
@@ -16943,7 +17445,7 @@ var QueryBase = class {
|
|
|
16943
17445
|
* state).
|
|
16944
17446
|
* @internal */
|
|
16945
17447
|
async walkBounded(p, limit, pageSizeBase, labelPages = false) {
|
|
16946
|
-
const
|
|
17448
|
+
const state2 = { cursor: null };
|
|
16947
17449
|
const items = [];
|
|
16948
17450
|
let pages2 = 0;
|
|
16949
17451
|
let sliced = 0;
|
|
@@ -16956,7 +17458,7 @@ var QueryBase = class {
|
|
|
16956
17458
|
guard = true;
|
|
16957
17459
|
break;
|
|
16958
17460
|
}
|
|
16959
|
-
const page = await this.fetchPage(p, pages2 + 1, pageSize,
|
|
17461
|
+
const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
|
|
16960
17462
|
pages2 += 1;
|
|
16961
17463
|
if (labelPages && this.http.client !== void 0) {
|
|
16962
17464
|
const labelled = await labelRows(this.http.client, this.config.key, page.items);
|
|
@@ -16977,7 +17479,7 @@ var QueryBase = class {
|
|
|
16977
17479
|
note: [...nameNotes].join("; "),
|
|
16978
17480
|
...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
|
|
16979
17481
|
};
|
|
16980
|
-
return { items, pages: pages2, guard, sliced, cursor:
|
|
17482
|
+
return { items, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
|
|
16981
17483
|
}
|
|
16982
17484
|
/** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
|
|
16983
17485
|
* was met with a live next cursor (or a sliced final page): rows exist
|
|
@@ -17250,17 +17752,11 @@ var MetaBase = class extends QueryBase {
|
|
|
17250
17752
|
* and the composite ROOT read of a hot resource (issue #36 — the
|
|
17251
17753
|
* ticket-composite root) must see the live record, never a snapshot.
|
|
17252
17754
|
* The entry's TTL follows the path (`readTtlFor`: reference tables 1 h).
|
|
17755
|
+
* Equivalent non-fresh misses share one request through the cache loader;
|
|
17756
|
+
* the ambient signal belongs to this subscriber, never to the shared wire.
|
|
17253
17757
|
* @internal */
|
|
17254
17758
|
async cachedGet(path, operation, fresh = false) {
|
|
17255
|
-
|
|
17256
|
-
if (cache !== void 0 && !fresh) {
|
|
17257
|
-
const hit = cache.get(path);
|
|
17258
|
-
if (hit !== void 0) return hit;
|
|
17259
|
-
}
|
|
17260
|
-
const epoch = cache?.epoch;
|
|
17261
|
-
const res = await this.http.request({ method: "GET", path, operation });
|
|
17262
|
-
cache?.set(path, res, epoch);
|
|
17263
|
-
return res;
|
|
17759
|
+
return cachedRecordGet(this.http, path, operation, fresh);
|
|
17264
17760
|
}
|
|
17265
17761
|
/**
|
|
17266
17762
|
* Entity-metadata read through the opt-in field cache (issue #31; off by
|
|
@@ -17609,8 +18105,8 @@ var MetaBase = class extends QueryBase {
|
|
|
17609
18105
|
);
|
|
17610
18106
|
}
|
|
17611
18107
|
const leaf = fields.map((field) => ({ field, op: "eq", value }));
|
|
17612
|
-
const
|
|
17613
|
-
const items = await this.queryPage1([
|
|
18108
|
+
const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
|
|
18109
|
+
const items = await this.queryPage1([root2], 2);
|
|
17614
18110
|
if (items.length === 1) {
|
|
17615
18111
|
return { value: items[0], resolutionCost: "server-filter", scanned: 0, scanTruncated: false };
|
|
17616
18112
|
}
|
|
@@ -17716,13 +18212,13 @@ var MetaBase = class extends QueryBase {
|
|
|
17716
18212
|
async scanForExactMatch(value, fields) {
|
|
17717
18213
|
const caps = this.resolutionCaps;
|
|
17718
18214
|
const pageSize = Math.max(1, Math.floor(caps.maxScanRecords / caps.maxScanPages));
|
|
17719
|
-
const
|
|
18215
|
+
const state2 = { cursor: null };
|
|
17720
18216
|
let scanned = 0;
|
|
17721
18217
|
let pages2 = 0;
|
|
17722
18218
|
let found = null;
|
|
17723
18219
|
let exhausted = false;
|
|
17724
18220
|
for (; ; ) {
|
|
17725
|
-
const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize,
|
|
18221
|
+
const page = await this.fetchPage({ maxRecords: pageSize }, pages2 + 1, pageSize, state2);
|
|
17726
18222
|
pages2 += 1;
|
|
17727
18223
|
for (const item of page.items) {
|
|
17728
18224
|
scanned += 1;
|
|
@@ -17777,7 +18273,7 @@ var MetaBase = class extends QueryBase {
|
|
|
17777
18273
|
}
|
|
17778
18274
|
const limit = opts.limit === void 0 ? 25 : clampPageSize(opts.limit);
|
|
17779
18275
|
const leaf = fields.map((field) => ({ field, op: "contains", value: text }));
|
|
17780
|
-
const
|
|
18276
|
+
const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
|
|
17781
18277
|
for (const key of Object.keys(opts)) {
|
|
17782
18278
|
if (key !== "limit" && key !== "companyID" && key !== "includeFields") {
|
|
17783
18279
|
throw new AutotaskConfigError(`search: unknown opts key "${key}" \u2014 the bag is closed: limit, companyID, includeFields`);
|
|
@@ -17791,7 +18287,7 @@ var MetaBase = class extends QueryBase {
|
|
|
17791
18287
|
}
|
|
17792
18288
|
const companyID = opts.companyID === void 0 ? void 0 : Number(opts.companyID);
|
|
17793
18289
|
const includeFields = opts.includeFields === void 0 ? void 0 : opts.includeFields.includes("id") ? opts.includeFields : ["id", ...opts.includeFields];
|
|
17794
|
-
const conditions = companyID === void 0 ? [
|
|
18290
|
+
const conditions = companyID === void 0 ? [root2] : [{ field: "companyID", op: "eq", value: companyID }, root2];
|
|
17795
18291
|
const rows = await this.queryEntity(`${this.resourcePath}/query`, conditions, {
|
|
17796
18292
|
maxRecords: limit,
|
|
17797
18293
|
...includeFields !== void 0 ? { includeFields } : {}
|
|
@@ -20064,20 +20560,20 @@ var GenericResource = class extends BaseResource {
|
|
|
20064
20560
|
this.requireHelper("getContext");
|
|
20065
20561
|
const cfg = this.config;
|
|
20066
20562
|
const rootField = cfg.contextRootField ?? this.config.key;
|
|
20067
|
-
const
|
|
20068
|
-
const result = { [rootField]:
|
|
20069
|
-
|
|
20070
|
-
|
|
20071
|
-
|
|
20563
|
+
const root2 = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
|
|
20564
|
+
const result = { [rootField]: root2 };
|
|
20565
|
+
const parts = cfg.contextParts ?? [];
|
|
20566
|
+
const values = await mapReadTasks(this.http, parts, ([, idField, targetPath]) => this.contextFetch(targetPath, root2[idField]));
|
|
20567
|
+
for (const [i, [name]] of parts.entries()) result[name] = values[i];
|
|
20072
20568
|
if (opts.names === true) {
|
|
20073
20569
|
const builder = createNamePlan();
|
|
20074
20570
|
for (const sib of cfg.nameSiblings ?? []) {
|
|
20075
|
-
const fk2 =
|
|
20571
|
+
const fk2 = root2[sib.field];
|
|
20076
20572
|
if (sib.kind === "resource") builder.addResource(fk2);
|
|
20077
20573
|
else builder.addFk(sib.kind, fk2);
|
|
20078
20574
|
}
|
|
20079
20575
|
const names = await resolveCompositeNames(this.http, builder.plan(), { maxNameReads: opts.maxNameReads });
|
|
20080
|
-
const row = { ...
|
|
20576
|
+
const row = { ...root2 };
|
|
20081
20577
|
for (const sib of cfg.nameSiblings ?? []) {
|
|
20082
20578
|
addNameSibling(row, sib.field, (v) => sib.kind === "resource" ? names.resourceName(v) : names.recordName(sib.kind, v));
|
|
20083
20579
|
}
|
|
@@ -20246,9 +20742,9 @@ async function searchFuzzy(resource, query, opts = {}) {
|
|
|
20246
20742
|
if (!opts.includeInactive) filter.push({ field: "isActive", op: "eq", value: true });
|
|
20247
20743
|
const index = companyIndex(resource.http);
|
|
20248
20744
|
index?.ensure();
|
|
20249
|
-
const
|
|
20745
|
+
const state2 = index?.state() ?? { state: "off" };
|
|
20250
20746
|
const revision = index?.revision();
|
|
20251
|
-
const indexed =
|
|
20747
|
+
const indexed = state2.state === "warm" ? index.candidates([...terms, terms.join("")]) : [];
|
|
20252
20748
|
const res = await resource.http.request({
|
|
20253
20749
|
method: "POST",
|
|
20254
20750
|
idempotent: true,
|
|
@@ -20267,7 +20763,7 @@ async function searchFuzzy(resource, query, opts = {}) {
|
|
|
20267
20763
|
const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
|
|
20268
20764
|
for (let i = 0; i < items.length; i++) items[i].record = records[i];
|
|
20269
20765
|
}
|
|
20270
|
-
return { items, tier:
|
|
20766
|
+
return { items, tier: state2.state === "warm" && validIndex ? "index+live" : "live", truncated: live.length >= 500 || ranked.length > limit, pieces, index: validIndex ? state2 : index.state() };
|
|
20271
20767
|
}
|
|
20272
20768
|
|
|
20273
20769
|
// src/operations/invoke/fieldNames.ts
|
|
@@ -20441,13 +20937,17 @@ async function readFields(http, fresh) {
|
|
|
20441
20937
|
const hit = cache.get(key);
|
|
20442
20938
|
if (hit !== void 0) return hit;
|
|
20443
20939
|
}
|
|
20444
|
-
const
|
|
20445
|
-
const
|
|
20446
|
-
|
|
20447
|
-
|
|
20448
|
-
|
|
20449
|
-
|
|
20450
|
-
|
|
20940
|
+
const epoch = cache?.epoch;
|
|
20941
|
+
const work = (async () => {
|
|
20942
|
+
const res = await http.request({ method: "GET", path: "/V1.0/Tickets/entityInformation/fields", operation: OP, maxRetries: 0 });
|
|
20943
|
+
const fields = res?.fields;
|
|
20944
|
+
if (!Array.isArray(fields)) {
|
|
20945
|
+
throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
|
|
20946
|
+
}
|
|
20947
|
+
if (fields.length > 0) cache?.set(key, fields, epoch);
|
|
20948
|
+
return fields;
|
|
20949
|
+
})();
|
|
20950
|
+
return cache !== void 0 && !fresh ? cache.track(key, work) : work;
|
|
20451
20951
|
}
|
|
20452
20952
|
function assumed(allowAssumed, operation) {
|
|
20453
20953
|
if (!allowAssumed) {
|
|
@@ -20669,14 +21169,16 @@ async function fullProfile(resource, id, opts = {}) {
|
|
|
20669
21169
|
const proj = validateProjection(opts.fields);
|
|
20670
21170
|
const companyID = parseIdentifier(id, "id");
|
|
20671
21171
|
const company = await resource.get(companyID);
|
|
20672
|
-
const locations = await
|
|
20673
|
-
|
|
20674
|
-
|
|
20675
|
-
|
|
20676
|
-
|
|
20677
|
-
|
|
20678
|
-
|
|
20679
|
-
|
|
21172
|
+
const [locations, contacts, notes, projects, openTickets] = await readTasks(http, [
|
|
21173
|
+
() => scopedCompanyQuery(http, "/V1.0/CompanyLocations/query", companyID, locLimit, proj.locations),
|
|
21174
|
+
() => scopedCompanyQuery(http, "/V1.0/Contacts/query", companyID, contactLimit, proj.contacts),
|
|
21175
|
+
() => scopedCompanyQuery(http, "/V1.0/CompanyNotes/query", companyID, noteLimit, proj.notes),
|
|
21176
|
+
() => scopedCompanyQuery(http, "/V1.0/Projects/query", companyID, projectLimit, proj.projects),
|
|
21177
|
+
() => readOpenTickets(http, companyID, ticketLimit, proj.openTickets, {
|
|
21178
|
+
...opts.excludeStatusIds === void 0 ? {} : { excludeStatusIds: opts.excludeStatusIds },
|
|
21179
|
+
...opts.allowAssumed === void 0 ? {} : { allowAssumed: opts.allowAssumed }
|
|
21180
|
+
})
|
|
21181
|
+
]);
|
|
20680
21182
|
const result = {
|
|
20681
21183
|
company,
|
|
20682
21184
|
locations: { items: locations, capped: locations.length >= locLimit },
|
|
@@ -20936,11 +21438,7 @@ async function fetchCompanies(http, ids2, limit) {
|
|
|
20936
21438
|
const out = [];
|
|
20937
21439
|
for (const id of ids2.slice(0, limit)) {
|
|
20938
21440
|
try {
|
|
20939
|
-
const res = await http.
|
|
20940
|
-
method: "GET",
|
|
20941
|
-
path: `/V1.0/Companies/${id}`,
|
|
20942
|
-
operation: "companies.searchByDomain"
|
|
20943
|
-
});
|
|
21441
|
+
const res = await cachedRecordGet(http, `/V1.0/Companies/${id}`, "companies.searchByDomain");
|
|
20944
21442
|
const body = res;
|
|
20945
21443
|
const item = body && "item" in body ? body.item : null;
|
|
20946
21444
|
if (item) out.push(item);
|
|
@@ -21376,9 +21874,11 @@ var CompaniesResource = class extends GenericResource {
|
|
|
21376
21874
|
* fetch; no sub-lists; absent/dangling references come back null). */
|
|
21377
21875
|
async getContext(id) {
|
|
21378
21876
|
const company = await this.fetchRecordRaw("/V1.0/Companies", id);
|
|
21379
|
-
const
|
|
21380
|
-
const ownerResource = await this.
|
|
21381
|
-
|
|
21877
|
+
const root2 = company;
|
|
21878
|
+
const [ownerResource, parentCompany] = await readTasks(this.http, [
|
|
21879
|
+
() => this.contextFetch("/V1.0/Resources", root2["ownerResourceID"]),
|
|
21880
|
+
() => this.contextFetch("/V1.0/Companies", root2["parentCompanyID"])
|
|
21881
|
+
]);
|
|
21382
21882
|
return { company, ownerResource, parentCompany };
|
|
21383
21883
|
}
|
|
21384
21884
|
/** Node-parity special op (hand-written in src/resources/special/companies/search.ts). */
|
|
@@ -22458,7 +22958,7 @@ async function fetchByIds(client, items, opts = {}) {
|
|
|
22458
22958
|
}
|
|
22459
22959
|
groups.set(item.resource, g);
|
|
22460
22960
|
}
|
|
22461
|
-
const
|
|
22961
|
+
const byKey2 = /* @__PURE__ */ new Map();
|
|
22462
22962
|
for (const [key, group] of groups) {
|
|
22463
22963
|
const holder = client[camelKey(key)];
|
|
22464
22964
|
if (holder === void 0) {
|
|
@@ -22487,28 +22987,28 @@ async function fetchByIds(client, items, opts = {}) {
|
|
|
22487
22987
|
if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
|
|
22488
22988
|
for (const u of chunk) {
|
|
22489
22989
|
const q = kOf(u);
|
|
22490
|
-
if (!
|
|
22990
|
+
if (!byKey2.has(q)) byKey2.set(q, { found: false, value: null, error: e });
|
|
22491
22991
|
}
|
|
22492
22992
|
return true;
|
|
22493
22993
|
}
|
|
22494
22994
|
});
|
|
22495
22995
|
for (const [k, row] of foundRows) {
|
|
22496
22996
|
const q = kOf(k);
|
|
22497
|
-
if (!
|
|
22997
|
+
if (!byKey2.has(q)) byKey2.set(q, { found: true, value: row });
|
|
22498
22998
|
}
|
|
22499
22999
|
for (const id of unique) {
|
|
22500
23000
|
const k = kOf(id);
|
|
22501
|
-
if (
|
|
23001
|
+
if (byKey2.has(k)) continue;
|
|
22502
23002
|
try {
|
|
22503
23003
|
const value = await holder.get(id);
|
|
22504
|
-
|
|
23004
|
+
byKey2.set(k, { found: true, value });
|
|
22505
23005
|
} catch (err) {
|
|
22506
23006
|
if (err instanceof NotFoundError) {
|
|
22507
|
-
|
|
23007
|
+
byKey2.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
|
|
22508
23008
|
} else if (isAutotaskError(err) && err.code !== "ABORTED") {
|
|
22509
23009
|
const e = { code: err.code, message: err.message };
|
|
22510
23010
|
if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
|
|
22511
|
-
|
|
23011
|
+
byKey2.set(k, { found: false, value: null, error: e });
|
|
22512
23012
|
} else {
|
|
22513
23013
|
throw err;
|
|
22514
23014
|
}
|
|
@@ -22519,7 +23019,7 @@ async function fetchByIds(client, items, opts = {}) {
|
|
|
22519
23019
|
for (let i = 0; i < items.length; i += 1) {
|
|
22520
23020
|
const item = items[i];
|
|
22521
23021
|
const id = canonical[i];
|
|
22522
|
-
const out =
|
|
23022
|
+
const out = byKey2.get(`${item.resource}:${String(id)}`);
|
|
22523
23023
|
const value = out.found ? item.fields !== void 0 ? project2(out.value, item.fields) : out.value : null;
|
|
22524
23024
|
results.push(
|
|
22525
23025
|
out.found ? { resource: item.resource, id, found: true, value } : { resource: item.resource, id, found: false, value: null, error: out.error }
|
|
@@ -23047,7 +23547,10 @@ async function revenueRollup(client, opts) {
|
|
|
23047
23547
|
const groupDims = v.groupBy.map((d) => DIMENSIONS[d]);
|
|
23048
23548
|
const paths = [.../* @__PURE__ */ new Set([CONTRACTS_PATH, ...groupDims.flatMap((d) => d.picklist ? [d.picklist] : [])])];
|
|
23049
23549
|
const labels = {};
|
|
23050
|
-
|
|
23550
|
+
const labelValues = await mapReadTasks(http, paths, (path) => readPicklists(http, path, OP4));
|
|
23551
|
+
paths.forEach((path, index) => {
|
|
23552
|
+
labels[path] = labelValues[index];
|
|
23553
|
+
});
|
|
23051
23554
|
const contractLabels = labels[CONTRACTS_PATH];
|
|
23052
23555
|
const typeValues = contractLabels.get("contractType") ?? /* @__PURE__ */ new Map();
|
|
23053
23556
|
const inTypes = v.contractTypes ? resolveSelector(OP4, "contractTypes", v.contractTypes, typeValues) : new Map([...typeValues].filter(([, l]) => DEFAULT_CONTRACT_TYPE_RE.test(l)));
|
|
@@ -23076,10 +23579,12 @@ async function revenueRollup(client, opts) {
|
|
|
23076
23579
|
const invoiceFilter = (voided2) => [...windowOn("invoiceDateTime"), { field: "isVoided", op: "eq", value: voided2 }];
|
|
23077
23580
|
const withVoided = v.scopeKind !== "contractIDs";
|
|
23078
23581
|
const voidedFilter = [...invoiceFilter(true), ...scopeIds !== void 0 && withVoided ? [{ field: "companyID", op: "in", value: scopeIds }] : []];
|
|
23079
|
-
const nInvoices = await invoices.count({ filter: invoiceFilter(false) });
|
|
23080
|
-
const nLines = await billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] });
|
|
23081
23582
|
const uninvoicedFilter = [{ field: "invoiceID", op: "notExist" }, ...windowOn("itemDate"), ...scopeCond];
|
|
23082
|
-
const nUninvoiced =
|
|
23583
|
+
const [nInvoices, nLines, nUninvoiced] = await readTasks(http, [
|
|
23584
|
+
() => invoices.count({ filter: invoiceFilter(false) }),
|
|
23585
|
+
() => billingItems.count({ filter: [...windowOn("itemDate"), { field: "invoiceID", op: "exist" }, ...scopeCond] }),
|
|
23586
|
+
() => v.nonChargeable ? billingItems.count({ filter: uninvoicedFilter }) : Promise.resolve(0)
|
|
23587
|
+
]);
|
|
23083
23588
|
if (typeof nInvoices !== "number" || typeof nLines !== "number" || typeof nUninvoiced !== "number") throw blindCountError(OP4, "the roll-up", BLIND_ACTION);
|
|
23084
23589
|
const joinsNeeded = Object.keys(JOINS).filter((j) => j === "contracts" || groupDims.some((d) => d.joins?.[j]));
|
|
23085
23590
|
const chunks4 = pages(nInvoices);
|
|
@@ -23124,14 +23629,17 @@ async function revenueRollup(client, opts) {
|
|
|
23124
23629
|
if (v.nonChargeable && uninvoiced.length !== nUninvoiced) throw countMismatchError(OP4, "uninvoiced line", uninvoiced.length, nUninvoiced);
|
|
23125
23630
|
const all = uninvoiced.length > 0 ? [...lines, ...uninvoiced] : lines;
|
|
23126
23631
|
const joined = Object.fromEntries(Object.keys(JOINS).map((j) => [j, /* @__PURE__ */ new Map()]));
|
|
23127
|
-
|
|
23632
|
+
const fetchJoin = async (j) => {
|
|
23128
23633
|
const spec = JOINS[j];
|
|
23129
23634
|
const res = spec.make(http);
|
|
23130
23635
|
const fields = [.../* @__PURE__ */ new Set([...spec.fields, ...groupDims.flatMap((d) => d.joins?.[j] ?? [])])];
|
|
23131
23636
|
const want = [...new Set(spec.ids(all, joined))].filter((id) => id > 0).sort((a, b) => a - b);
|
|
23132
23637
|
const rows = await client.batch((c) => collectRows(res, [{ field: "id", op: "in", value: c }], fields, PAGE), idChunks(want, PAGE), { concurrency: CONCURRENCY });
|
|
23133
23638
|
for (const r of rows.flat()) joined[j].set(num(r["id"]), r);
|
|
23134
|
-
}
|
|
23639
|
+
};
|
|
23640
|
+
const levels = ["organizationalLevel1s", "organizationalLevel2s"];
|
|
23641
|
+
await mapReadTasks(http, joinsNeeded.filter((j) => !levels.includes(j)), fetchJoin);
|
|
23642
|
+
await mapReadTasks(http, joinsNeeded.filter((j) => levels.includes(j)), fetchJoin);
|
|
23135
23643
|
return fold(v, { invoiceById, voided, lines, uninvoiced, joined, labels, inTypes, inCategories, scopeIds, calls: budget.spent(), estimate });
|
|
23136
23644
|
}
|
|
23137
23645
|
function refusal(v, estimate, fixed, scopeIds, joinCount) {
|
|
@@ -23513,7 +24021,7 @@ function capJoinSet2(ids2, cap) {
|
|
|
23513
24021
|
}
|
|
23514
24022
|
async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity) {
|
|
23515
24023
|
const unique = [...new Set(ids2)].sort((a, b) => a - b);
|
|
23516
|
-
const
|
|
24024
|
+
const byKey2 = /* @__PURE__ */ new Map();
|
|
23517
24025
|
const misses = [];
|
|
23518
24026
|
const notes = [];
|
|
23519
24027
|
const found = await fetchIdChunks(http, entityPath, unique, fields, operation, {
|
|
@@ -23523,17 +24031,17 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
|
|
|
23523
24031
|
const code = err instanceof AutotaskError ? err.code : "SERVER_ERROR";
|
|
23524
24032
|
for (const k of chunk) {
|
|
23525
24033
|
const id = Number(k);
|
|
23526
|
-
if (!
|
|
24034
|
+
if (!byKey2.has(id) && !misses.some((m) => m.id === id)) misses.push({ id, code, message: err instanceof Error ? err.message : String(err) });
|
|
23527
24035
|
}
|
|
23528
24036
|
return true;
|
|
23529
24037
|
}
|
|
23530
24038
|
});
|
|
23531
|
-
for (const [k, row] of found)
|
|
23532
|
-
const queryMissed = unique.filter((k) => !
|
|
24039
|
+
for (const [k, row] of found) byKey2.set(Number(k), row);
|
|
24040
|
+
const queryMissed = unique.filter((k) => !byKey2.has(k) && !misses.some((m) => m.id === k));
|
|
23533
24041
|
for (const k of queryMissed) {
|
|
23534
24042
|
try {
|
|
23535
24043
|
const res = await http.request({ method: "GET", path: `${entityPath}/${k}`, operation });
|
|
23536
|
-
|
|
24044
|
+
byKey2.set(k, unwrapItem(res, k, operation, entity));
|
|
23537
24045
|
} catch (err) {
|
|
23538
24046
|
if (err instanceof NotFoundError) {
|
|
23539
24047
|
misses.push({ id: k, code: "NOT_FOUND", message: err.message });
|
|
@@ -23544,14 +24052,14 @@ async function fetchByIdsPart(http, entityPath, ids2, fields, operation, entity)
|
|
|
23544
24052
|
}
|
|
23545
24053
|
}
|
|
23546
24054
|
}
|
|
23547
|
-
const items = unique.map((k) =>
|
|
24055
|
+
const items = unique.map((k) => byKey2.get(k)).filter((r) => r !== void 0);
|
|
23548
24056
|
const gotByQuery = unique.length - queryMissed.length;
|
|
23549
|
-
if (queryMissed.length > 0 && gotByQuery === 0 &&
|
|
24057
|
+
if (queryMissed.length > 0 && gotByQuery === 0 && byKey2.size > 0) {
|
|
23550
24058
|
notes.push(
|
|
23551
|
-
`the chunk \`id in\` query returned 0 rows for ${
|
|
24059
|
+
`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)`
|
|
23552
24060
|
);
|
|
23553
24061
|
}
|
|
23554
|
-
const foundIds = new Set(
|
|
24062
|
+
const foundIds = new Set(byKey2.keys());
|
|
23555
24063
|
if (misses.length > 0) {
|
|
23556
24064
|
const byCode = /* @__PURE__ */ new Map();
|
|
23557
24065
|
for (const m of misses) byCode.set(m.code, (byCode.get(m.code) ?? 0) + 1);
|
|
@@ -23643,6 +24151,17 @@ function makeFetchCtx(rawHttp, v, contractId, budget, sharedExpenses) {
|
|
|
23643
24151
|
};
|
|
23644
24152
|
return { v, OP: OP14, id, idNum, rawHttp, http, wires, windowOn, readPart, windowedPart, truncatedMonths, ...sharedExpenses ? { sharedExpenses } : {} };
|
|
23645
24153
|
}
|
|
24154
|
+
function forkFetchCtx(ctx) {
|
|
24155
|
+
return makeFetchCtx(ctx.rawHttp, ctx.v, ctx.id, ctx.wires.budget, ctx.sharedExpenses);
|
|
24156
|
+
}
|
|
24157
|
+
function mergeFetchContexts(ctx, branches) {
|
|
24158
|
+
for (const branch of branches) {
|
|
24159
|
+
ctx.wires.issued += branch.wires.issued;
|
|
24160
|
+
ctx.wires.requests += branch.wires.requests;
|
|
24161
|
+
if (branch.wires.note) appendWiresNote(ctx.wires, branch.wires.note);
|
|
24162
|
+
Object.assign(ctx.truncatedMonths, branch.truncatedMonths);
|
|
24163
|
+
}
|
|
24164
|
+
}
|
|
23646
24165
|
|
|
23647
24166
|
// src/resources/special/contracts/profitability.util.ts
|
|
23648
24167
|
function dateToDay(v) {
|
|
@@ -23791,11 +24310,7 @@ async function fetchCustomer(ctx, companyID) {
|
|
|
23791
24310
|
let customerAbsent;
|
|
23792
24311
|
if (companyID > 0) {
|
|
23793
24312
|
try {
|
|
23794
|
-
const res = await ctx.http.
|
|
23795
|
-
method: "GET",
|
|
23796
|
-
path: `/V1.0/Companies/${companyID}`,
|
|
23797
|
-
operation: ctx.OP
|
|
23798
|
-
});
|
|
24313
|
+
const res = await cachedRecordGet(ctx.http, `/V1.0/Companies/${companyID}`, ctx.OP);
|
|
23799
24314
|
const item = unwrapItem(res, companyID, ctx.OP, "company");
|
|
23800
24315
|
customer = item ?? null;
|
|
23801
24316
|
customerStatus = "ok";
|
|
@@ -23825,16 +24340,17 @@ async function resolveContractType(ctx, contractType) {
|
|
|
23825
24340
|
const isTimeAndMaterials = contractTypeKnown && TIME_AND_MATERIALS_LABEL_RE.test(contractTypeLabel);
|
|
23826
24341
|
return { contractTypeLabel, contractTypeKnown, isBlockHours, isTimeAndMaterials };
|
|
23827
24342
|
}
|
|
23828
|
-
async function fetchRoot(ctx
|
|
23829
|
-
const
|
|
23830
|
-
const contract =
|
|
24343
|
+
async function fetchRoot(ctx) {
|
|
24344
|
+
const body = await cachedRecordGet(ctx.http, `/V1.0/Contracts/${ctx.id}`, "contracts.get");
|
|
24345
|
+
const contract = unwrapItem(body, ctx.id, "contracts.get", "contract");
|
|
23831
24346
|
ctx.wires.issued += 1;
|
|
23832
|
-
if (!contractCached) ctx.wires.requests += 1;
|
|
23833
24347
|
const contractRow = contract;
|
|
23834
24348
|
const companyID = num(contractRow["companyID"]);
|
|
23835
24349
|
const contractType = num(contractRow["contractType"]);
|
|
23836
|
-
const customerStage = await
|
|
23837
|
-
|
|
24350
|
+
const [customerStage, typeStage] = await readTasks(ctx.http, [
|
|
24351
|
+
() => fetchCustomer(ctx, companyID),
|
|
24352
|
+
() => resolveContractType(ctx, contractType)
|
|
24353
|
+
]);
|
|
23838
24354
|
return { contract, contractRow, contractType, ...customerStage, ...typeStage };
|
|
23839
24355
|
}
|
|
23840
24356
|
async function fetchCharges(ctx) {
|
|
@@ -23845,27 +24361,29 @@ async function fetchCharges(ctx) {
|
|
|
23845
24361
|
const raw = await ctx.readPart("/V1.0/ContractCharges/query", chargesCond, ["id", "chargeType", "billableAmount", "extendedCost", "unitCost", "unitPrice", "unitQuantity", "datePurchased", "isBilled", "status", "contractServiceID"]);
|
|
23846
24362
|
return { charges: raw.items, chargesPart: stampPart("contract_charges", raw, chargesCond) };
|
|
23847
24363
|
}
|
|
23848
|
-
async function fetchBlocks(ctx,
|
|
23849
|
-
if (!
|
|
24364
|
+
async function fetchBlocks(ctx, root2) {
|
|
24365
|
+
if (!root2.isBlockHours) {
|
|
23850
24366
|
return skipPart(
|
|
23851
|
-
|
|
24367
|
+
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)`
|
|
23852
24368
|
);
|
|
23853
24369
|
}
|
|
23854
24370
|
const blocksCond = [{ field: "contractID", op: "eq", value: ctx.id }];
|
|
23855
24371
|
const raw = await ctx.readPart("/V1.0/ContractBlocks/query", blocksCond, ["id", "datePurchased", "startDate", "endDate", "hours", "hoursApproved", "status", "isPaid"]);
|
|
23856
24372
|
return stampPart("contract_blocks", raw, blocksCond);
|
|
23857
24373
|
}
|
|
23858
|
-
async function fetchContractState(ctx,
|
|
24374
|
+
async function fetchContractState(ctx, root2) {
|
|
23859
24375
|
const servicesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
|
|
23860
|
-
const servicesRaw = await ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]);
|
|
23861
24376
|
const unitsCond = [{ field: "contractID", op: "eq", value: ctx.id }, ...ctx.windowOn("startDate")];
|
|
23862
|
-
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");
|
|
23863
|
-
const { chargesPart, charges } = await fetchCharges(ctx);
|
|
23864
24377
|
const roleCostsCond = [{ field: "contractID", op: "eq", value: ctx.id }];
|
|
23865
|
-
const roleCostsRaw = await ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]);
|
|
23866
24378
|
const ratesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
|
|
23867
|
-
const
|
|
23868
|
-
|
|
24379
|
+
const [servicesRaw, units, { chargesPart, charges }, roleCostsRaw, ratesRaw, blocksPart] = await readTasks(ctx.http, [
|
|
24380
|
+
() => ctx.readPart("/V1.0/ContractServices/query", servicesCond, ["id", "serviceID", "unitPrice", "unitCost", "internalCurrencyUnitPrice", "internalDescription"]),
|
|
24381
|
+
() => ctx.windowedPart("contractServiceUnits", "contract_service_units", "/V1.0/ContractServiceUnits/query", unitsCond, ["id", "contractServiceID", "serviceID", "units", "price", "cost", "internalCurrencyPrice", "startDate", "endDate", "approveAndPostDate"], "startDate"),
|
|
24382
|
+
() => fetchCharges(ctx),
|
|
24383
|
+
() => ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]),
|
|
24384
|
+
() => ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]),
|
|
24385
|
+
() => fetchBlocks(ctx, root2)
|
|
24386
|
+
]);
|
|
23869
24387
|
return { servicesRaw, servicesCond, unitRows: units.rows, unitsPartRaw: units.part, chargesPart, charges, roleCostsRaw, roleCostsCond, ratesRaw, ratesCond, blocksPart };
|
|
23870
24388
|
}
|
|
23871
24389
|
async function fetchBillingItems(ctx) {
|
|
@@ -24228,25 +24746,46 @@ async function fetchSubscriptionsJoin(ctx) {
|
|
|
24228
24746
|
}
|
|
24229
24747
|
|
|
24230
24748
|
// src/resources/special/contracts/profitability.data.ts
|
|
24231
|
-
async function gather(ctx
|
|
24232
|
-
const
|
|
24233
|
-
const
|
|
24234
|
-
|
|
24235
|
-
|
|
24236
|
-
|
|
24237
|
-
const
|
|
24238
|
-
|
|
24239
|
-
const
|
|
24240
|
-
|
|
24241
|
-
|
|
24749
|
+
async function gather(ctx) {
|
|
24750
|
+
const root2 = await fetchRoot(ctx);
|
|
24751
|
+
const stages = Object.fromEntries(
|
|
24752
|
+
["state", "billing", "time", "activity", "open", "res", "join", "subs"].map((name) => [name, forkFetchCtx(ctx)])
|
|
24753
|
+
);
|
|
24754
|
+
let timeRead;
|
|
24755
|
+
const timeTask = () => timeRead ??= fetchTime(stages.time);
|
|
24756
|
+
let activityRead;
|
|
24757
|
+
const activityTask = () => activityRead ??= timeTask().then((time) => fetchTicketActivity(stages.activity, time.entries));
|
|
24758
|
+
let openRead;
|
|
24759
|
+
const openTask = () => openRead ??= fetchOpenTickets(stages.open);
|
|
24760
|
+
const tasks = {
|
|
24761
|
+
state: () => fetchContractState(stages.state, root2),
|
|
24762
|
+
billing: () => fetchBilling(stages.billing),
|
|
24763
|
+
time: timeTask,
|
|
24764
|
+
activity: activityTask,
|
|
24765
|
+
open: openTask,
|
|
24766
|
+
res: async () => fetchResources(stages.res, (await timeTask()).entries),
|
|
24767
|
+
join: async () => {
|
|
24768
|
+
const activity = await activityTask();
|
|
24769
|
+
const open = await openTask();
|
|
24770
|
+
const time = await timeTask();
|
|
24771
|
+
Object.assign(stages.join.truncatedMonths, stages.time.truncatedMonths);
|
|
24772
|
+
return fetchTicketJoinParts(stages.join, [...activity.ticketsActRaw.items, ...open.openTickets], time.entries);
|
|
24773
|
+
},
|
|
24774
|
+
subs: () => fetchSubscriptionsJoin(stages.subs)
|
|
24775
|
+
};
|
|
24776
|
+
const order = ctx.http.maxConcurrent === 1 ? ["state", "billing", "time", "activity", "open", "res", "join", "subs"] : ["state", "billing", "time", "open", "subs", "activity", "res", "join"];
|
|
24777
|
+
const completed = await mapReadTasks(ctx.http, order, async (name) => [name, await tasks[name]()]);
|
|
24778
|
+
const parts = Object.fromEntries(completed);
|
|
24779
|
+
mergeFetchContexts(ctx, Object.values(stages));
|
|
24780
|
+
return { root: root2, ...parts };
|
|
24242
24781
|
}
|
|
24243
24782
|
function stampListParts(v, f) {
|
|
24244
|
-
const { state, activity, join } = f;
|
|
24783
|
+
const { state: state2, activity, join } = f;
|
|
24245
24784
|
return {
|
|
24246
|
-
servicesPart: stampPart("contract_services",
|
|
24247
|
-
unitsPart:
|
|
24248
|
-
roleCostsPart: stampPart("contract_role_costs",
|
|
24249
|
-
ratesPart: stampPart("contract_rates",
|
|
24785
|
+
servicesPart: stampPart("contract_services", state2.servicesRaw, state2.servicesCond),
|
|
24786
|
+
unitsPart: state2.unitsPartRaw,
|
|
24787
|
+
roleCostsPart: stampPart("contract_role_costs", state2.roleCostsRaw, state2.roleCostsCond),
|
|
24788
|
+
ratesPart: stampPart("contract_rates", state2.ratesRaw, state2.ratesCond),
|
|
24250
24789
|
ticketsActivityPart: stampPart("tickets", activity.ticketsActRaw, activity.ticketsActCond, [
|
|
24251
24790
|
...activity.ticketsActRaw.hasMore ? [`${join.fetchedTickets.size} ticket(s) returned of possibly more \u2014 the checks cover the returned set only`] : [],
|
|
24252
24791
|
...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`] : []
|
|
@@ -24887,7 +25426,7 @@ async function profitability(resource, contractId, opts, sharedExpenses) {
|
|
|
24887
25426
|
const v = validateProfitabilityOptions(contractId, opts);
|
|
24888
25427
|
const ctx = makeFetchCtx(resource.http, v, contractId, PROFITABILITY_WIRE_BUDGET, sharedExpenses);
|
|
24889
25428
|
const asOf = (/* @__PURE__ */ new Date()).toISOString();
|
|
24890
|
-
const f = await gather(ctx
|
|
25429
|
+
const f = await gather(ctx);
|
|
24891
25430
|
const fc = makeFoldCtx(ctx, f, stampListParts(v, f), Date.parse(asOf));
|
|
24892
25431
|
return assemble(ctx, fc, asOf);
|
|
24893
25432
|
}
|
|
@@ -24974,17 +25513,30 @@ function validate2(opts) {
|
|
|
24974
25513
|
function latchingHttp(raw, spend) {
|
|
24975
25514
|
const counted = countingHttp(raw, spend);
|
|
24976
25515
|
let fatal;
|
|
25516
|
+
const controller = new AbortController();
|
|
25517
|
+
const caller = ambientCallerSignal();
|
|
25518
|
+
const signal = caller === void 0 ? controller.signal : AbortSignal.any([caller, controller.signal]);
|
|
24977
25519
|
const http = Object.create(counted);
|
|
24978
|
-
|
|
25520
|
+
const latch = (err) => {
|
|
25521
|
+
if (err instanceof RateLimitError || err instanceof AutotaskError && err.code === "BUDGET_EXCEEDED") {
|
|
25522
|
+
fatal ??= err;
|
|
25523
|
+
controller.abort(fatal);
|
|
25524
|
+
}
|
|
25525
|
+
};
|
|
25526
|
+
observeRecordReadFailures(http, latch);
|
|
25527
|
+
const fail = (err) => {
|
|
25528
|
+
latch(err);
|
|
25529
|
+
throw err;
|
|
25530
|
+
};
|
|
25531
|
+
http.request = (o) => {
|
|
24979
25532
|
if (fatal) throw fatal;
|
|
24980
25533
|
try {
|
|
24981
|
-
return
|
|
25534
|
+
return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail);
|
|
24982
25535
|
} catch (err) {
|
|
24983
|
-
|
|
24984
|
-
throw err;
|
|
25536
|
+
return fail(err);
|
|
24985
25537
|
}
|
|
24986
25538
|
};
|
|
24987
|
-
return { http, fatal: () => fatal };
|
|
25539
|
+
return { http, fatal: () => fatal, signal };
|
|
24988
25540
|
}
|
|
24989
25541
|
async function portfolioMargin(client, opts) {
|
|
24990
25542
|
const v = validate2(opts);
|
|
@@ -24995,7 +25547,7 @@ async function portfolioMargin(client, opts) {
|
|
|
24995
25547
|
{ phase: estimate === 0 ? "estimate" : "walk", budget: v.budget, vendorCalls: spent, ...estimate > 0 ? { estimate } : {} },
|
|
24996
25548
|
`Pass maxVendorCalls > ${v.budget} (cap ${BUDGET_CAP2}) or fewer contracts.`
|
|
24997
25549
|
));
|
|
24998
|
-
const { http, fatal } = latchingHttp(client.http, budget.spend);
|
|
25550
|
+
const { http, fatal, signal } = latchingHttp(client.http, budget.spend);
|
|
24999
25551
|
const contracts = new ContractsResource(http, PAGE2);
|
|
25000
25552
|
let typeMap;
|
|
25001
25553
|
if (v.contractTypes) {
|
|
@@ -25042,7 +25594,7 @@ async function portfolioMargin(client, opts) {
|
|
|
25042
25594
|
let results;
|
|
25043
25595
|
try {
|
|
25044
25596
|
const shared = countFault ?? (expenseCount === 0 ? { rows: [], contractOf: /* @__PURE__ */ new Map(), misses: 0 } : await readTicketExpenses(http, expenseItems, expenseFilter, expenseCount));
|
|
25045
|
-
results = await client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 });
|
|
25597
|
+
results = await client.withSignal(signal, () => client.batch((id) => profitability(contracts, id, v.profitOpts, shared), ids2, { concurrency: CONCURRENCY2 }));
|
|
25046
25598
|
} catch (err) {
|
|
25047
25599
|
throw fatal() ?? err;
|
|
25048
25600
|
}
|
|
@@ -25285,8 +25837,10 @@ async function recurringRevenue(client, opts) {
|
|
|
25285
25837
|
];
|
|
25286
25838
|
const subsRes = res("subscriptions");
|
|
25287
25839
|
const subFilter = [{ field: "effectiveDate", op: "lt", value: next }, { field: "expirationDate", op: "gte", value: v.asOf }];
|
|
25288
|
-
const nContracts = await
|
|
25289
|
-
|
|
25840
|
+
const [nContracts, nSubs] = await readTasks(http, [
|
|
25841
|
+
() => countOf(contractsRes, "contract", contractFilter),
|
|
25842
|
+
() => countOf(subsRes, "subscription", subFilter)
|
|
25843
|
+
]);
|
|
25290
25844
|
const chunks4 = Math.ceil(nContracts / CHUNK);
|
|
25291
25845
|
const subCalls = Math.ceil(nSubs / PAGE3) + (nSubs > 0 ? 1 : 0) + Math.ceil(nSubs / CHUNK) + (v.scopeIds ? 1 : Math.ceil((nContracts + nSubs) / CHUNK));
|
|
25292
25846
|
const refuse3 = (calls, sets2) => {
|
|
@@ -25325,26 +25879,35 @@ async function recurringRevenue(client, opts) {
|
|
|
25325
25879
|
nCharges: 0
|
|
25326
25880
|
};
|
|
25327
25881
|
});
|
|
25328
|
-
|
|
25329
|
-
|
|
25330
|
-
|
|
25331
|
-
|
|
25882
|
+
await mapReadTasks(http, sets.flatMap((x) => [
|
|
25883
|
+
async () => {
|
|
25884
|
+
x.nUnits = await countOf(res("contract_service_units"), "service unit", x.unitFilter);
|
|
25885
|
+
},
|
|
25886
|
+
async () => {
|
|
25887
|
+
x.nCharges = await countOf(res("contract_charges"), "charge", x.chargeFilter);
|
|
25888
|
+
}
|
|
25889
|
+
]), (task) => task());
|
|
25332
25890
|
const nUnits = sets.reduce((a, x) => a + x.nUnits, 0);
|
|
25333
25891
|
const nCharges = sets.reduce((a, x) => a + x.nCharges, 0);
|
|
25334
25892
|
estimate = budget.spent() + sets.reduce((a, x) => a + Math.ceil(x.nUnits / PAGE3) + Math.ceil(x.nCharges / PAGE3), 0) + subCalls;
|
|
25335
25893
|
if (estimate > v.budget) {
|
|
25336
25894
|
throw refuse3(estimate, { contracts: nContracts, serviceUnits: nUnits, charges: nCharges, subscriptions: nSubs });
|
|
25337
25895
|
}
|
|
25338
|
-
const
|
|
25339
|
-
|
|
25340
|
-
|
|
25341
|
-
|
|
25342
|
-
|
|
25343
|
-
|
|
25344
|
-
|
|
25345
|
-
|
|
25346
|
-
|
|
25347
|
-
|
|
25896
|
+
const [unitSets, chargeSets, { subs, labels, cis }] = await readTasks(http, [
|
|
25897
|
+
() => mapReadTasks(http, sets, (x) => gated(res("contract_service_units"), "service unit", x.unitFilter, ["id", "contractID", "contractServiceID", "startDate", "endDate", "units", "price", "internalCurrencyPrice"], x.nUnits)),
|
|
25898
|
+
() => mapReadTasks(http, sets, (x) => gated(res("contract_charges"), "charge", x.chargeFilter, ["id", "contractID", "billableAmount", "internalCurrencyBillableAmount"], x.nCharges)),
|
|
25899
|
+
async () => {
|
|
25900
|
+
const subs2 = await gated(subsRes, "subscription", subFilter, ["id", "configurationItemID", "periodPrice", "periodType", "status"], nSubs);
|
|
25901
|
+
const ciIds = [...new Set(subs2.map((s) => num(s["configurationItemID"])).filter((n) => n > 0))].sort((a, b) => a - b);
|
|
25902
|
+
const [labels2, cis2] = await readTasks(http, [
|
|
25903
|
+
() => subs2.length > 0 ? readPicklists(http, "/V1.0/Subscriptions", OP6) : Promise.resolve(/* @__PURE__ */ new Map()),
|
|
25904
|
+
() => ciIds.length > 0 ? fetchIdChunks(http, "/V1.0/ConfigurationItems", ciIds, ["companyID"], OP6, { chunkSize: CHUNK }) : Promise.resolve(/* @__PURE__ */ new Map())
|
|
25905
|
+
]);
|
|
25906
|
+
return { subs: subs2, labels: labels2, cis: cis2 };
|
|
25907
|
+
}
|
|
25908
|
+
]);
|
|
25909
|
+
const units = unitSets.flat();
|
|
25910
|
+
const charges = chargeSets.flat();
|
|
25348
25911
|
const contractOf = new Map(contracts.map((c) => [num(c["id"]), c]));
|
|
25349
25912
|
const latest = /* @__PURE__ */ new Map();
|
|
25350
25913
|
for (const u of units) {
|
|
@@ -26057,7 +26620,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
|
|
|
26057
26620
|
suggestedAction: "Narrow the dateWorked window, or page it with cursor (rows mode reports unconfirmed entries via truncated)."
|
|
26058
26621
|
});
|
|
26059
26622
|
}
|
|
26060
|
-
for (const [id,
|
|
26623
|
+
for (const [id, state2] of joined.states) states.set(id, state2);
|
|
26061
26624
|
cursor = page.items.length === 0 ? null : page.pageDetails.nextPageUrl ?? null;
|
|
26062
26625
|
} while (cursor !== null);
|
|
26063
26626
|
spend();
|
|
@@ -26075,7 +26638,7 @@ async function countPostedState(http, filter, OP14, budget, window) {
|
|
|
26075
26638
|
});
|
|
26076
26639
|
}
|
|
26077
26640
|
let postedCount = 0;
|
|
26078
|
-
for (const
|
|
26641
|
+
for (const state2 of states.values()) if (state2 === "posted") postedCount += 1;
|
|
26079
26642
|
return { window, total: states.size, postedCount, unpostedCount: states.size - postedCount, vendorCalls: callBudget.spent(), estimate, budget };
|
|
26080
26643
|
}
|
|
26081
26644
|
async function dateWorkedWindow(resource, from, to, opts) {
|
|
@@ -26096,8 +26659,8 @@ async function dateWorkedWindow(resource, from, to, opts) {
|
|
|
26096
26659
|
const { states, incomplete } = await postedStateOf(http, items, OP14);
|
|
26097
26660
|
let postedCount = 0;
|
|
26098
26661
|
let unpostedCount = 0;
|
|
26099
|
-
for (const
|
|
26100
|
-
if (
|
|
26662
|
+
for (const state2 of states.values()) {
|
|
26663
|
+
if (state2 === "posted") postedCount += 1;
|
|
26101
26664
|
else unpostedCount += 1;
|
|
26102
26665
|
}
|
|
26103
26666
|
return {
|
|
@@ -26381,12 +26944,14 @@ async function wipHours(client, opts) {
|
|
|
26381
26944
|
} else {
|
|
26382
26945
|
const contractIds = positiveIds2(wipIn.map((e) => e["contractID"]));
|
|
26383
26946
|
gate(chunks2(contractIds.length) + (contractIds.length > 0 ? 1 : 0), "before label reads", { contracts: contractIds.length });
|
|
26384
|
-
const contracts = await
|
|
26947
|
+
const [contracts, types] = await readTasks(http, [
|
|
26948
|
+
() => readChunks2(http, "/V1.0/Contracts", contractIds, ["contractType"]),
|
|
26949
|
+
async () => contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0
|
|
26950
|
+
]);
|
|
26385
26951
|
const typeOf = (id) => contracts.get(String(id))?.["contractType"];
|
|
26386
26952
|
const bad = contractIds.filter((id) => typeof typeOf(id) !== "number");
|
|
26387
26953
|
if (bad.length > 0) throw unresolved("contracts", bad);
|
|
26388
26954
|
keyOfEntry = (e) => num(e["contractID"]) > 0 ? typeOf(num(e["contractID"])) : null;
|
|
26389
|
-
const types = contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP10)).get("contractType") : void 0;
|
|
26390
26955
|
for (const [id, label] of types ?? []) labels.set(id, { label });
|
|
26391
26956
|
}
|
|
26392
26957
|
const approvalData = entries.some((e) => isApproved(e));
|
|
@@ -26578,8 +27143,10 @@ async function nonChargeableWork(client, opts) {
|
|
|
26578
27143
|
const contractIds = distinctIds(ncLines.map((x) => x.line["contractID"]), 1);
|
|
26579
27144
|
const typed = v.groupBy === "contractType";
|
|
26580
27145
|
gate(chunks3(contractIds.length) + (typed && contractIds.length > 0 ? 1 : 0) + (v.includeUnpostedTime ? 1 : 0), "before label reads", { contracts: contractIds.length });
|
|
26581
|
-
const contracts = await
|
|
26582
|
-
|
|
27146
|
+
const [contracts, types] = await readTasks(http, [
|
|
27147
|
+
() => readChunks3(http, "/V1.0/Contracts", contractIds, [typed ? "contractType" : "contractName"]),
|
|
27148
|
+
async () => typed && contractIds.length > 0 ? (await readPicklists(http, "/V1.0/Contracts", OP11)).get("contractType") : void 0
|
|
27149
|
+
]);
|
|
26583
27150
|
keyOfLine = (line) => {
|
|
26584
27151
|
if (num(line["contractID"]) === 0) return null;
|
|
26585
27152
|
const c = contracts.get(String(line["contractID"]));
|
|
@@ -27061,6 +27628,10 @@ async function openTicketsOfPart(client, field, id, limit) {
|
|
|
27061
27628
|
const filter = [{ field, op: "eq", value: id }, ...closed.map((v) => ({ field: "status", op: "noteq", value: v }))];
|
|
27062
27629
|
return { ...await compositePart(client, "tickets.query", [{ filter, limit }]), closedStatus };
|
|
27063
27630
|
}
|
|
27631
|
+
async function joinedCompositePart(client, source, idField, targetOp, targetField, limit, absent) {
|
|
27632
|
+
const ids2 = numericIds(source.value?.items ?? [], idField).slice(0, IN_FILTER_CAP);
|
|
27633
|
+
return ids2.length === 0 ? { value: null, absent } : await compositePart(client, targetOp, [{ filter: [{ field: targetField, op: "in", value: ids2 }], limit }]);
|
|
27634
|
+
}
|
|
27064
27635
|
|
|
27065
27636
|
// src/resources/special/contracts/fullProfile.ts
|
|
27066
27637
|
var OP12 = "contracts.fullProfile";
|
|
@@ -27071,21 +27642,23 @@ async function fullProfile2(resource, id, opts = {}) {
|
|
|
27071
27642
|
const serviceLimit = compositePartLimit(opts.serviceLimit, "serviceLimit", OP12);
|
|
27072
27643
|
const billingRuleLimit = compositePartLimit(opts.billingRuleLimit, "billingRuleLimit", OP12);
|
|
27073
27644
|
const contractId = parseIdentifier(id, "id");
|
|
27074
|
-
const
|
|
27075
|
-
const services = await
|
|
27076
|
-
|
|
27077
|
-
|
|
27078
|
-
|
|
27079
|
-
|
|
27080
|
-
|
|
27081
|
-
|
|
27082
|
-
|
|
27083
|
-
|
|
27084
|
-
|
|
27085
|
-
|
|
27645
|
+
const root2 = await invokeRead(client, "contracts.get", [contractId]);
|
|
27646
|
+
const [services, billingRules, charges, units] = await readTasks(resource.http, [
|
|
27647
|
+
() => compositePart(client, "contract_services.query", [
|
|
27648
|
+
{ filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
|
|
27649
|
+
]),
|
|
27650
|
+
() => compositePart(client, "contract_billing_rules.query", [
|
|
27651
|
+
{ filter: [{ field: "contractID", op: "eq", value: contractId }], limit: billingRuleLimit }
|
|
27652
|
+
]),
|
|
27653
|
+
() => compositePart(client, "contract_charges.query", [
|
|
27654
|
+
{ filter: [{ field: "contractID", op: "eq", value: contractId }], limit: CHARGES_RECENT_CAP, latest: CHARGES_RECENT_CAP }
|
|
27655
|
+
]),
|
|
27656
|
+
() => compositePart(client, "contract_service_units.query", [
|
|
27657
|
+
{ filter: [{ field: "contractID", op: "eq", value: contractId }], limit: SERVICE_UNITS_CAP }
|
|
27658
|
+
])
|
|
27086
27659
|
]);
|
|
27087
27660
|
return {
|
|
27088
|
-
root,
|
|
27661
|
+
root: root2,
|
|
27089
27662
|
parts: {
|
|
27090
27663
|
services,
|
|
27091
27664
|
billing_rules: billingRules,
|
|
@@ -27164,4 +27737,4 @@ var ContractsResource = class extends GenericResource {
|
|
|
27164
27737
|
}
|
|
27165
27738
|
};
|
|
27166
27739
|
|
|
27167
|
-
export { AGGREGATE_DATE_BUCKETS, AGGREGATE_DEFAULT_LIMIT, AGGREGATE_DEFAULT_TOP, AGGREGATE_TOP_MAX, AutotaskAbortError, AutotaskConfigError, AutotaskError, AutotaskNetworkError, AutotaskTimeoutError, CREATE_BLOCKER_KINDS, CREDENTIAL_ENV_LOAD_ACTION, CREDENTIAL_SHAPE_POINTER, CompaniesResource, ConfirmationRequiredError, ConflictError, ContractsResource, DEFAULT_ZONE, DeleteBoundaryError, EXPAND_RESOURCE_NAMES_MAX_IDS, EmptyResponseError, FETCH_BY_IDS_CHUNK_SIZE, FETCH_BY_IDS_MAX_ITEMS, FIELD_CACHE_KINDS, FIELD_CATALOG_HONESTY_NOTE, GenericResource, HostPolicyDeniedError, HttpClient, INVOKE_OPTION_KEYS,
|
|
27740
|
+
export { AGGREGATE_DATE_BUCKETS, AGGREGATE_DEFAULT_LIMIT, AGGREGATE_DEFAULT_TOP, AGGREGATE_TOP_MAX, AutotaskAbortError, AutotaskConfigError, AutotaskError, AutotaskNetworkError, AutotaskTimeoutError, CREATE_BLOCKER_KINDS, CREDENTIAL_ENV_LOAD_ACTION, CREDENTIAL_SHAPE_POINTER, CompaniesResource, ConfirmationRequiredError, ConflictError, ContractsResource, DEFAULT_ZONE, DeleteBoundaryError, EXPAND_RESOURCE_NAMES_MAX_IDS, EmptyResponseError, FETCH_BY_IDS_CHUNK_SIZE, FETCH_BY_IDS_MAX_ITEMS, FIELD_CACHE_KINDS, FIELD_CATALOG_HONESTY_NOTE, GenericResource, HostPolicyDeniedError, HttpClient, INVOKE_OPTION_KEYS, InvoicesResource, MAX_FIELD_CATALOG_WIRE, MIN_FIELD_CATALOG_MAX_BYTES, MIN_PREFIX_SUMMARY_LENGTH, MaintenanceError, MarkerUnsafeIdError, MoveRefusedError, NotFoundError, OperationNotSupportedError, PARAMS_BAG_KEYS, PICKLIST_VALUE_NOT_SERVED_NOTE, PaginationLimitError, QueryTooLongError, RELATIONSHIP_MAP, RateLimitError, RecoveryTruncatedError, ResolutionError, ResponseRejectedError, SIMPLE_RESOURCES, ScopeRequiredError, StaleObjectError, TICKET_LABEL_FIELDS, TimeEntriesResource, TtlCache, UI_LINK_ENTITIES, UNSCOPED_WALK_THRESHOLD, UnexpectedContentTypeError, WORKFLOW_RESOURCES, ZONES, addLabelSibling, addNameSibling, aggregate, arAging, buildDryRunResult, buildQueryRequest, buildReadCache, buildUiLink, cachedRecordGet, clientOf, compositePart, compositePartLimit, createGuidance, createNamePlan, credentialShapeProblem, credentialValueSummary, cursorToPath, dateBucketLabel, effectiveRequiredFields, errorFromStatus, expandResourceNames, fetchByIds, fieldCatalog, foldFlattenedOpts, formatVendorDetail, invoke, invokeDelete, invokeRead, invokeWrite, isAutotaskError, isClosedStatus, isDeterministicVendor500, joinedCompositePart, mergeDetails, mergePartialBody, needsConfirmation, nextActionFor, nonChargeableWork, notPersistedFields, openStatusFilter, openTicketsOfPart, parseIdentifier, parseVendorErrors, portfolioMargin, queryRows, readTasks, recurringRevenue, refuse2 as refuse, relationshipMap, resolveAny, resolveCompositeNames, resolveConfig, resolveCredentials, resolveLineOfBusinessChain, resolveStaff, resolveTicketStatusSemantics, revenueRollup, runBounded, runMove, runWithSignal, sanitiseResult, searchAcrossResources, suspendCompanyIndex, uiLink, uiLinkFor, unknownKeysRefusal, unwrapItem, unwrapItems, unwrapOperation, validateDispatchArgs, validateInvokeOptions, validateParamsBag, vendorId, wipHours, zoneUrl };
|