node-autotask 0.69.0 → 0.69.1

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.
@@ -664,6 +664,7 @@ var TtlCache = class {
664
664
  * its last subscriber leaves. A fresh load starts a new flight and prevents
665
665
  * an older flight from replacing its result; invalidation detaches flights
666
666
  * without changing the answer owed to their existing subscribers.
667
+ * `shouldStore` controls retention, never the result returned to subscribers.
667
668
  * @internal
668
669
  */
669
670
  async load(key, loader, opts) {
@@ -689,7 +690,7 @@ var TtlCache = class {
689
690
  }
690
691
  };
691
692
  }).then((value) => {
692
- if (this.loads.get(key) === created && !controller.signal.aborted) this.set(key, value, epoch);
693
+ if (this.loads.get(key) === created && !controller.signal.aborted && (opts.shouldStore?.(value) ?? true)) this.set(key, value, epoch);
693
694
  return value;
694
695
  });
695
696
  const settled = () => {
@@ -1529,8 +1530,8 @@ function buildFilter(conditions) {
1529
1530
  if (list.length === 0) {
1530
1531
  throw new AutotaskConfigError("buildFilter requires at least one condition");
1531
1532
  }
1532
- const root2 = list.length === 1 ? list[0] : { op: "and", items: list };
1533
- const filter = { filter: [root2] };
1533
+ const root3 = list.length === 1 ? list[0] : { op: "and", items: list };
1534
+ const filter = { filter: [root3] };
1534
1535
  validateFilter(filter);
1535
1536
  return filter;
1536
1537
  }
@@ -1850,6 +1851,10 @@ var Semaphore = class {
1850
1851
  maxConcurrent;
1851
1852
  inFlight = 0;
1852
1853
  waitQueue = /* @__PURE__ */ new Set();
1854
+ /** Synchronous eligibility check; acquisition must follow without an await. @internal */
1855
+ canAcquire() {
1856
+ return this.inFlight < this.maxConcurrent && this.waitQueue.size === 0;
1857
+ }
1853
1858
  acquire(signal) {
1854
1859
  if (signal?.aborted) return Promise.reject(signal.reason);
1855
1860
  if (this.inFlight < this.maxConcurrent) {
@@ -14269,13 +14274,43 @@ function canonicalObjectKey(url) {
14269
14274
 
14270
14275
  // src/http/object-threads.ts
14271
14276
  var REGISTRY2 = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-gates.v1");
14277
+ var NOTIFY = /* @__PURE__ */ Symbol.for("node-autotask.object-thread-notify.v1");
14272
14278
  var OBJECT_THREAD_LIMIT = 3;
14273
14279
  var state = globalThis;
14274
- async function acquireObjectThread(url, trackingIdentifier, signal) {
14275
- if (signal.aborted) throw signal.reason;
14280
+ function unsupported() {
14281
+ return new AutotaskConfigError("Unsupported shared object-thread semaphore; refusing admission");
14282
+ }
14283
+ function available(semaphore) {
14284
+ const legacy = semaphore;
14285
+ if (!Number.isInteger(legacy.inFlight) || legacy.inFlight < 0 || legacy.inFlight > OBJECT_THREAD_LIMIT || legacy.maxConcurrent !== OBJECT_THREAD_LIMIT || !(legacy.waitQueue instanceof Set)) {
14286
+ throw unsupported();
14287
+ }
14288
+ return legacy.inFlight < OBJECT_THREAD_LIMIT && legacy.waitQueue.size === 0 && (typeof semaphore.canAcquire !== "function" || semaphore.canAcquire());
14289
+ }
14290
+ function observe(semaphore, notify) {
14291
+ let notifications = semaphore[NOTIFY];
14292
+ if (notifications === void 0) {
14293
+ notifications = { listeners: /* @__PURE__ */ new Map() };
14294
+ semaphore[NOTIFY] = notifications;
14295
+ const original = semaphore.release;
14296
+ const shared = notifications;
14297
+ semaphore.release = function() {
14298
+ original.call(this);
14299
+ for (const listener of shared.listeners.keys()) listener();
14300
+ };
14301
+ }
14302
+ const listeners = notifications.listeners;
14303
+ listeners.set(notify, (listeners.get(notify) ?? 0) + 1);
14304
+ return () => {
14305
+ const count = listeners.get(notify) ?? 0;
14306
+ if (count <= 1) listeners.delete(notify);
14307
+ else listeners.set(notify, count - 1);
14308
+ };
14309
+ }
14310
+ function retainObjectThread(url, trackingIdentifier) {
14276
14311
  const target = new URL(url);
14277
14312
  const object = canonicalObjectKey(target.pathname);
14278
- if (object === void 0) return () => void 0;
14313
+ if (object === void 0) return void 0;
14279
14314
  const key = createHash("sha256").update(JSON.stringify([target.origin, trackingIdentifier.trim().toLowerCase(), object])).digest("hex");
14280
14315
  const registry2 = state[REGISTRY2] ??= /* @__PURE__ */ new Map();
14281
14316
  let entry = registry2.get(key);
@@ -14284,24 +14319,260 @@ async function acquireObjectThread(url, trackingIdentifier, signal) {
14284
14319
  registry2.set(key, entry);
14285
14320
  }
14286
14321
  const active = entry;
14322
+ if (!Number.isInteger(active.users) || active.users < 0 || typeof active.semaphore?.acquire !== "function" || typeof active.semaphore.release !== "function") {
14323
+ throw unsupported();
14324
+ }
14325
+ available(active.semaphore);
14287
14326
  active.users += 1;
14288
- const leave = () => {
14289
- active.users -= 1;
14290
- if (active.users === 0 && registry2.get(key) === active) registry2.delete(key);
14327
+ let left = false;
14328
+ return {
14329
+ identity: active,
14330
+ listen: (notify) => observe(active.semaphore, notify),
14331
+ available: () => available(active.semaphore),
14332
+ acquire: (signal) => active.semaphore.acquire(signal),
14333
+ release: () => active.semaphore.release(),
14334
+ leave: () => {
14335
+ if (left) return;
14336
+ left = true;
14337
+ active.users -= 1;
14338
+ if (active.users === 0 && registry2.get(key) === active) registry2.delete(key);
14339
+ }
14291
14340
  };
14292
- try {
14293
- await active.semaphore.acquire(signal);
14294
- } catch (error) {
14295
- leave();
14296
- throw error;
14341
+ }
14342
+
14343
+ // src/http/transport-admission.ts
14344
+ var KEY = /* @__PURE__ */ Symbol.for("node-autotask.transport-admission.v2");
14345
+ var root2 = globalThis;
14346
+ var coordinator = root2[KEY] ??= { ready: { rows: [], available: () => true }, dirty: /* @__PURE__ */ new Set(), objects: /* @__PURE__ */ new Map(), signals: /* @__PURE__ */ new WeakMap(), sequence: 0, draining: false, batching: 0 };
14347
+ function subscribe(signal, aborted) {
14348
+ let queue = coordinator.signals.get(signal);
14349
+ if (queue === void 0) {
14350
+ const callbacks = /* @__PURE__ */ new Set();
14351
+ queue = { callbacks, listener: () => {
14352
+ coordinator.signals.delete(signal);
14353
+ coordinator.batching += 1;
14354
+ try {
14355
+ for (const callback of callbacks) callback();
14356
+ } finally {
14357
+ coordinator.batching -= 1;
14358
+ drain();
14359
+ }
14360
+ } };
14361
+ coordinator.signals.set(signal, queue);
14362
+ signal.addEventListener("abort", queue.listener, { once: true });
14297
14363
  }
14298
- let released = false;
14364
+ const shared = queue;
14365
+ shared.callbacks.add(aborted);
14299
14366
  return () => {
14300
- if (released) return;
14301
- released = true;
14302
- active.semaphore.release();
14303
- leave();
14367
+ shared.callbacks.delete(aborted);
14368
+ if (shared.callbacks.size === 0) {
14369
+ coordinator.signals.delete(signal);
14370
+ signal.removeEventListener("abort", shared.listener);
14371
+ }
14372
+ };
14373
+ }
14374
+ function earlier(a, b) {
14375
+ return a.head.sequence < b.head.sequence;
14376
+ }
14377
+ function swap(heap, a, b) {
14378
+ const rows = heap.rows;
14379
+ [rows[a], rows[b]] = [rows[b], rows[a]];
14380
+ rows[a].index = a;
14381
+ rows[b].index = b;
14382
+ }
14383
+ function remove(pair) {
14384
+ const heap = pair.heap;
14385
+ if (heap === void 0) return;
14386
+ const index = pair.index;
14387
+ const last = heap.rows.pop();
14388
+ pair.heap = void 0;
14389
+ if (last === pair) return;
14390
+ heap.rows[index] = last;
14391
+ last.index = index;
14392
+ let current = index;
14393
+ while (current > 0) {
14394
+ const parent = Math.floor((current - 1) / 2);
14395
+ if (!earlier(heap.rows[current], heap.rows[parent])) break;
14396
+ swap(heap, current, parent);
14397
+ current = parent;
14398
+ }
14399
+ if (current !== index) return;
14400
+ for (; ; ) {
14401
+ const left = current * 2 + 1;
14402
+ const right = left + 1;
14403
+ if (left >= heap.rows.length) break;
14404
+ const child = right < heap.rows.length && earlier(heap.rows[right], heap.rows[left]) ? right : left;
14405
+ if (!earlier(heap.rows[child], heap.rows[current])) break;
14406
+ swap(heap, current, child);
14407
+ current = child;
14408
+ }
14409
+ }
14410
+ function insert(heap, pair) {
14411
+ pair.heap = heap;
14412
+ pair.index = heap.rows.length;
14413
+ heap.rows.push(pair);
14414
+ let current = pair.index;
14415
+ while (current > 0) {
14416
+ const parent = Math.floor((current - 1) / 2);
14417
+ if (!earlier(heap.rows[current], heap.rows[parent])) break;
14418
+ swap(heap, current, parent);
14419
+ current = parent;
14420
+ }
14421
+ }
14422
+ function reconsider(pair) {
14423
+ const origin = pair.origin;
14424
+ pair.origin = void 0;
14425
+ remove(pair);
14426
+ if (origin !== void 0) coordinator.dirty.add(origin);
14427
+ if (pair.head === void 0) return false;
14428
+ if (pair.client.active >= pair.client.maxConcurrent) insert(pair.client.waiting, pair);
14429
+ else if (pair.object !== void 0 && !pair.object.gate.available()) insert(pair.object.waiting, pair);
14430
+ else {
14431
+ insert(coordinator.ready, pair);
14432
+ return true;
14433
+ }
14434
+ return false;
14435
+ }
14436
+ function unlink(ticket) {
14437
+ const pair = ticket.pair;
14438
+ if (ticket.previous !== void 0) ticket.previous.next = ticket.next;
14439
+ else pair.head = ticket.next;
14440
+ if (ticket.next !== void 0) ticket.next.previous = ticket.previous;
14441
+ else pair.tail = ticket.previous;
14442
+ ticket.previous = void 0;
14443
+ ticket.next = void 0;
14444
+ if (pair.head === void 0) pair.client.pairs.delete(pair.object?.gate.identity);
14445
+ }
14446
+ function drain() {
14447
+ if (coordinator.draining || coordinator.batching > 0) return;
14448
+ coordinator.draining = true;
14449
+ try {
14450
+ for (; ; ) {
14451
+ for (const heap of coordinator.dirty) {
14452
+ coordinator.dirty.delete(heap);
14453
+ while (heap.rows.length > 0 && heap.available()) {
14454
+ const pair2 = heap.rows[0];
14455
+ if (reconsider(pair2)) {
14456
+ pair2.origin = heap;
14457
+ break;
14458
+ }
14459
+ }
14460
+ }
14461
+ const pair = coordinator.ready.rows[0];
14462
+ if (pair === void 0) break;
14463
+ remove(pair);
14464
+ if (pair.client.active >= pair.client.maxConcurrent || pair.object !== void 0 && !pair.object.gate.available()) {
14465
+ reconsider(pair);
14466
+ continue;
14467
+ }
14468
+ const origin = pair.origin;
14469
+ pair.origin = void 0;
14470
+ if (origin !== void 0) coordinator.dirty.add(origin);
14471
+ const ticket = pair.head;
14472
+ unlink(ticket);
14473
+ ticket.grant();
14474
+ if (pair.head !== void 0) reconsider(pair);
14475
+ }
14476
+ } finally {
14477
+ coordinator.draining = false;
14478
+ }
14479
+ }
14480
+ function wake(heap) {
14481
+ coordinator.dirty.add(heap);
14482
+ drain();
14483
+ }
14484
+ function admissionClient(maxConcurrent) {
14485
+ const client = { maxConcurrent, active: 0, pairs: /* @__PURE__ */ new Map(), waiting: { rows: [], available: () => client.active < client.maxConcurrent } };
14486
+ return client;
14487
+ }
14488
+ async function acquireTransport(client, url, trackingIdentifier, signal) {
14489
+ if (signal.aborted) throw signal.reason;
14490
+ const retained = retainObjectThread(url, trackingIdentifier);
14491
+ let object = retained === void 0 ? void 0 : coordinator.objects.get(retained.identity);
14492
+ if (retained !== void 0 && object === void 0) {
14493
+ object = { gate: retained, references: 0, stop: () => void 0, waiting: { rows: [], available: () => retained.available() } };
14494
+ const shared = object;
14495
+ shared.stop = retained.listen(() => wake(shared.waiting));
14496
+ coordinator.objects.set(retained.identity, shared);
14497
+ }
14498
+ if (object !== void 0) object.references += 1;
14499
+ const drop = () => {
14500
+ retained?.leave();
14501
+ if (object !== void 0 && --object.references === 0) {
14502
+ object.stop();
14503
+ coordinator.objects.delete(object.gate.identity);
14504
+ }
14304
14505
  };
14506
+ let pair = client.pairs.get(retained?.identity);
14507
+ if (pair === void 0) {
14508
+ pair = { client, object, index: -1 };
14509
+ client.pairs.set(retained?.identity, pair);
14510
+ }
14511
+ const queue = pair;
14512
+ return new Promise((resolve, reject) => {
14513
+ let released = false;
14514
+ let unsubscribe = () => void 0;
14515
+ const leave = () => {
14516
+ if (released) return;
14517
+ released = true;
14518
+ coordinator.batching += 1;
14519
+ client.active -= 1;
14520
+ coordinator.dirty.add(client.waiting);
14521
+ try {
14522
+ retained?.release();
14523
+ } finally {
14524
+ drop();
14525
+ coordinator.batching -= 1;
14526
+ drain();
14527
+ }
14528
+ };
14529
+ const aborted = () => {
14530
+ const front = queue.head === ticket;
14531
+ if (front) remove(queue);
14532
+ unlink(ticket);
14533
+ unsubscribe();
14534
+ drop();
14535
+ reject(signal.reason);
14536
+ if (front) reconsider(queue);
14537
+ drain();
14538
+ };
14539
+ const ticket = {
14540
+ sequence: coordinator.sequence++,
14541
+ pair: queue,
14542
+ grant: () => {
14543
+ unsubscribe();
14544
+ client.active += 1;
14545
+ let acquired;
14546
+ try {
14547
+ acquired = retained?.acquire(signal) ?? Promise.resolve();
14548
+ } catch (error) {
14549
+ client.active -= 1;
14550
+ drop();
14551
+ reject(error);
14552
+ wake(client.waiting);
14553
+ return;
14554
+ }
14555
+ void acquired.then(() => {
14556
+ if (signal.aborted) {
14557
+ leave();
14558
+ reject(signal.reason);
14559
+ } else resolve(leave);
14560
+ }, (error) => {
14561
+ client.active -= 1;
14562
+ drop();
14563
+ reject(error);
14564
+ wake(client.waiting);
14565
+ });
14566
+ }
14567
+ };
14568
+ ticket.previous = queue.tail;
14569
+ if (queue.tail !== void 0) queue.tail.next = ticket;
14570
+ else queue.head = ticket;
14571
+ queue.tail = ticket;
14572
+ unsubscribe = subscribe(signal, aborted);
14573
+ if (queue.head === ticket) reconsider(queue);
14574
+ drain();
14575
+ });
14305
14576
  }
14306
14577
 
14307
14578
  // src/http/credentials.ts
@@ -14557,8 +14828,8 @@ var HttpClient = class {
14557
14828
  maxResponseBytes;
14558
14829
  /** Local hourly budget (undefined when `rateLimit.perHour` is off). */
14559
14830
  hourly;
14560
- /** FIFO semaphore bounding in-flight requests to `maxConcurrent`. */
14561
- semaphore;
14831
+ /** Client identity for atomic local/object capacity admission. */
14832
+ admission;
14562
14833
  /** Tenant 429 cooldown gate (issue #6; ON by default). */
14563
14834
  cooldownEnabled;
14564
14835
  cooldownMaxMs;
@@ -14621,7 +14892,7 @@ var HttpClient = class {
14621
14892
  this.cooldownMaxMs = config.cooldown.maxMs;
14622
14893
  this.cooldownDefaultMs = config.cooldown.defaultMs;
14623
14894
  this.maxConcurrent = config.maxConcurrent;
14624
- this.semaphore = new Semaphore(config.maxConcurrent);
14895
+ this.admission = admissionClient(config.maxConcurrent);
14625
14896
  this.timeoutMs = config.timeoutMs;
14626
14897
  this.logger = config.logger;
14627
14898
  this.redactPersonalData = config.redactPersonalData;
@@ -14828,7 +15099,7 @@ var HttpClient = class {
14828
15099
  }
14829
15100
  // ---- the attempt --------------------------------------------------------
14830
15101
  /**
14831
- * Take the hourly slot and a semaphore permit, fetch, and read the body.
15102
+ * Acquire client/object capacity together, charge the attempt, fetch and read the body.
14832
15103
  * `retry` when a network error is retriable (already waited); throws the
14833
15104
  * typed error otherwise. The permit is released on every path.
14834
15105
  */
@@ -14836,24 +15107,22 @@ var HttpClient = class {
14836
15107
  const { method, opts, ctx } = s;
14837
15108
  let release;
14838
15109
  for (; ; ) {
15110
+ let releaseThreads;
14839
15111
  try {
14840
- await this.semaphore.acquire(s.signal);
15112
+ releaseThreads = await acquireTransport(this.admission, s.url, this.auth.apiIntegrationCode, s.signal);
14841
15113
  } catch (err) {
14842
15114
  if (s.signal.aborted) throw this.interrupted(s);
14843
15115
  throw err;
14844
15116
  }
14845
- let releaseObject = () => void 0;
14846
15117
  let finishHourly = () => void 0;
14847
15118
  let released = false;
14848
15119
  const releaseCurrent = () => {
14849
15120
  if (released) return;
14850
15121
  released = true;
14851
15122
  finishHourly();
14852
- releaseObject();
14853
- this.semaphore.release();
15123
+ releaseThreads();
14854
15124
  };
14855
15125
  try {
14856
- releaseObject = await acquireObjectThread(s.url, this.auth.apiIntegrationCode, s.signal);
14857
15126
  if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
14858
15127
  this.gate(s, false);
14859
15128
  if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
@@ -15573,6 +15842,56 @@ var WORKFLOW_RESOURCES = [
15573
15842
  "projects"
15574
15843
  ];
15575
15844
 
15845
+ // src/utils/bounded.ts
15846
+ async function runBounded(fn, items, opts) {
15847
+ const { concurrency, signal, settle } = opts;
15848
+ if (!Number.isInteger(concurrency) || concurrency <= 0) {
15849
+ throw new AutotaskConfigError("batch concurrency must be a positive integer");
15850
+ }
15851
+ const results = new Array(items.length);
15852
+ let next = 0;
15853
+ let failure;
15854
+ const fail = (error, index) => {
15855
+ if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
15856
+ };
15857
+ const worker = async () => {
15858
+ while (failure === void 0 && next < items.length) {
15859
+ if (signal?.aborted) {
15860
+ fail(signal.reason, -1);
15861
+ return;
15862
+ }
15863
+ const i = next++;
15864
+ try {
15865
+ const item = items[i];
15866
+ const value = await (signal === void 0 ? fn(item) : runWithSignal(signal, () => fn(item)));
15867
+ results[i] = settle ? { status: "fulfilled", value } : value;
15868
+ } catch (error) {
15869
+ if (settle) results[i] = { status: "rejected", reason: error };
15870
+ else fail(error, i);
15871
+ }
15872
+ }
15873
+ };
15874
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
15875
+ if (failure !== void 0) throw failure.error;
15876
+ return results;
15877
+ }
15878
+ async function mapReadTasks(http, items, fn) {
15879
+ const signal = ambientCallerSignal();
15880
+ const abort = () => new AutotaskAbortError("Read fan-out aborted by the caller");
15881
+ if (signal?.aborted) throw abort();
15882
+ try {
15883
+ const results = await runBounded(fn, items, { concurrency: http === void 0 ? DEFAULT_MAX_CONCURRENT : http.maxConcurrent, orderedErrors: true, ...signal === void 0 ? {} : { signal } });
15884
+ if (signal?.aborted) throw abort();
15885
+ return results;
15886
+ } catch (error) {
15887
+ if (signal?.aborted && !(error instanceof AutotaskAbortError)) throw abort();
15888
+ throw error;
15889
+ }
15890
+ }
15891
+ function readTasks(http, tasks) {
15892
+ return mapReadTasks(http, tasks, (task) => task());
15893
+ }
15894
+
15576
15895
  // src/operations/fieldCatalog.ts
15577
15896
  var MAX_FIELD_CATALOG_WIRE = 60;
15578
15897
  var FIELD_CATALOG_HONESTY_NOTE = "Live field metadata reports the SHAPE of a field (existence, requiredness, type, maxLength, read-only, queryable, picklist-ness) as FLAGS and NAMES: picklist-ness as a flag (isPickList) and picklist field names (picklistFields). With the opt-in `labels: true`, picklist rows carry the vendor's exposed picklist VALUES (labels next to each value); without it the op serves no VALUES. It cannot resolve a picklist VALUE the vendor does not expose to this API user (a vendor-withheld picklist value): retrying the catalog will not surface a withheld value; that gap is vendor-side, not a client defect.";
@@ -15845,13 +16164,25 @@ function kindFetches(holder, resource) {
15845
16164
  udf: () => holder?.getUdfInfo?.() ?? Promise.reject(new AutotaskError(`fieldCatalog: the client exposes no getUdfInfo read for "${resource}"`, { code: "INVALID_RESPONSE", category: "server" }))
15846
16165
  };
15847
16166
  }
15848
- async function sweepResource(ctx, resource, tally) {
15849
- const { client, include, fieldsFilter, labels, fresh } = ctx;
15850
- const cache = client.http.fieldCache;
16167
+ async function readKind(ctx, resource, kind, fetch2) {
16168
+ const cache = ctx.client.http.fieldCache;
16169
+ const peek = cache !== void 0 && !ctx.fresh ? cache.peek(fieldKey(resource, kind)) : { hit: false, age: null };
16170
+ if (peek.hit && cache !== void 0) {
16171
+ return { kind, peek, outcome: { status: "fulfilled", value: cache.get(fieldKey(resource, kind)) } };
16172
+ }
16173
+ try {
16174
+ const value = await fetch2();
16175
+ return { kind, peek, outcome: { status: "fulfilled", value } };
16176
+ } catch (error) {
16177
+ if (!isAutotaskError(error) || error.code === "ABORTED") throw error;
16178
+ return { kind, peek, outcome: { status: "rejected", reason: error } };
16179
+ }
16180
+ }
16181
+ async function sweepResource(ctx, resource, tally, reads) {
16182
+ const { fieldsFilter, labels } = ctx;
15851
16183
  const fieldOp = ctx.fieldOps.get(resource);
15852
16184
  if (fieldOp === void 0) return void 0;
15853
16185
  const apiEntity = apiEntityFor(fieldOp);
15854
- const holder = client[camelKey(resource)];
15855
16186
  const row = {
15856
16187
  resource,
15857
16188
  apiEntity,
@@ -15867,8 +16198,6 @@ async function sweepResource(ctx, resource, tally) {
15867
16198
  wire: 0,
15868
16199
  error: null
15869
16200
  };
15870
- const fetches = kindFetches(holder, resource);
15871
- if (fresh) cache?.invalidate(`${resource}:`);
15872
16201
  const projectList = (kind, list) => {
15873
16202
  const projected = list.map((f) => projectFieldRow(f, labels, kind === "udf"));
15874
16203
  if (kind === "fields") applyFieldsFilter(projected, fieldsFilter, row);
@@ -15877,28 +16206,18 @@ async function sweepResource(ctx, resource, tally) {
15877
16206
  };
15878
16207
  let allCached = true;
15879
16208
  const ages = [];
15880
- for (const kind of include) {
15881
- const peek = cache !== void 0 && !fresh ? cache.peek(fieldKey(resource, kind)) : { hit: false, age: null };
15882
- if (peek.hit !== true) allCached = false;
15883
- if (peek.hit === true && cache !== void 0) {
15884
- const value2 = cache.get(fieldKey(resource, kind));
15885
- if (kind === "info") row.info = value2 ?? null;
15886
- else projectList(kind, Array.isArray(value2) ? value2 : []);
15887
- if (peek.age !== null) ages.push(peek.age);
15888
- continue;
15889
- }
15890
- let value;
15891
- try {
15892
- value = await fetches[kind]();
15893
- } catch (err) {
15894
- if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16209
+ for (const { kind, peek, outcome } of reads) {
16210
+ if (!peek.hit) {
16211
+ allCached = false;
15895
16212
  tally.wireUsed += 1;
15896
16213
  row.wire += 1;
15897
- if (row.error === null) row.error = { code: err.code, message: err.message };
16214
+ } else if (peek.age !== null) ages.push(peek.age);
16215
+ if (outcome.status === "rejected") {
16216
+ const error = outcome.reason;
16217
+ if (row.error === null) row.error = { code: error.code, message: error.message };
15898
16218
  continue;
15899
16219
  }
15900
- tally.wireUsed += 1;
15901
- row.wire += 1;
16220
+ const value = outcome.value;
15902
16221
  if (kind === "info") {
15903
16222
  row.info = value ?? null;
15904
16223
  } else {
@@ -15943,9 +16262,20 @@ async function fieldCatalog(client, opts) {
15943
16262
  const zone = client.config.zone ?? "unknown";
15944
16263
  const rows = [];
15945
16264
  const tally = { wireUsed: 0, anyPicklistValues: false };
15946
- const ctx = { client, include, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
16265
+ const ctx = { client, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
15947
16266
  for (const resource of targets) {
15948
- const row = await sweepResource(ctx, resource, tally);
16267
+ apiEntityFor(fieldOps.get(resource));
16268
+ if (ctx.fresh) cache?.invalidate(`${resource}:`);
16269
+ }
16270
+ const tasks = targets.flatMap((resource) => {
16271
+ const holder = client[camelKey(resource)];
16272
+ const fetches = kindFetches(holder, resource);
16273
+ return include.map((kind) => ({ resource, kind, fetch: fetches[kind] }));
16274
+ });
16275
+ const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2 }) => readKind(ctx, resource, kind, fetch2));
16276
+ for (let index = 0; index < targets.length; index += 1) {
16277
+ const start = index * include.length;
16278
+ const row = await sweepResource(ctx, targets[index], tally, reads.slice(start, start + include.length));
15949
16279
  if (row !== void 0) rows.push(row);
15950
16280
  }
15951
16281
  const result = {
@@ -16128,56 +16458,6 @@ function entityNameFromPath(resourcePath) {
16128
16458
  return snake;
16129
16459
  }
16130
16460
 
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
16461
  // src/operations/nameSnapshot.ts
16182
16462
  function nameRecordSnapshot(cache, path, id, operation) {
16183
16463
  const body = cache?.get(path);
@@ -16714,27 +16994,27 @@ function subscriberError(error, operation) {
16714
16994
  };
16715
16995
  return copyValue(error);
16716
16996
  }
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 });
16997
+ function cachedRead(http, cache, key, path, operation, request, fresh, shouldStore) {
16998
+ if (cache === void 0) return request();
16720
16999
  let ownsLoader = false;
16721
17000
  const loader = (signal) => {
16722
17001
  ownsLoader = true;
16723
- return http.request({ method: "GET", path, operation, signal });
17002
+ return request(signal);
16724
17003
  };
16725
17004
  const options = {
16726
17005
  signal: ambientCallerSignal(),
16727
17006
  fresh,
17007
+ shouldStore,
16728
17008
  abortError: () => new AutotaskAbortError(`Request aborted: GET ${path}`, {
16729
17009
  operation,
16730
17010
  suggestedAction: "The caller aborted; re-issue the call if still needed."
16731
17011
  })
16732
17012
  };
16733
- return cache.load(path, loader, options).catch((error) => {
17013
+ return cache.load(key, loader, options).catch((error) => {
16734
17014
  if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
16735
17015
  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 });
17016
+ const warm = cache.get(key);
17017
+ return warm !== void 0 ? warm : cache.load(key, loader, { ...options, fresh: true });
16738
17018
  }).catch((error) => {
16739
17019
  if (!(error instanceof AutotaskError)) throw error;
16740
17020
  const failure = subscriberError(error, operation);
@@ -16742,6 +17022,33 @@ function cachedRecordGet(http, path, operation, fresh = false) {
16742
17022
  throw failure;
16743
17023
  });
16744
17024
  }
17025
+ function cachedRecordGet(http, path, operation, fresh = false) {
17026
+ return cachedRead(
17027
+ http,
17028
+ http.readCache,
17029
+ path,
17030
+ path,
17031
+ operation,
17032
+ (signal) => http.request({ method: "GET", path, operation, signal }),
17033
+ fresh
17034
+ );
17035
+ }
17036
+ function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh = false, maxRetries) {
17037
+ const cache = http.fieldCache;
17038
+ const request = (signal) => {
17039
+ return http.request({ method: "GET", path, operation, signal, maxRetries }).then(unwrap).catch((error) => {
17040
+ if (error instanceof AutotaskError && (error.code === "INVALID_RESPONSE" || error.details?.deterministic === true)) {
17041
+ cache?.invalidate(`${resource}:`);
17042
+ }
17043
+ throw error;
17044
+ });
17045
+ };
17046
+ return cachedRead(http, cache, fieldKey(resource, kind), path, operation, request, fresh, (value) => {
17047
+ if (value === null || value === void 0) return false;
17048
+ if (Array.isArray(value)) return value.length > 0;
17049
+ return typeof value !== "object" || Object.keys(value).length > 0;
17050
+ });
17051
+ }
16745
17052
 
16746
17053
  // src/field-sets.ts
16747
17054
  var MODEL_FIELD_SETS = {
@@ -16954,6 +17261,19 @@ async function boundedPart(http, path, conditions, limit, operation, includeFiel
16954
17261
  return { items, capped, hasMore: capped && pageDetails.nextPageUrl != null };
16955
17262
  }
16956
17263
 
17264
+ // src/utils/model-fields.ts
17265
+ var lookups = /* @__PURE__ */ new Map();
17266
+ function modelFieldLookup(resourceKey) {
17267
+ if (!Object.hasOwn(MODEL_FIELD_SETS, resourceKey)) return void 0;
17268
+ let lookup = lookups.get(resourceKey);
17269
+ if (lookup === void 0) {
17270
+ const names = new Set(MODEL_FIELD_SETS[resourceKey]);
17271
+ lookup = (field) => names.has(field);
17272
+ lookups.set(resourceKey, lookup);
17273
+ }
17274
+ return lookup;
17275
+ }
17276
+
16957
17277
  // src/resources/special/_shared/relation-filters.ts
16958
17278
  var JOIN_SET_CAP = 300;
16959
17279
  function capJoinSet(ids2, cap = JOIN_SET_CAP) {
@@ -16967,8 +17287,8 @@ var RELATION_TARGETS = {
16967
17287
  project: { resource: "projects", path: "/V1.0/Projects/query" }
16968
17288
  };
16969
17289
  function relationsFor(resourceKey) {
16970
- const fields = MODEL_FIELD_SETS[resourceKey] ?? [];
16971
- return Object.keys(RELATION_TARGETS).filter((rel) => fields.includes(`${rel}ID`));
17290
+ const hasField = modelFieldLookup(resourceKey);
17291
+ return Object.keys(RELATION_TARGETS).filter((rel) => hasField?.(`${rel}ID`) === true);
16972
17292
  }
16973
17293
  function selfPrefixes(resourceKey) {
16974
17294
  const rels = Object.keys(RELATION_TARGETS).filter((rel) => RELATION_TARGETS[rel].resource === resourceKey);
@@ -17013,7 +17333,7 @@ function validateRelationLeaves(resourceKey, conditions, op) {
17013
17333
  if (rest.length > 0 || !sub) fail("is not <relation>.<field> (multi-hop relations are not supported)");
17014
17334
  if (!valid.includes(rel)) fail(`names an unknown relation for ${resourceKey} (valid: ${valid.join(", ") || "none"})`);
17015
17335
  const parentFields = MODEL_FIELD_SETS[RELATION_TARGETS[rel].resource];
17016
- if (parentFields !== void 0 && !parentFields.includes(sub)) {
17336
+ if (parentFields !== void 0 && modelFieldLookup(RELATION_TARGETS[rel].resource)?.(sub) !== true) {
17017
17337
  fail(`names a field unknown on ${RELATION_TARGETS[rel].resource}`);
17018
17338
  }
17019
17339
  }
@@ -17024,36 +17344,52 @@ async function rewriteRelationFilters(http, resourceKey, conditions, op) {
17024
17344
  if (!hasRelationConditions(conditions)) return void 0;
17025
17345
  const conds = conditions;
17026
17346
  validateRelationLeaves(resourceKey, conds, op);
17347
+ const parentReads = /* @__PURE__ */ new Map();
17027
17348
  const parentIds = async (rel, leaves) => {
17028
17349
  const target = RELATION_TARGETS[rel];
17029
17350
  const parentConds = buildFilter(leaves.map((l) => ({ ...l, field: l.field.slice(rel.length + 1) }))).filter;
17030
- const res = await boundedPart(http, target.path, parentConds, JOIN_SET_CAP, op, ["id"]);
17031
- if (res.hasMore) {
17032
- throw new AutotaskConfigError(
17033
- `${op}: the ${rel}.* conditions match more than ${JOIN_SET_CAP} ${target.resource} \u2014 the ${resourceKey} query was not issued (a partial ${rel} set would give partial results)`,
17034
- { operation: op, suggestedAction: `Narrow the ${rel}.* conditions (e.g. add a ${rel} date or status condition) or filter ${resourceKey} by ${rel}ID directly.` }
17035
- );
17351
+ const key = JSON.stringify([target.path, parentConds], (_key, value) => isRecord2(value) ? Object.fromEntries(Object.keys(value).sort().map((name) => [name, value[name]])) : value);
17352
+ let pending = parentReads.get(key);
17353
+ if (pending === void 0) {
17354
+ pending = (async () => {
17355
+ const res = await boundedPart(http, target.path, parentConds, JOIN_SET_CAP, op, ["id"]);
17356
+ if (res.hasMore) {
17357
+ throw new AutotaskConfigError(
17358
+ `${op}: the ${rel}.* conditions match more than ${JOIN_SET_CAP} ${target.resource} \u2014 the ${resourceKey} query was not issued (a partial ${rel} set would give partial results)`,
17359
+ { operation: op, suggestedAction: `Narrow the ${rel}.* conditions (e.g. add a ${rel} date or status condition) or filter ${resourceKey} by ${rel}ID directly.` }
17360
+ );
17361
+ }
17362
+ return capJoinSet(res.items.map((r) => Number(r.id)).filter((n) => Number.isFinite(n) && n > 0)).ids;
17363
+ })();
17364
+ parentReads.set(key, pending);
17036
17365
  }
17037
- return capJoinSet(res.items.map((r) => Number(r.id)).filter((n) => Number.isFinite(n) && n > 0)).ids;
17366
+ return [...await pending];
17038
17367
  };
17039
17368
  const NEVER = null;
17369
+ const rewriteLeaf = async (c) => {
17370
+ const [rel, field] = c.field.split(".");
17371
+ if (selfPrefixes(resourceKey).includes(rel)) return { ...c, field };
17372
+ const ids2 = await parentIds(rel, [c]);
17373
+ return ids2.length === 0 ? void 0 : { field: `${rel}ID`, op: "in", value: ids2 };
17374
+ };
17040
17375
  const rewrite = async (list, mode) => {
17376
+ if (mode === "or" && !list.some((c) => Array.isArray(c.items) && hasRelationConditions(c.items))) {
17377
+ const parts = await mapReadTasks(http, list, (c) => isRelationLeaf(c) ? rewriteLeaf(c) : Promise.resolve(c));
17378
+ const out2 = parts.filter((c) => c !== void 0);
17379
+ return out2.length === 0 ? NEVER : out2;
17380
+ }
17041
17381
  const out = [];
17042
17382
  const byRel = /* @__PURE__ */ new Map();
17043
17383
  for (const c of list) {
17044
17384
  if (isRelationLeaf(c)) {
17045
17385
  const parts = c.field.split(".");
17046
- if (parts.length === 2 && selfPrefixes(resourceKey).includes(parts[0])) {
17047
- out.push({ ...c, field: parts[1] });
17386
+ if (mode === "or" || parts.length === 2 && selfPrefixes(resourceKey).includes(parts[0])) {
17387
+ const leaf = await rewriteLeaf(c);
17388
+ if (leaf !== void 0) out.push(leaf);
17048
17389
  continue;
17049
17390
  }
17050
17391
  const rel = parts[0];
17051
- if (mode === "and") {
17052
- byRel.set(rel, [...byRel.get(rel) ?? [], c]);
17053
- continue;
17054
- }
17055
- const ids2 = await parentIds(rel, [c]);
17056
- if (ids2.length > 0) out.push({ field: `${rel}ID`, op: "in", value: ids2 });
17392
+ byRel.set(rel, [...byRel.get(rel) ?? [], c]);
17057
17393
  continue;
17058
17394
  }
17059
17395
  if (isRecord2(c) && (c.op === "and" || c.op === "or") && Array.isArray(c.items) && hasRelationConditions(c.items)) {
@@ -17090,6 +17426,17 @@ var ROW_FK_TABLES = {
17090
17426
  billingCodeID: "billingCode"
17091
17427
  };
17092
17428
  var isResourceFkField = (field) => field === "resourceID" || field.endsWith("ResourceID");
17429
+ function rowNamePlan(rows, resourceKey, picklistFields = []) {
17430
+ const builder = createNamePlan(picklistFields, resourceKey);
17431
+ for (const row of rows) {
17432
+ for (const [field, value] of Object.entries(row)) {
17433
+ const table = ROW_FK_TABLES[field];
17434
+ if (table !== void 0) builder.addFk(table, value);
17435
+ else if (isResourceFkField(field)) builder.addResource(value);
17436
+ }
17437
+ }
17438
+ return builder.plan();
17439
+ }
17093
17440
  var LABEL_NAME_MAX_CHARS = 200;
17094
17441
  function untrustedName(name) {
17095
17442
  if (name === null) return null;
@@ -17108,8 +17455,8 @@ async function labelRows(client, resourceKey, rows) {
17108
17455
  for (const row of rows) for (const k of Object.keys(row)) keys.add(k);
17109
17456
  if (keys.size === 0) return { rows: [...rows] };
17110
17457
  let picklistFields = [];
17111
- const modelFields = MODEL_FIELD_SETS[resourceKey] ?? [];
17112
- const candidates = [...keys].filter((f) => f !== "id" && modelFields.includes(f) && ROW_FK_TABLES[f] === void 0 && !isResourceFkField(f));
17458
+ const modelHas = modelFieldLookup(resourceKey);
17459
+ const candidates = [...keys].filter((f) => f !== "id" && modelHas?.(f) === true && ROW_FK_TABLES[f] === void 0 && !isResourceFkField(f));
17113
17460
  if (candidates.length > 0) {
17114
17461
  try {
17115
17462
  const catalog = await fieldCatalog(client, { resources: [resourceKey], labels: true });
@@ -17123,16 +17470,7 @@ async function labelRows(client, resourceKey, rows) {
17123
17470
  }
17124
17471
  const labelled = (field) => picklistFields.includes(field) || ROW_FK_TABLES[field] !== void 0 || isResourceFkField(field);
17125
17472
  if (![...keys].some(labelled)) return { rows: [...rows] };
17126
- const builder = createNamePlan(picklistFields, resourceKey);
17127
- for (const row of rows) {
17128
- for (const [field, value] of Object.entries(row)) {
17129
- const table = ROW_FK_TABLES[field];
17130
- if ((value === 0 || value === "0") && table !== "company") continue;
17131
- if (table !== void 0) builder.addFk(table, value);
17132
- else if (isResourceFkField(field)) builder.addResource(value);
17133
- }
17134
- }
17135
- const plan = builder.plan();
17473
+ const plan = rowNamePlan(rows, resourceKey, picklistFields);
17136
17474
  const names = plan.resourceIds.length === 0 && plan.recordFks.length === 0 && picklistFields.length === 0 ? void 0 : await resolveCompositeNames(client.http, plan);
17137
17475
  const out = rows.map((row) => {
17138
17476
  const r = { ...row };
@@ -17160,16 +17498,34 @@ async function labelFetchResults(client, result) {
17160
17498
  if (r.found && r.value !== null) byResource2.set(r.resource, [...byResource2.get(r.resource) ?? [], i]);
17161
17499
  });
17162
17500
  const results = [...result.results];
17501
+ const groups = [...byResource2].map(([resource, indices]) => ({ resource, indices, rows: indices.map((i) => results[i].value) }));
17502
+ const seen = /* @__PURE__ */ new Set();
17503
+ let dependent = false;
17504
+ for (const group of groups) {
17505
+ const plan = rowNamePlan(group.rows, group.resource);
17506
+ const targets = [...plan.resourceIds.map((id) => `resource:${String(id)}`), ...plan.recordFks.map((fk2) => `${fk2.table}:${String(fk2.id)}`)];
17507
+ for (const target of targets) {
17508
+ if (seen.has(target)) dependent = true;
17509
+ seen.add(target);
17510
+ }
17511
+ }
17512
+ const labelledGroups = /* @__PURE__ */ new Map();
17513
+ const labelled = await mapReadTasks(
17514
+ dependent ? { maxConcurrent: 1 } : client.http,
17515
+ groups,
17516
+ async (group) => ({ resource: group.resource, result: await labelRows(client, group.resource, group.rows) })
17517
+ );
17518
+ for (const group of labelled) labelledGroups.set(group.resource, group.result);
17163
17519
  const notes = [];
17164
17520
  const reasons = {};
17165
17521
  for (const [resource, indices] of byResource2) {
17166
- const labelled = await labelRows(client, resource, indices.map((i) => results[i].value));
17522
+ const labelled2 = labelledGroups.get(resource);
17167
17523
  indices.forEach((idx, j) => {
17168
- results[idx] = { ...results[idx], value: labelled.rows[j] };
17524
+ results[idx] = { ...results[idx], value: labelled2.rows[j] };
17169
17525
  });
17170
- if (labelled.names !== void 0) {
17171
- notes.push(labelled.names.note);
17172
- for (const [field, why] of Object.entries(labelled.names.reasons ?? {})) reasons[field] = why;
17526
+ if (labelled2.names !== void 0) {
17527
+ notes.push(labelled2.names.note);
17528
+ for (const [field, why] of Object.entries(labelled2.names.reasons ?? {})) reasons[field] = why;
17173
17529
  }
17174
17530
  }
17175
17531
  if (notes.length === 0) return { ...result, results };
@@ -17759,8 +18115,8 @@ var MetaBase = class extends QueryBase {
17759
18115
  return cachedRecordGet(this.http, path, operation, fresh);
17760
18116
  }
17761
18117
  /**
17762
- * Entity-metadata read through the opt-in field cache (issue #31; off by
17763
- * default: with no fieldCache this is exactly one `http.request` — the
18118
+ * Entity-metadata read through the default-on field cache (issue #31;
18119
+ * with no fieldCache this is exactly one `http.request` — the
17764
18120
  * bit-for-bit uncached trio path). One private helper beside `cachedGet`,
17765
18121
  * for the same three reasons the read cache exists: a vendor drift
17766
18122
  * (deterministic 500, INVALID_RESPONSE) must not be served stale, repeat
@@ -17768,7 +18124,9 @@ var MetaBase = class extends QueryBase {
17768
18124
  * duplicate requests. The UNWRAPPED value is stored (never the raw
17769
18125
  * envelope); an EMPTY or FAILED result is never cached (a failure
17770
18126
  * rejects before any `set`; an empty is refused by the cache itself);
17771
- * concurrent callers share ONE in-flight wire request; the drift signal
18127
+ * concurrent callers share one wire with independent cancellation and cloned
18128
+ * values; invalidation detaches older reads before they can repopulate
18129
+ * the cache. The drift signal
17772
18130
  * (the INVALID_RESPONSE shape drift, the deterministic validation 500)
17773
18131
  * invalidates THIS entity's entries so the next call refetches
17774
18132
  * (transport-level signals are also invalidated in the transport's own
@@ -17777,29 +18135,7 @@ var MetaBase = class extends QueryBase {
17777
18135
  * @internal
17778
18136
  */
17779
18137
  async cachedMeta(kind, path, operation, unwrap, fresh = false) {
17780
- const cache = this.http.fieldCache;
17781
- if (cache === void 0) {
17782
- const res = await this.http.request({ method: "GET", path, operation });
17783
- return unwrap(res);
17784
- }
17785
- const key = fieldKey(this.config.key, kind);
17786
- if (!fresh) {
17787
- const shared = cache.inflight(key);
17788
- if (shared !== void 0) return shared;
17789
- const hit = cache.get(key);
17790
- if (hit !== void 0) return hit;
17791
- }
17792
- const work = this.http.request({ method: "GET", path, operation }).then((body) => {
17793
- const value = unwrap(body);
17794
- if (!isEmpty(value)) cache.set(key, value);
17795
- return value;
17796
- });
17797
- work.catch((err) => {
17798
- if (err instanceof AutotaskError && (err.code === "INVALID_RESPONSE" || err.details?.deterministic === true)) {
17799
- cache.invalidate(`${this.config.key}:`);
17800
- }
17801
- });
17802
- return cache.track(key, work);
18138
+ return cachedMetadataGet(this.http, this.config.key, kind, path, operation, unwrap, fresh);
17803
18139
  }
17804
18140
  /** `GET /V1.0/<E>/{id}` → `{ item }` unwrapped (`item: null` → NotFoundError). */
17805
18141
  async getGlobal(id, fresh = false) {
@@ -18105,8 +18441,8 @@ var MetaBase = class extends QueryBase {
18105
18441
  );
18106
18442
  }
18107
18443
  const leaf = fields.map((field) => ({ field, op: "eq", value }));
18108
- const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18109
- const items = await this.queryPage1([root2], 2);
18444
+ const root3 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18445
+ const items = await this.queryPage1([root3], 2);
18110
18446
  if (items.length === 1) {
18111
18447
  return { value: items[0], resolutionCost: "server-filter", scanned: 0, scanTruncated: false };
18112
18448
  }
@@ -18273,7 +18609,7 @@ var MetaBase = class extends QueryBase {
18273
18609
  }
18274
18610
  const limit = opts.limit === void 0 ? 25 : clampPageSize(opts.limit);
18275
18611
  const leaf = fields.map((field) => ({ field, op: "contains", value: text }));
18276
- const root2 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18612
+ const root3 = leaf.length === 1 ? leaf[0] : { op: "or", items: leaf };
18277
18613
  for (const key of Object.keys(opts)) {
18278
18614
  if (key !== "limit" && key !== "companyID" && key !== "includeFields") {
18279
18615
  throw new AutotaskConfigError(`search: unknown opts key "${key}" \u2014 the bag is closed: limit, companyID, includeFields`);
@@ -18287,7 +18623,7 @@ var MetaBase = class extends QueryBase {
18287
18623
  }
18288
18624
  const companyID = opts.companyID === void 0 ? void 0 : Number(opts.companyID);
18289
18625
  const includeFields = opts.includeFields === void 0 ? void 0 : opts.includeFields.includes("id") ? opts.includeFields : ["id", ...opts.includeFields];
18290
- const conditions = companyID === void 0 ? [root2] : [{ field: "companyID", op: "eq", value: companyID }, root2];
18626
+ const conditions = companyID === void 0 ? [root3] : [{ field: "companyID", op: "eq", value: companyID }, root3];
18291
18627
  const rows = await this.queryEntity(`${this.resourcePath}/query`, conditions, {
18292
18628
  maxRecords: limit,
18293
18629
  ...includeFields !== void 0 ? { includeFields } : {}
@@ -18318,11 +18654,6 @@ var MetaBase = class extends QueryBase {
18318
18654
  return this.searchBase(value, { limit });
18319
18655
  }
18320
18656
  };
18321
- function isEmpty(value) {
18322
- if (value === null || value === void 0) return true;
18323
- if (Array.isArray(value)) return value.length === 0;
18324
- return typeof value === "object" && Object.keys(value).length === 0;
18325
- }
18326
18657
 
18327
18658
  // src/resources/base/mutations.ts
18328
18659
  var MutationBase = class extends MetaBase {
@@ -20560,20 +20891,20 @@ var GenericResource = class extends BaseResource {
20560
20891
  this.requireHelper("getContext");
20561
20892
  const cfg = this.config;
20562
20893
  const rootField = cfg.contextRootField ?? this.config.key;
20563
- const root2 = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20564
- const result = { [rootField]: root2 };
20894
+ const root3 = await this.fetchRecordRaw(this.config.resourcePath, id, cfg.contextRootFresh === true);
20895
+ const result = { [rootField]: root3 };
20565
20896
  const parts = cfg.contextParts ?? [];
20566
- const values = await mapReadTasks(this.http, parts, ([, idField, targetPath]) => this.contextFetch(targetPath, root2[idField]));
20897
+ const values = await mapReadTasks(this.http, parts, ([, idField, targetPath]) => this.contextFetch(targetPath, root3[idField]));
20567
20898
  for (const [i, [name]] of parts.entries()) result[name] = values[i];
20568
20899
  if (opts.names === true) {
20569
20900
  const builder = createNamePlan();
20570
20901
  for (const sib of cfg.nameSiblings ?? []) {
20571
- const fk2 = root2[sib.field];
20902
+ const fk2 = root3[sib.field];
20572
20903
  if (sib.kind === "resource") builder.addResource(fk2);
20573
20904
  else builder.addFk(sib.kind, fk2);
20574
20905
  }
20575
20906
  const names = await resolveCompositeNames(this.http, builder.plan(), { maxNameReads: opts.maxNameReads });
20576
- const row = { ...root2 };
20907
+ const row = { ...root3 };
20577
20908
  for (const sib of cfg.nameSiblings ?? []) {
20578
20909
  addNameSibling(row, sib.field, (v) => sib.kind === "resource" ? names.resourceName(v) : names.recordName(sib.kind, v));
20579
20910
  }
@@ -20853,12 +21184,14 @@ function readIncludeNames(record, includeFields) {
20853
21184
  return names;
20854
21185
  }
20855
21186
  function resolveAuthority(record, live) {
20856
- if (live !== null) return { known: live, authority: "the tenant's live entity field metadata" };
21187
+ if (live !== null) return { known: live, authority: "the tenant's live entity field metadata", hasField: (name) => live.includes(name) };
20857
21188
  const vendored = MODEL_FIELD_SETS[record.resource];
21189
+ const modelHas = modelFieldLookup(record.resource);
20858
21190
  const liveOnlyExempt = Array.isArray(record.metadata?.liveOnlyFields) ? record.metadata.liveOnlyFields : [];
20859
- if (vendored === void 0) return void 0;
21191
+ if (vendored === void 0 || modelHas === void 0) return void 0;
20860
21192
  return {
20861
21193
  known: [...vendored, ...liveOnlyExempt],
21194
+ hasField: (name) => modelHas(name) || liveOnlyExempt.includes(name),
20862
21195
  authority: liveOnlyExempt.length > 0 ? "the vendored spec (src/field-sets.ts) + the plan-pinned live-only fields (exempt from the vendored refusal)" : "the vendored spec (src/field-sets.ts)"
20863
21196
  };
20864
21197
  }
@@ -20908,8 +21241,8 @@ async function findUnknownFieldNames(record, holder, lists) {
20908
21241
  const resolved = resolveAuthority(record, await liveFieldNames(holder));
20909
21242
  if (resolved === void 0) return void 0;
20910
21243
  const unknown = {};
20911
- for (const [key, names] of Object.entries(lists)) unknown[key] = [...new Set(names.filter((name) => !resolved.known.includes(name)))];
20912
- return { ...resolved, unknown };
21244
+ for (const [key, names] of Object.entries(lists)) unknown[key] = [...new Set(names.filter((name) => !resolved.hasField(name)))];
21245
+ return { known: resolved.known, authority: resolved.authority, unknown };
20913
21246
  }
20914
21247
 
20915
21248
  // src/resources/special/_shared/ticketStatus.ts
@@ -20929,25 +21262,13 @@ function picklistOf(fields) {
20929
21262
  return out;
20930
21263
  }
20931
21264
  async function readFields(http, fresh) {
20932
- const cache = http.fieldCache;
20933
- const key = fieldKey("tickets", "fields");
20934
- if (!fresh && cache !== void 0) {
20935
- const shared = cache.inflight(key);
20936
- if (shared !== void 0) return await shared;
20937
- const hit = cache.get(key);
20938
- if (hit !== void 0) return hit;
20939
- }
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 });
21265
+ return cachedMetadataGet(http, "tickets", "fields", "/V1.0/Tickets/entityInformation/fields", OP, (res) => {
20943
21266
  const fields = res?.fields;
20944
21267
  if (!Array.isArray(fields)) {
20945
21268
  throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
20946
21269
  }
20947
- if (fields.length > 0) cache?.set(key, fields, epoch);
20948
21270
  return fields;
20949
- })();
20950
- return cache !== void 0 && !fresh ? cache.track(key, work) : work;
21271
+ }, fresh, 0);
20951
21272
  }
20952
21273
  function assumed(allowAssumed, operation) {
20953
21274
  if (!allowAssumed) {
@@ -21037,7 +21358,8 @@ function validateProjection(fields) {
21037
21358
  const names = [...new Set(list)];
21038
21359
  const entity = PART_ENTITY[part];
21039
21360
  const known = MODEL_FIELD_SETS[entity] ?? [];
21040
- const unknown = names.filter((n) => !known.includes(n));
21361
+ const hasField = modelFieldLookup(entity);
21362
+ const unknown = names.filter((n) => hasField?.(n) !== true);
21041
21363
  if (unknown.length > 0) {
21042
21364
  throw new AutotaskConfigError(
21043
21365
  `fullProfile: fields.${part} has unknown field name(s) ${formatUnknownNameList(unknown)} against the vendored spec for ${entity} (${known.length} fields; operations.fieldCatalog resources: ["${entity}"] lists the live set) \u2014 no request was issued`
@@ -21308,7 +21630,7 @@ async function prepareCrmWrite(resource, input) {
21308
21630
  if (input.intent === "create_company" && status !== "matched") {
21309
21631
  const eff = effectiveRequiredFields(null, RELATIONSHIP_MAP.companies?.zoneFacts);
21310
21632
  const research = (f) => ["companyType", "ownerResourceID", "countryID"].includes(f) ? "lookup" : "web_if_available_else_ask";
21311
- const lookups = {
21633
+ const lookups2 = {
21312
21634
  companyType: { via: "operations.fieldCatalog", resource: "companies", field: "companyType", labels: true, note: "map the user wording to one returned label; never hardcode ids" },
21313
21635
  ownerResourceID: { via: "resources.get / the staff resolver", note: "owners cannot be enumerated on a blind surface: take a known resource id and confirm it with resources.get" },
21314
21636
  countryID: { via: "countries.query", note: "resolve the country name to an id; never guess" }
@@ -21319,7 +21641,7 @@ async function prepareCrmWrite(resource, input) {
21319
21641
  ];
21320
21642
  for (const [f, source] of wanted) {
21321
21643
  if (has(co[f]) || needsInput.some((n) => n.field === f)) continue;
21322
- needsInput.push({ field: f, why: source === "policy" ? `CRM policy: a new company needs ${f} (the vendor auto-creates a "Primary Address" location from it)` : `the vendor requires ${f} to create a company`, source, ...lookups[f] ? { lookup: lookups[f] } : {}, research: research(f) });
21644
+ needsInput.push({ field: f, why: source === "policy" ? `CRM policy: a new company needs ${f} (the vendor auto-creates a "Primary Address" location from it)` : `the vendor requires ${f} to create a company`, source, ...lookups2[f] ? { lookup: lookups2[f] } : {}, research: research(f) });
21323
21645
  }
21324
21646
  }
21325
21647
  if (input.intent === "add_contact") {
@@ -21874,10 +22196,10 @@ var CompaniesResource = class extends GenericResource {
21874
22196
  * fetch; no sub-lists; absent/dangling references come back null). */
21875
22197
  async getContext(id) {
21876
22198
  const company = await this.fetchRecordRaw("/V1.0/Companies", id);
21877
- const root2 = company;
22199
+ const root3 = company;
21878
22200
  const [ownerResource, parentCompany] = await readTasks(this.http, [
21879
- () => this.contextFetch("/V1.0/Resources", root2["ownerResourceID"]),
21880
- () => this.contextFetch("/V1.0/Companies", root2["parentCompanyID"])
22201
+ () => this.contextFetch("/V1.0/Resources", root3["ownerResourceID"]),
22202
+ () => this.contextFetch("/V1.0/Companies", root3["parentCompanyID"])
21881
22203
  ]);
21882
22204
  return { company, ownerResource, parentCompany };
21883
22205
  }
@@ -22145,6 +22467,14 @@ var DEFAULT_LIMIT2 = 25;
22145
22467
  function resourceFor(client, key) {
22146
22468
  return client[camelKey(key)];
22147
22469
  }
22470
+ function searchable(client, key) {
22471
+ const holder = resourceFor(client, key);
22472
+ return holder !== void 0 && typeof holder.search === "function" && (typeof holder.hasSearch !== "function" || holder.hasSearch()) ? holder : void 0;
22473
+ }
22474
+ async function searchRows(holder, text, limit) {
22475
+ const matches = await holder.search(text, { limit });
22476
+ return Array.isArray(matches) ? matches.filter((m) => typeof m === "object" && m !== null) : [];
22477
+ }
22148
22478
  async function searchAcrossResources(client, query, opts = {}) {
22149
22479
  const text = query.trim();
22150
22480
  if (text === "") {
@@ -22161,12 +22491,23 @@ async function searchAcrossResources(client, query, opts = {}) {
22161
22491
  }
22162
22492
  const results = [];
22163
22493
  const skipped = [];
22494
+ if (totalLimit === void 0) {
22495
+ const completed = await mapReadTasks(client.http, keys, async (key) => {
22496
+ const holder = searchable(client, key);
22497
+ return holder === void 0 ? void 0 : { resource: key, matches: await searchRows(holder, text, limit) };
22498
+ });
22499
+ completed.forEach((row, i) => {
22500
+ if (row === void 0) skipped.push(keys[i]);
22501
+ else results.push(row);
22502
+ });
22503
+ return { query: text, results, skipped };
22504
+ }
22164
22505
  const notSearched = [];
22165
- let remaining = totalLimit ?? Infinity;
22506
+ let remaining = totalLimit;
22166
22507
  let hitQuota = false;
22167
22508
  for (const key of keys) {
22168
- const holder = resourceFor(client, key);
22169
- if (holder === void 0 || typeof holder.search !== "function" || typeof holder.hasSearch === "function" && !holder.hasSearch()) {
22509
+ const holder = searchable(client, key);
22510
+ if (holder === void 0) {
22170
22511
  skipped.push(key);
22171
22512
  continue;
22172
22513
  }
@@ -22175,14 +22516,12 @@ async function searchAcrossResources(client, query, opts = {}) {
22175
22516
  continue;
22176
22517
  }
22177
22518
  const ask = Math.min(limit, remaining);
22178
- const matches = await holder.search(text, { limit: ask });
22179
- const rows = Array.isArray(matches) ? matches.filter((m) => typeof m === "object" && m !== null).map((m) => m) : [];
22180
- if (totalLimit !== void 0) rows.length = Math.min(rows.length, ask);
22519
+ const rows = await searchRows(holder, text, ask);
22520
+ rows.length = Math.min(rows.length, ask);
22181
22521
  results.push({ resource: key, matches: rows });
22182
22522
  remaining -= rows.length;
22183
22523
  if (rows.length === ask) hitQuota = true;
22184
22524
  }
22185
- if (totalLimit === void 0) return { query: text, results, skipped };
22186
22525
  return { query: text, results, skipped, notSearched, truncated: notSearched.length > 0 || hitQuota };
22187
22526
  }
22188
22527
 
@@ -22214,11 +22553,10 @@ async function resolveAny(client, identifier, opts = {}) {
22214
22553
  }
22215
22554
  const configuredCap = Math.min(client.config?.resolution?.maxScanRecords ?? 500, 500);
22216
22555
  const limit = Math.min(opts.limit ?? configuredCap, configuredCap);
22217
- const results = [];
22218
- for (const key of keys) {
22556
+ const results = await mapReadTasks(client.http, keys, async (key) => {
22219
22557
  const holder = resourceFor2(client, key);
22220
22558
  if (holder === void 0 || typeof holder.resolveDetailed !== "function") {
22221
- results.push({
22559
+ return {
22222
22560
  resource: key,
22223
22561
  value: null,
22224
22562
  resolutionCost: missCost(identifier),
@@ -22226,8 +22564,7 @@ async function resolveAny(client, identifier, opts = {}) {
22226
22564
  scanTruncated: false,
22227
22565
  candidates: [],
22228
22566
  error: "NO_RESOLVE"
22229
- });
22230
- continue;
22567
+ };
22231
22568
  }
22232
22569
  try {
22233
22570
  const r = await holder.resolveDetailed(identifier);
@@ -22239,7 +22576,7 @@ async function resolveAny(client, identifier, opts = {}) {
22239
22576
  scanTruncated: r.scanTruncated,
22240
22577
  candidates: (r.candidates ?? []).map((c) => c.id)
22241
22578
  };
22242
- results.push(outcome);
22579
+ return outcome;
22243
22580
  } catch (err) {
22244
22581
  let code;
22245
22582
  let candidates = [];
@@ -22254,7 +22591,7 @@ async function resolveAny(client, identifier, opts = {}) {
22254
22591
  } else {
22255
22592
  throw err;
22256
22593
  }
22257
- results.push({
22594
+ return {
22258
22595
  resource: key,
22259
22596
  value: null,
22260
22597
  resolutionCost: missCost(identifier),
@@ -22262,9 +22599,9 @@ async function resolveAny(client, identifier, opts = {}) {
22262
22599
  scanTruncated: code === "RESOLUTION_TRUNCATED",
22263
22600
  candidates,
22264
22601
  error: code
22265
- });
22602
+ };
22266
22603
  }
22267
- }
22604
+ });
22268
22605
  const cleanMiss = results.every((r) => r.value === null && r.candidates.length === 0 && !r.scanTruncated && (r.error === void 0 || r.error === "NOT_FOUND"));
22269
22606
  if (match === "auto" && typeof identifier === "string" && !/^\d+$/.test(identifier.trim()) && cleanMiss) {
22270
22607
  const contains = await searchAcrossResources(client, identifier, { resources: keys, limit });
@@ -22831,6 +23168,7 @@ var shortName = (operation) => operation.split(".").pop() ?? operation;
22831
23168
  // src/operations/fetchByIds.ts
22832
23169
  var FETCH_BY_IDS_MAX_ITEMS = 500;
22833
23170
  var FETCH_BY_IDS_CHUNK_SIZE = 250;
23171
+ var itemKey = (resource, id) => `${resource}:${String(id)}`;
22834
23172
  function project2(value, fields) {
22835
23173
  const out = {};
22836
23174
  for (const f of fields) {
@@ -22884,7 +23222,8 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
22884
23222
  }
22885
23223
  const resourceKey = item.resource;
22886
23224
  const fields = MODEL_FIELD_SETS[resourceKey];
22887
- if (fields === void 0) {
23225
+ const hasField = modelFieldLookup(resourceKey);
23226
+ if (fields === void 0 || hasField === void 0) {
22888
23227
  problems.push(
22889
23228
  `${at}.resource: "${resourceKey}" is not a single-record GETtable resource (${Object.keys(MODEL_FIELD_SETS).length} known) \u2014 see autotask_catalog for the exact plan keys`
22890
23229
  );
@@ -22919,7 +23258,7 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
22919
23258
  continue;
22920
23259
  }
22921
23260
  for (const f of item.fields) {
22922
- if (!fields.includes(f)) {
23261
+ if (!hasField(f)) {
22923
23262
  problems.push(
22924
23263
  `${at}.fields: "${f}" is not a field of ${resourceKey} \u2014 a hallucinated field is a shape error, not a silent projection-miss (exact vendor field names via operations.fieldCatalog)`
22925
23264
  );
@@ -22959,7 +23298,7 @@ async function fetchByIds(client, items, opts = {}) {
22959
23298
  groups.set(item.resource, g);
22960
23299
  }
22961
23300
  const byKey2 = /* @__PURE__ */ new Map();
22962
- for (const [key, group] of groups) {
23301
+ const plans = [...groups].map(([key, group]) => {
22963
23302
  const holder = client[camelKey(key)];
22964
23303
  if (holder === void 0) {
22965
23304
  throw new AutotaskConfigError(`fetchByIds: the client exposes no accessor for resource "${key}"`, {
@@ -22977,7 +23316,10 @@ async function fetchByIds(client, items, opts = {}) {
22977
23316
  }
22978
23317
  }
22979
23318
  const includeFields = group.anyFields && group.indices.every((i) => items[i].fields !== void 0) ? [...group.fields] : void 0;
22980
- const kOf = (id) => `${key}:${String(id)}`;
23319
+ const kOf = (id) => itemKey(key, id);
23320
+ return { key, holder, resourcePath, unique, includeFields, kOf };
23321
+ });
23322
+ await mapReadTasks(client.http, plans, async ({ key, resourcePath, unique, includeFields, kOf }) => {
22981
23323
  const foundRows = await fetchIdChunks(client.http, resourcePath, unique, includeFields, `${key}.fetchByIds`, {
22982
23324
  chunkSize: FETCH_BY_IDS_CHUNK_SIZE,
22983
23325
  maxRecords: FETCH_BY_IDS_CHUNK_SIZE,
@@ -22996,30 +23338,30 @@ async function fetchByIds(client, items, opts = {}) {
22996
23338
  const q = kOf(k);
22997
23339
  if (!byKey2.has(q)) byKey2.set(q, { found: true, value: row });
22998
23340
  }
22999
- for (const id of unique) {
23000
- const k = kOf(id);
23001
- if (byKey2.has(k)) continue;
23002
- try {
23003
- const value = await holder.get(id);
23004
- byKey2.set(k, { found: true, value });
23005
- } catch (err) {
23006
- if (err instanceof NotFoundError) {
23007
- byKey2.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
23008
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
23009
- const e = { code: err.code, message: err.message };
23010
- if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
23011
- byKey2.set(k, { found: false, value: null, error: e });
23012
- } else {
23013
- throw err;
23014
- }
23341
+ });
23342
+ const missing = plans.flatMap((plan) => plan.unique.filter((id) => !byKey2.has(plan.kOf(id))).map((id) => ({ plan, id })));
23343
+ await mapReadTasks(client.http, missing, async ({ plan: { holder, kOf }, id }) => {
23344
+ const k = kOf(id);
23345
+ try {
23346
+ const value = await holder.get(id);
23347
+ byKey2.set(k, { found: true, value });
23348
+ } catch (err) {
23349
+ if (err instanceof NotFoundError) {
23350
+ byKey2.set(k, { found: false, value: null, error: { code: "NOT_FOUND", message: err.message } });
23351
+ } else if (isAutotaskError(err) && err.code !== "ABORTED") {
23352
+ const e = { code: err.code, message: err.message };
23353
+ if (err.httpStatus !== void 0) e.httpStatus = err.httpStatus;
23354
+ byKey2.set(k, { found: false, value: null, error: e });
23355
+ } else {
23356
+ throw err;
23015
23357
  }
23016
23358
  }
23017
- }
23359
+ });
23018
23360
  const results = [];
23019
23361
  for (let i = 0; i < items.length; i += 1) {
23020
23362
  const item = items[i];
23021
23363
  const id = canonical[i];
23022
- const out = byKey2.get(`${item.resource}:${String(id)}`);
23364
+ const out = byKey2.get(itemKey(item.resource, id));
23023
23365
  const value = out.found ? item.fields !== void 0 ? project2(out.value, item.fields) : out.value : null;
23024
23366
  results.push(
23025
23367
  out.found ? { resource: item.resource, id, found: true, value } : { resource: item.resource, id, found: false, value: null, error: out.error }
@@ -24361,17 +24703,17 @@ async function fetchCharges(ctx) {
24361
24703
  const raw = await ctx.readPart("/V1.0/ContractCharges/query", chargesCond, ["id", "chargeType", "billableAmount", "extendedCost", "unitCost", "unitPrice", "unitQuantity", "datePurchased", "isBilled", "status", "contractServiceID"]);
24362
24704
  return { charges: raw.items, chargesPart: stampPart("contract_charges", raw, chargesCond) };
24363
24705
  }
24364
- async function fetchBlocks(ctx, root2) {
24365
- if (!root2.isBlockHours) {
24706
+ async function fetchBlocks(ctx, root3) {
24707
+ if (!root3.isBlockHours) {
24366
24708
  return skipPart(
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)`
24709
+ root3.contractTypeKnown ? `skipped: not a Block Hours contract (contractType ${root3.contractType} "${root3.contractTypeLabel}") \u2014 included hours apply to hour blocks only (zero wire)` : `skipped: the contract type is unknown (contractType ${root3.contractType || "absent"}; label unresolved) \u2014 included hours are not evaluable (zero wire)`
24368
24710
  );
24369
24711
  }
24370
24712
  const blocksCond = [{ field: "contractID", op: "eq", value: ctx.id }];
24371
24713
  const raw = await ctx.readPart("/V1.0/ContractBlocks/query", blocksCond, ["id", "datePurchased", "startDate", "endDate", "hours", "hoursApproved", "status", "isPaid"]);
24372
24714
  return stampPart("contract_blocks", raw, blocksCond);
24373
24715
  }
24374
- async function fetchContractState(ctx, root2) {
24716
+ async function fetchContractState(ctx, root3) {
24375
24717
  const servicesCond = [{ field: "contractID", op: "eq", value: ctx.id }];
24376
24718
  const unitsCond = [{ field: "contractID", op: "eq", value: ctx.id }, ...ctx.windowOn("startDate")];
24377
24719
  const roleCostsCond = [{ field: "contractID", op: "eq", value: ctx.id }];
@@ -24382,7 +24724,7 @@ async function fetchContractState(ctx, root2) {
24382
24724
  () => fetchCharges(ctx),
24383
24725
  () => ctx.readPart("/V1.0/ContractRoleCosts/query", roleCostsCond, ["id", "rate", "resourceID", "roleID"]),
24384
24726
  () => ctx.readPart("/V1.0/ContractRates/query", ratesCond, ["id", "roleID", "contractHourlyRate", "internalCurrencyContractHourlyRate"]),
24385
- () => fetchBlocks(ctx, root2)
24727
+ () => fetchBlocks(ctx, root3)
24386
24728
  ]);
24387
24729
  return { servicesRaw, servicesCond, unitRows: units.rows, unitsPartRaw: units.part, chargesPart, charges, roleCostsRaw, roleCostsCond, ratesRaw, ratesCond, blocksPart };
24388
24730
  }
@@ -24747,7 +25089,7 @@ async function fetchSubscriptionsJoin(ctx) {
24747
25089
 
24748
25090
  // src/resources/special/contracts/profitability.data.ts
24749
25091
  async function gather(ctx) {
24750
- const root2 = await fetchRoot(ctx);
25092
+ const root3 = await fetchRoot(ctx);
24751
25093
  const stages = Object.fromEntries(
24752
25094
  ["state", "billing", "time", "activity", "open", "res", "join", "subs"].map((name) => [name, forkFetchCtx(ctx)])
24753
25095
  );
@@ -24758,7 +25100,7 @@ async function gather(ctx) {
24758
25100
  let openRead;
24759
25101
  const openTask = () => openRead ??= fetchOpenTickets(stages.open);
24760
25102
  const tasks = {
24761
- state: () => fetchContractState(stages.state, root2),
25103
+ state: () => fetchContractState(stages.state, root3),
24762
25104
  billing: () => fetchBilling(stages.billing),
24763
25105
  time: timeTask,
24764
25106
  activity: activityTask,
@@ -24777,7 +25119,7 @@ async function gather(ctx) {
24777
25119
  const completed = await mapReadTasks(ctx.http, order, async (name) => [name, await tasks[name]()]);
24778
25120
  const parts = Object.fromEntries(completed);
24779
25121
  mergeFetchContexts(ctx, Object.values(stages));
24780
- return { root: root2, ...parts };
25122
+ return { root: root3, ...parts };
24781
25123
  }
24782
25124
  function stampListParts(v, f) {
24783
25125
  const { state: state2, activity, join } = f;
@@ -27642,7 +27984,7 @@ async function fullProfile2(resource, id, opts = {}) {
27642
27984
  const serviceLimit = compositePartLimit(opts.serviceLimit, "serviceLimit", OP12);
27643
27985
  const billingRuleLimit = compositePartLimit(opts.billingRuleLimit, "billingRuleLimit", OP12);
27644
27986
  const contractId = parseIdentifier(id, "id");
27645
- const root2 = await invokeRead(client, "contracts.get", [contractId]);
27987
+ const root3 = await invokeRead(client, "contracts.get", [contractId]);
27646
27988
  const [services, billingRules, charges, units] = await readTasks(resource.http, [
27647
27989
  () => compositePart(client, "contract_services.query", [
27648
27990
  { filter: [{ field: "contractID", op: "eq", value: contractId }], limit: serviceLimit }
@@ -27658,7 +28000,7 @@ async function fullProfile2(resource, id, opts = {}) {
27658
28000
  ])
27659
28001
  ]);
27660
28002
  return {
27661
- root: root2,
28003
+ root: root3,
27662
28004
  parts: {
27663
28005
  services,
27664
28006
  billing_rules: billingRules,