node-autotask 0.86.0 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/MCP_TOOL_CATALOG.json +152 -9
  3. package/README.md +1 -1
  4. package/capabilities.json +714 -194
  5. package/dist/capabilities-data.js +713 -193
  6. package/dist/capabilities.cjs +4 -4
  7. package/dist/capabilities.js +1 -1
  8. package/dist/{chunk-SZ33SCCI.cjs → chunk-AB326MJO.cjs} +200 -200
  9. package/dist/{chunk-BD4AUGCJ.cjs → chunk-CM5O672I.cjs} +5 -4
  10. package/dist/{chunk-23LTWBKP.cjs → chunk-ESKQAINP.cjs} +31 -30
  11. package/dist/{chunk-YX6SSS4I.cjs → chunk-GEFUSYH5.cjs} +739 -378
  12. package/dist/{chunk-ELZTECDS.js → chunk-K72PPAAD.js} +726 -365
  13. package/dist/{chunk-AZ54RMQR.js → chunk-LGOJ2HBH.js} +3 -2
  14. package/dist/{chunk-DVD7RZIB.js → chunk-QKRHKLVY.js} +2 -2
  15. package/dist/{chunk-EYRQUMA2.cjs → chunk-SHJ7EOBW.cjs} +3 -3
  16. package/dist/{chunk-7NKB4UXV.js → chunk-X6VWD6WW.js} +5 -4
  17. package/dist/{chunk-KYFJOIG4.js → chunk-ZADTVF6M.js} +3 -3
  18. package/dist/{index-B3zO78nP.d.ts → index-BFgZJsqx.d.ts} +19 -13
  19. package/dist/{index-CIgmz8qI.d.cts → index-D0KHVqoO.d.cts} +37 -3
  20. package/dist/{index-CIgmz8qI.d.ts → index-D0KHVqoO.d.ts} +37 -3
  21. package/dist/{index-C2p8D2mZ.d.cts → index-DsA1-2GA.d.cts} +19 -13
  22. package/dist/index.cjs +90 -87
  23. package/dist/index.d.cts +4 -3
  24. package/dist/index.d.ts +4 -3
  25. package/dist/index.js +9 -6
  26. package/dist/operations/index.cjs +53 -53
  27. package/dist/operations/index.d.cts +4 -4
  28. package/dist/operations/index.d.ts +4 -4
  29. package/dist/operations/index.js +3 -3
  30. package/dist/pool.cjs +13 -13
  31. package/dist/pool.d.cts +1 -1
  32. package/dist/pool.d.ts +1 -1
  33. package/dist/pool.js +5 -5
  34. package/dist/resources/index.cjs +28 -28
  35. package/dist/resources/index.d.cts +2 -2
  36. package/dist/resources/index.d.ts +2 -2
  37. package/dist/resources/index.js +4 -4
  38. package/dist/types/index.d.cts +1 -1
  39. package/dist/types/index.d.ts +1 -1
  40. package/dist/untrusted.cjs +11 -11
  41. package/dist/untrusted.d.cts +1 -1
  42. package/dist/untrusted.d.ts +1 -1
  43. package/dist/untrusted.js +1 -1
  44. package/docs/API.md +6 -2
  45. package/docs/VENDOR-QUIRKS.md +34 -17
  46. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkEYRQUMA2_cjs = require('./chunk-EYRQUMA2.cjs');
4
- var chunkBD4AUGCJ_cjs = require('./chunk-BD4AUGCJ.cjs');
3
+ var chunkSHJ7EOBW_cjs = require('./chunk-SHJ7EOBW.cjs');
4
+ var chunkCM5O672I_cjs = require('./chunk-CM5O672I.cjs');
5
5
  var crypto = require('crypto');
6
6
  var async_hooks = require('async_hooks');
7
7
 
@@ -328,7 +328,7 @@ function redactResponseBody(value, policy) {
328
328
  const out = {};
329
329
  for (const [key, entry] of Object.entries(value)) {
330
330
  const pinned = SECRET_SET.has(key) || personal && OPTIONAL_SET.has(key);
331
- out[key] = pinned ? chunkBD4AUGCJ_cjs.REDACTED : redactResponseBody(entry, policy);
331
+ out[key] = pinned ? chunkCM5O672I_cjs.REDACTED : redactResponseBody(entry, policy);
332
332
  }
333
333
  return out;
334
334
  }
@@ -1412,7 +1412,7 @@ function resolveConfig(config) {
1412
1412
  }
1413
1413
  labels = config.labels;
1414
1414
  }
1415
- const logger = config.logger ?? chunkBD4AUGCJ_cjs.NoopLogger;
1415
+ const logger = config.logger ?? chunkCM5O672I_cjs.NoopLogger;
1416
1416
  if (credentials.baseUrl.startsWith("http:")) {
1417
1417
  const host = new URL(credentials.baseUrl).host;
1418
1418
  logger.warn?.(
@@ -1492,7 +1492,7 @@ function redactAuditBody(value) {
1492
1492
  if (!isRecord2(value)) return value;
1493
1493
  const out = {};
1494
1494
  for (const [key, entry] of Object.entries(value)) {
1495
- out[key] = CREDENTIAL_KEY_RE.test(key) ? chunkBD4AUGCJ_cjs.REDACTED : redactAuditBody(entry);
1495
+ out[key] = CREDENTIAL_KEY_RE.test(key) ? chunkCM5O672I_cjs.REDACTED : redactAuditBody(entry);
1496
1496
  }
1497
1497
  return out;
1498
1498
  }
@@ -1694,13 +1694,13 @@ function normalizeInCondition(cond, path) {
1694
1694
  return items === cond.items ? cond : { ...cond, items };
1695
1695
  }
1696
1696
  if (cond.op !== "in" && cond.op !== "notIn" || typeof cond.value !== "string") return cond;
1697
- const tokens = cond.value.split(",").map((t) => t.trim()).filter((t) => t.length > 0);
1698
- if (tokens.length === 0) {
1697
+ const tokens2 = cond.value.split(",").map((t) => t.trim()).filter((t) => t.length > 0);
1698
+ if (tokens2.length === 0) {
1699
1699
  throw new AutotaskConfigError(
1700
1700
  `Operator "${cond.op}" at ${path} has an empty value list \u2014 pass an array or a comma-separated string with at least one value (e.g. "1,2,3")`
1701
1701
  );
1702
1702
  }
1703
- const value = cond.udf === true ? tokens : tokens.map((t) => /^(0|[1-9]\d*)$/.test(t) && Number.isSafeInteger(Number(t)) ? Number(t) : t);
1703
+ const value = cond.udf === true ? tokens2 : tokens2.map((t) => /^(0|[1-9]\d*)$/.test(t) && Number.isSafeInteger(Number(t)) ? Number(t) : t);
1704
1704
  return { ...cond, value };
1705
1705
  }
1706
1706
  function refusedFilterShape(filter) {
@@ -10938,6 +10938,59 @@ var RELATIONSHIP_MAP = {
10938
10938
  },
10939
10939
  "deleteBoundary": null,
10940
10940
  "markerField": null
10941
+ },
10942
+ "inventory_locations": {
10943
+ "resource": "inventory_locations",
10944
+ "apiEntity": "InventoryLocation",
10945
+ "kind": "entity",
10946
+ "path": "InventoryLocations",
10947
+ "parentScoped": false,
10948
+ "tier": "extended",
10949
+ "workflowResource": false,
10950
+ "group": "A",
10951
+ "parent": null,
10952
+ "children": [],
10953
+ "naturalKeys": {
10954
+ "hasSearch": false,
10955
+ "searchCovers": null,
10956
+ "findBy": []
10957
+ },
10958
+ "blindSurfaces": null,
10959
+ "zoneFacts": {
10960
+ "createRequiredSet": [
10961
+ "locationName",
10962
+ "isActive"
10963
+ ],
10964
+ "createGuidance": {
10965
+ "createOp": "inventory_locations.create",
10966
+ "parentScoped": false,
10967
+ "liveProvenPrefix": [],
10968
+ "unproven": true,
10969
+ "blocker": {
10970
+ "kind": "unknown",
10971
+ "message": "Inventory location creation requires Inventory permissions and a unique locationName; not live verified.",
10972
+ "remedy": "Read current metadata, supply locationName and isActive, and preview first.",
10973
+ "requires": {
10974
+ "allOf": [
10975
+ "locationName",
10976
+ "isActive"
10977
+ ]
10978
+ }
10979
+ },
10980
+ "vendorEvidence": [
10981
+ "https://www.autotask.net/help/developerhelp/Content/APIs/REST/Entities/InventoryLocationsEntity.htm"
10982
+ ],
10983
+ "deleteBoundary": {
10984
+ "available": false,
10985
+ "note": "The vendor defines no DELETE for inventory_locations (spec-derived); a created inventory location cannot be removed through the public API."
10986
+ }
10987
+ }
10988
+ },
10989
+ "deleteBoundary": {
10990
+ "note": "The vendor defines no DELETE for inventory_locations (spec-derived); a created inventory location cannot be removed through the public API.",
10991
+ "proof": "spec-derived"
10992
+ },
10993
+ "markerField": null
10941
10994
  }
10942
10995
  };
10943
10996
  var BLIND_SURFACE_STAMPS = {
@@ -11049,7 +11102,8 @@ var DELETE_BOUNDARY_NOTES = {
11049
11102
  "user_defined_field_definitions": "the vendor defines no DELETE for user_defined_field_definitions (spec-derived: the vendored api-docs.json defines no DELETE on the entity's paths) \u2014 a UDF definition cannot be deleted through the API; deactivation is via isActive (vendor soft-removal); hard cleanup is UI-only.",
11050
11103
  "user_defined_field_list_items": "the vendor defines no DELETE for user_defined_field_list_items (spec-derived: the vendored api-docs.json defines no DELETE on the standalone or parent-scoped ListItems paths) \u2014 a picklist value cannot be deleted through the API; deactivation is via isActive (vendor soft-removal); hard cleanup is UI-only.",
11051
11104
  "task_notes": "The vendor defines no DELETE for task_notes (spec-derived); a created task note cannot be removed through the public API.",
11052
- "time_off_requests": "The vendor defines no DELETE for time-off requests; cancel through time_off_requests.update using the Canceled status from exposed field metadata. Cancellation is leave management, not timesheet unposting."
11105
+ "time_off_requests": "The vendor defines no DELETE for time-off requests; cancel through time_off_requests.update using the Canceled status from exposed field metadata. Cancellation is leave management, not timesheet unposting.",
11106
+ "inventory_locations": "The vendor defines no DELETE for inventory_locations (spec-derived); a created inventory location cannot be removed through the public API."
11053
11107
  };
11054
11108
  var RESPONSE_DRIFT_MARKERS = {
11055
11109
  "ticket_checklist_libraries": {
@@ -12485,6 +12539,15 @@ var EMPTY_REASON_STAMPS = {
12485
12539
  "authority": null,
12486
12540
  "remedy": "verify the created record by id (ticket_checklist_libraries.get) \u2014 the create may have succeeded despite the drifted envelope"
12487
12541
  }
12542
+ },
12543
+ "inventory_locations": {
12544
+ "get": {
12545
+ "surface": "inventory_locations.get",
12546
+ "kind": "tenant-empty-for-user",
12547
+ "note": "No inventory location at this ID was visible to this API user. This is INCONCLUSIVE about tenant inventory because visibility may be limited by Inventory module access and permissions.",
12548
+ "authority": "inventory_locations.get",
12549
+ "remedy": "Verify the ID and check View permission, Inventory access and Inventory Manage Locations with an authorized user."
12550
+ }
12488
12551
  }
12489
12552
  };
12490
12553
  var POINTER_NOTES = {
@@ -13967,6 +14030,31 @@ var CREATE_GUIDANCE = {
13967
14030
  "note": null
13968
14031
  }
13969
14032
  },
14033
+ {
14034
+ "resource": "inventory_locations",
14035
+ "createOp": "inventory_locations.create",
14036
+ "parentScoped": false,
14037
+ "liveProvenPrefix": [],
14038
+ "unproven": true,
14039
+ "blocker": {
14040
+ "kind": "unknown",
14041
+ "message": "Inventory location creation requires Inventory permissions and a unique locationName; not live verified.",
14042
+ "remedy": "Read current metadata, supply locationName and isActive, and preview first.",
14043
+ "requires": {
14044
+ "allOf": [
14045
+ "locationName",
14046
+ "isActive"
14047
+ ]
14048
+ }
14049
+ },
14050
+ "vendorEvidence": [
14051
+ "https://www.autotask.net/help/developerhelp/Content/APIs/REST/Entities/InventoryLocationsEntity.htm"
14052
+ ],
14053
+ "deleteBoundary": {
14054
+ "available": false,
14055
+ "note": "The vendor defines no DELETE for inventory_locations (spec-derived); a created inventory location cannot be removed through the public API."
14056
+ }
14057
+ },
13970
14058
  {
13971
14059
  "resource": "inventory_products",
13972
14060
  "createOp": "inventory_products.create",
@@ -15547,7 +15635,7 @@ var CREATE_GUIDANCE = {
15547
15635
  }
15548
15636
  ],
15549
15637
  "counts": {
15550
- "total": 116,
15638
+ "total": 117,
15551
15639
  "byKind": {
15552
15640
  "ok": 41,
15553
15641
  "blind-reference": 16,
@@ -15557,7 +15645,7 @@ var CREATE_GUIDANCE = {
15557
15645
  "resource-role-pair": 2,
15558
15646
  "delete-absent": 0,
15559
15647
  "non-mutable": 0,
15560
- "unknown": 40
15648
+ "unknown": 41
15561
15649
  }
15562
15650
  }
15563
15651
  };
@@ -16336,6 +16424,9 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
16336
16424
  "keywords",
16337
16425
  "referenceLink",
16338
16426
  "title"
16427
+ ],
16428
+ "inventory_locations": [
16429
+ "locationName"
16339
16430
  ]
16340
16431
  };
16341
16432
 
@@ -16794,22 +16885,25 @@ function auditReadTarget(path, operation) {
16794
16885
  function isKnowledgeBaseRootResource(resource) {
16795
16886
  return resource === "knowledge_base_categories" || resource === "knowledge_base_articles";
16796
16887
  }
16797
- var KNOWLEDGE_BASE_PATH = /^\/v1\.0\/(?:KnowledgeBaseArticles|KnowledgeBaseCategories(?:\/\d+\/KnowledgeBaseArticles)?)(?:\/(query(?:\/(?:next|previous|count))?|\d+))?\/?$/i;
16798
- function knowledgeBaseResponseTarget(path, method, operation) {
16799
- const match = KNOWLEDGE_BASE_PATH.exec(path);
16888
+ function isExactRecordResource(resource) {
16889
+ return resource === "inventory_locations" || isKnowledgeBaseRootResource(resource);
16890
+ }
16891
+ var EXACT_RECORD_PATH = /^\/v1\.0\/(?:InventoryLocations|KnowledgeBaseArticles|KnowledgeBaseCategories(?:\/\d+\/KnowledgeBaseArticles)?)(?:\/(query(?:\/(?:next|previous|count))?|\d+))?\/?$/i;
16892
+ function exactRecordResponseTarget(path, method, operation) {
16893
+ const match = EXACT_RECORD_PATH.exec(path);
16800
16894
  if (match === null) return void 0;
16801
16895
  const suffix = match[1]?.toLowerCase();
16802
16896
  if (suffix === "query/count") return suffix;
16803
16897
  if (suffix?.startsWith("query")) return "query";
16804
16898
  if (suffix !== void 0 && !isAuditDecimalId(suffix)) {
16805
- throw new AutotaskConfigError("Knowledge Base record ID must be a non-negative signed 64-bit integer.", { operation });
16899
+ throw new AutotaskConfigError("Record ID must be a non-negative signed 64-bit integer.", { operation });
16806
16900
  }
16807
16901
  return method === "GET" ? suffix === void 0 ? void 0 : "item" : "mutation";
16808
16902
  }
16809
16903
  function isNonNegativeInt64(id) {
16810
16904
  return typeof id === "number" ? Number.isSafeInteger(id) && id >= 0 : typeof id === "string" && isAuditDecimalId(id);
16811
16905
  }
16812
- function validateKnowledgeBaseResponse(body, target, path, method, requestBody, operation) {
16906
+ function validateExactRecordResponse(body, target, path, method, requestBody, operation) {
16813
16907
  const invalid = (message) => {
16814
16908
  throw new AutotaskError(message, { code: "INVALID_RESPONSE", category: "server", operation, suggestedAction: INVALID_SHAPE_ACTION });
16815
16909
  };
@@ -16819,15 +16913,15 @@ function validateKnowledgeBaseResponse(body, target, path, method, requestBody,
16819
16913
  }
16820
16914
  if (target === "query") {
16821
16915
  if (!isRecord2(body) || !Array.isArray(body.items) || !isRecord2(body.pageDetails)) {
16822
- return invalid("Expected a Knowledge Base query page with paging details");
16916
+ return invalid("Expected a query page with paging details");
16823
16917
  }
16824
- if (!body.items.every(hasExactRecordId)) invalid("Expected valid record IDs in the Knowledge Base query response");
16918
+ if (!body.items.every(hasExactRecordId)) invalid("Expected valid record IDs in the query response");
16825
16919
  if (body.pageDetails.count !== body.items.length) {
16826
- invalid("The Knowledge Base page record count did not match its rows");
16920
+ invalid("The page record count did not match its rows");
16827
16921
  }
16828
16922
  const cursor = body.pageDetails.nextPageUrl;
16829
16923
  if (cursor !== null && (typeof cursor !== "string" || cursor.trim() === "")) {
16830
- invalid("Expected a valid Knowledge Base query cursor or an explicit end of results");
16924
+ invalid("Expected a valid query cursor or an explicit end of results");
16831
16925
  }
16832
16926
  return;
16833
16927
  }
@@ -16835,7 +16929,7 @@ function validateKnowledgeBaseResponse(body, target, path, method, requestBody,
16835
16929
  const expectedId = parts.at(-1);
16836
16930
  if (target === "mutation") {
16837
16931
  const id = isRecord2(body) ? body.itemId === void 0 ? body.id : body.itemId : void 0;
16838
- if (!isNonNegativeInt64(id)) invalid("Expected a valid Knowledge Base mutation receipt");
16932
+ if (!isNonNegativeInt64(id)) invalid("Expected a valid mutation receipt");
16839
16933
  const expected = method === "DELETE" ? expectedId : isRecord2(requestBody) ? requestBody.id : void 0;
16840
16934
  if (expected !== void 0 && String(id) !== String(expected)) {
16841
16935
  invalid("The mutation response identified a different record. Re-read the requested record before retrying.");
@@ -16845,9 +16939,10 @@ function validateKnowledgeBaseResponse(body, target, path, method, requestBody,
16845
16939
  const item = isRecord2(body) ? body.item : void 0;
16846
16940
  if (item === null) return;
16847
16941
  if (!isRecord2(item) || !isNonNegativeInt64(item.id)) {
16848
- return invalid("Expected a Knowledge Base item envelope with a valid record ID");
16942
+ return invalid("Expected an item envelope with a valid record ID");
16849
16943
  }
16850
- const resource = parts.at(-2)?.toLowerCase() === "knowledgebasearticles" ? "article" : "category";
16944
+ const entity = parts.at(-2)?.toLowerCase();
16945
+ const resource = entity === "inventorylocations" ? "inventory location" : entity === "knowledgebasearticles" ? "article" : "category";
16851
16946
  if (String(item.id) !== expectedId) {
16852
16947
  throw new AutotaskConfigError(`returned ${resource} id must match the requested id`, { operation });
16853
16948
  }
@@ -16861,16 +16956,16 @@ function validateKnowledgeBaseResponse(body, target, path, method, requestBody,
16861
16956
  }
16862
16957
  }
16863
16958
  }
16864
- function serializeKnowledgeBaseUpdate(body, operation) {
16959
+ function serializeExactRecordUpdate(body, operation) {
16865
16960
  if (!isRecord2(body) || typeof body.id !== "string") return JSON.stringify(body);
16866
16961
  if (!isAuditDecimalId(body.id)) {
16867
- throw new AutotaskConfigError("Knowledge Base update id must be a non-negative signed 64-bit integer.", { operation });
16962
+ throw new AutotaskConfigError("Update id must be a non-negative signed 64-bit integer.", { operation });
16868
16963
  }
16869
16964
  const { rawJSON } = JSON;
16870
16965
  return JSON.stringify({ ...body, id: rawJSON(body.id) });
16871
16966
  }
16872
- function decodeResponseJson(text, auditTarget, knowledgeBaseTarget) {
16873
- const target = auditTarget ?? knowledgeBaseTarget;
16967
+ function decodeResponseJson(text, auditTarget, recordTarget) {
16968
+ const target = auditTarget ?? recordTarget;
16874
16969
  if (target === void 0) return JSON.parse(text);
16875
16970
  if (target === "query/count") {
16876
16971
  return JSON.parse(text, (key, value, context) => key === "queryCount" && typeof value === "number" && !isAuditDecimalId(context?.source ?? "") ? null : value);
@@ -16930,9 +17025,9 @@ function attachEmptyReasonDetails(err) {
16930
17025
  const resource = err.operation.slice(0, dot);
16931
17026
  const op = err.operation.slice(dot + 1);
16932
17027
  const surface = err.operation;
16933
- const stamp = EMPTY_REASON_STAMPS[resource]?.[op];
16934
- const pointer = POINTER_NOTES[surface];
16935
17028
  const isGetMiss = err instanceof NotFoundError && op === "get";
17029
+ const stamp = op !== "get" || isGetMiss ? EMPTY_REASON_STAMPS[resource]?.[op] : void 0;
17030
+ const pointer = POINTER_NOTES[surface];
16936
17031
  if (stamp === void 0 && pointer === void 0 && !isGetMiss) return;
16937
17032
  err.details = { ...err.details ?? {} };
16938
17033
  if (stamp !== void 0) {
@@ -17044,7 +17139,7 @@ function normalizeZoneBase(raw) {
17044
17139
  return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
17045
17140
  }
17046
17141
  function canReResolveZone(reResolveZoneOn401, zone, opts) {
17047
- if (!reResolveZoneOn401) return false;
17142
+ if (!reResolveZoneOn401 || opts.checkedBaseUrl !== void 0) return false;
17048
17143
  if (zone === void 0 || zone === "other") return false;
17049
17144
  if (!opts.path.startsWith("/") || /^https?:\/\//i.test(opts.path)) return false;
17050
17145
  return true;
@@ -17437,6 +17532,7 @@ var HttpClient = class {
17437
17532
  if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
17438
17533
  this.gate(s, false);
17439
17534
  if (s.signal.aborted || Date.now() >= s.deadlineAt) throw this.interrupted(s);
17535
+ this.assertCheckedBase(opts);
17440
17536
  const admission = admitHourlyAttempt(s.url, this.hourly, Date.now());
17441
17537
  if (!admission.admitted) {
17442
17538
  releaseCurrent();
@@ -17513,13 +17609,13 @@ var HttpClient = class {
17513
17609
  }
17514
17610
  let parsed;
17515
17611
  try {
17516
- parsed = decodeResponseJson(text, s.auditTarget, s.knowledgeBaseTarget);
17612
+ parsed = decodeResponseJson(text, s.auditTarget, s.recordTarget);
17517
17613
  } catch {
17518
17614
  return this.handleNonJson2xx(s, res, status, text);
17519
17615
  }
17520
17616
  validateAuditResponse(parsed, s.auditTarget, opts.operation);
17521
- if (s.knowledgeBaseTarget !== void 0) {
17522
- validateKnowledgeBaseResponse(parsed, s.knowledgeBaseTarget, decodeURIComponent(opts.path), method, opts.body, opts.operation);
17617
+ if (s.recordTarget !== void 0) {
17618
+ validateExactRecordResponse(parsed, s.recordTarget, decodeURIComponent(opts.path), method, opts.body, opts.operation);
17523
17619
  }
17524
17620
  return {
17525
17621
  done: true,
@@ -17706,6 +17802,13 @@ var HttpClient = class {
17706
17802
  this.readCache?.clear();
17707
17803
  if (/\/V1\.0\/Companies(?:\/[^/]+)?(?:\?|$)/i.test(opts.path)) invalidateCompanyIndex(this);
17708
17804
  }
17805
+ assertCheckedBase(opts) {
17806
+ const baseUrl = this.baseUrl;
17807
+ if (opts.checkedBaseUrl !== void 0 && opts.checkedBaseUrl !== baseUrl) {
17808
+ throw new AutotaskConfigError("The Autotask zone changed after preflight. Preview or check the target again.", { operation: opts.operation });
17809
+ }
17810
+ return baseUrl;
17811
+ }
17709
17812
  /**
17710
17813
  * One request: build URL/headers, apply the whole-call deadline, retry
17711
17814
  * idempotent methods on 429/5xx, map failures to the typed errors.
@@ -17713,8 +17816,9 @@ var HttpClient = class {
17713
17816
  */
17714
17817
  async request(opts) {
17715
17818
  const method = opts.method;
17716
- const url = buildUrl(this.baseUrl, opts.path, opts.query);
17717
- const wirePath = url.slice(this.baseUrl.length);
17819
+ const baseUrl = this.assertCheckedBase(opts);
17820
+ const url = buildUrl(baseUrl, opts.path, opts.query);
17821
+ const wirePath = url.slice(baseUrl.length);
17718
17822
  const path = wirePath.split("?", 1)[0];
17719
17823
  const route = decodeURIComponent(path);
17720
17824
  const auditTarget = auditReadTarget(route, opts.operation);
@@ -17724,13 +17828,14 @@ var HttpClient = class {
17724
17828
  const queryRoute = /\/query(?:\/|$)/i.test(route);
17725
17829
  const getQuery = method === "GET" && queryRoute && requestUrl.search !== "";
17726
17830
  if (getQuery) assertGetQueryUrlLength(url);
17727
- const knowledgeBaseTarget = knowledgeBaseResponseTarget(route, method, opts.operation);
17728
- const knowledgeBaseUpdate = knowledgeBaseTarget === "mutation" && (method === "PUT" || method === "PATCH");
17729
- const bodyText = knowledgeBaseUpdate && opts.body !== void 0 ? serializeKnowledgeBaseUpdate(opts.body, opts.operation) : opts.body === void 0 ? void 0 : JSON.stringify(opts.body);
17831
+ const recordTarget = exactRecordResponseTarget(route, method, opts.operation);
17832
+ const exactRecordUpdate = recordTarget === "mutation" && (method === "PUT" || method === "PATCH");
17833
+ const bodyText = exactRecordUpdate && opts.body !== void 0 ? serializeExactRecordUpdate(opts.body, opts.operation) : opts.body === void 0 ? void 0 : JSON.stringify(opts.body);
17730
17834
  if (queryRoute) {
17731
17835
  const audit = auditTarget === "query" || auditTarget === "query/count";
17732
- const knowledgeBase = knowledgeBaseTarget === "query" || knowledgeBaseTarget === "query/count";
17733
- const exactIdLabel = audit ? "audit log" : knowledgeBase ? "Knowledge Base record" : void 0;
17836
+ const exactRecord = recordTarget === "query" || recordTarget === "query/count";
17837
+ const recordLabel = /^\/v1\.0\/InventoryLocations\//i.test(route) ? "inventory location" : "Knowledge Base record";
17838
+ const exactIdLabel = audit ? "audit log" : exactRecord ? recordLabel : void 0;
17734
17839
  assertQueryFilters(opts, requestUrl, bodyText, exactIdLabel);
17735
17840
  }
17736
17841
  opts = { ...opts, path };
@@ -17746,7 +17851,7 @@ var HttpClient = class {
17746
17851
  getQuery,
17747
17852
  method,
17748
17853
  auditTarget,
17749
- knowledgeBaseTarget,
17854
+ recordTarget,
17750
17855
  url,
17751
17856
  headers,
17752
17857
  bodyText,
@@ -18327,13 +18432,13 @@ async function runBounded(fn, items, opts) {
18327
18432
  const results = new Array(items.length);
18328
18433
  let next = 0;
18329
18434
  let failure;
18330
- const fail3 = (error, index) => {
18435
+ const fail4 = (error, index) => {
18331
18436
  if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
18332
18437
  };
18333
18438
  const worker = async () => {
18334
18439
  while (failure === void 0 && next < items.length) {
18335
18440
  if (signal?.aborted) {
18336
- fail3(signal.reason, -1);
18441
+ fail4(signal.reason, -1);
18337
18442
  return;
18338
18443
  }
18339
18444
  const i = next++;
@@ -18343,7 +18448,7 @@ async function runBounded(fn, items, opts) {
18343
18448
  results[i] = settle ? { status: "fulfilled", value } : value;
18344
18449
  } catch (error) {
18345
18450
  if (settle) results[i] = { status: "rejected", reason: error };
18346
- else fail3(error, i);
18451
+ else fail4(error, i);
18347
18452
  }
18348
18453
  }
18349
18454
  };
@@ -18399,7 +18504,7 @@ async function capabilitySets() {
18399
18504
  const fieldOps = /* @__PURE__ */ new Map();
18400
18505
  const udfCapable = /* @__PURE__ */ new Set();
18401
18506
  const resources = /* @__PURE__ */ new Set();
18402
- for (const rec of await chunkEYRQUMA2_cjs.loadCapabilityRecords()) {
18507
+ for (const rec of await chunkSHJ7EOBW_cjs.loadCapabilityRecords()) {
18403
18508
  if (rec.resource === "operations") continue;
18404
18509
  resources.add(rec.resource);
18405
18510
  if (rec.operation === "getFieldInfo") fieldOps.set(rec.resource, rec);
@@ -18410,7 +18515,7 @@ async function capabilitySets() {
18410
18515
  var derivedIndexPromise = null;
18411
18516
  function derivedIndexLoad() {
18412
18517
  if (derivedIndexPromise === null) {
18413
- derivedIndexPromise = chunkEYRQUMA2_cjs.loadCapabilityRecords().then((records) => {
18518
+ derivedIndexPromise = chunkSHJ7EOBW_cjs.loadCapabilityRecords().then((records) => {
18414
18519
  const index = /* @__PURE__ */ new Map();
18415
18520
  for (const rec of records) {
18416
18521
  const declared = rec.metadata?.derivedFields;
@@ -18831,7 +18936,7 @@ function buildDryRunResult(spec, policy = { redactPersonalData: true }) {
18831
18936
  const diffPart = spec.diff !== void 0 ? {
18832
18937
  diff: spec.diff.map((entry) => {
18833
18938
  if (entry.to === void 0) return entry;
18834
- const to = isRedactedFieldName(entry.field, policy) ? chunkBD4AUGCJ_cjs.REDACTED : redactResponseBody(entry.to, policy);
18939
+ const to = isRedactedFieldName(entry.field, policy) ? chunkCM5O672I_cjs.REDACTED : redactResponseBody(entry.to, policy);
18835
18940
  return { ...entry, to };
18836
18941
  })
18837
18942
  } : {};
@@ -19055,6 +19160,210 @@ async function expandResourceNames(client, ids2, opts = {}) {
19055
19160
  return { results, resolved, blind, failed };
19056
19161
  }
19057
19162
 
19163
+ // src/resources/special/_shared/numbers.ts
19164
+ function num(v) {
19165
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
19166
+ }
19167
+
19168
+ // src/resources/special/_shared/finance.ts
19169
+ function budgetExceededError(operation, message, details, suggestedAction) {
19170
+ return new AutotaskError(message, { code: "BUDGET_EXCEEDED", category: "policy", operation, details, suggestedAction });
19171
+ }
19172
+ function makeCallBudget(budget, onExceed) {
19173
+ let spent = 0;
19174
+ return {
19175
+ spend() {
19176
+ if (spent >= budget) throw onExceed(spent);
19177
+ spent += 1;
19178
+ },
19179
+ spent: () => spent
19180
+ };
19181
+ }
19182
+ function countingHttp(raw, spend) {
19183
+ const http = Object.create(raw);
19184
+ http.request = (o) => {
19185
+ spend();
19186
+ return raw.request(o);
19187
+ };
19188
+ return http;
19189
+ }
19190
+ function idChunks(ids2, size) {
19191
+ const out = [];
19192
+ for (let i = 0; i < ids2.length; i += size) out.push(ids2.slice(i, i + size));
19193
+ return out;
19194
+ }
19195
+ async function fetchIdChunks(http, entityPath, ids2, fields, operation, opts) {
19196
+ const chunkSize = opts?.chunkSize ?? 250;
19197
+ const out = /* @__PURE__ */ new Map();
19198
+ for (const chunk of idChunks(ids2, chunkSize)) {
19199
+ opts?.budgetSpend?.();
19200
+ const chunkKeys = new Set(chunk.map((id) => String(id)));
19201
+ try {
19202
+ const req = buildQueryRequest(http.baseUrl, entityPath, {
19203
+ filter: [{ field: "id", op: "in", value: chunk }],
19204
+ maxRecords: opts?.maxRecords ?? chunkSize,
19205
+ includeFields: fields
19206
+ });
19207
+ const res = await http.request({ ...req, operation });
19208
+ const { items: rows } = unwrapItems(res, operation);
19209
+ for (const row of rows) {
19210
+ const k = String(row["id"]);
19211
+ if (!chunkKeys.has(k)) continue;
19212
+ out.set(k, row);
19213
+ }
19214
+ } catch (err) {
19215
+ if (opts?.onChunkFault?.(chunk, err) !== true) throw err;
19216
+ }
19217
+ }
19218
+ return out;
19219
+ }
19220
+ function internalAmount(row, internalKey, localKey) {
19221
+ const v = row[internalKey];
19222
+ return typeof v === "number" && Number.isFinite(v) ? v : num(row[localKey]);
19223
+ }
19224
+ function toCents(v) {
19225
+ return Math.round(num(v) * 100);
19226
+ }
19227
+ async function readPicklists(http, entityPath, operation) {
19228
+ const res = await http.request({ method: "GET", path: `${entityPath}/entityInformation/fields`, operation });
19229
+ const body = typeof res === "object" && res !== null ? res : {};
19230
+ const fields = Array.isArray(body["fields"]) ? body["fields"] : [];
19231
+ const out = /* @__PURE__ */ new Map();
19232
+ for (const f of fields) {
19233
+ if (f["isPickList"] !== true || typeof f["name"] !== "string" || !Array.isArray(f["picklistValues"])) continue;
19234
+ const values = /* @__PURE__ */ new Map();
19235
+ for (const p of f["picklistValues"]) {
19236
+ const id = typeof p["value"] === "string" ? Number.parseInt(p["value"], 10) : Number.NaN;
19237
+ if (Number.isFinite(id)) values.set(id, String(p["label"] ?? ""));
19238
+ }
19239
+ out.set(f["name"], values);
19240
+ }
19241
+ return out;
19242
+ }
19243
+ function resolveSelector(operation, name, sel, values) {
19244
+ const out = /* @__PURE__ */ new Map();
19245
+ const misses = [];
19246
+ for (const s of sel) {
19247
+ const hits = typeof s === "number" ? values.has(s) ? [s] : [] : [...values].filter(([, l]) => l.trim().toLowerCase() === s.trim().toLowerCase()).map(([id]) => id);
19248
+ if (hits.length === 0) misses.push(JSON.stringify(s));
19249
+ for (const h of hits) out.set(h, values.get(h));
19250
+ }
19251
+ if (misses.length > 0) throw selectorUnmatched(operation, name, `${misses.join(", ")} matched no live value`, values);
19252
+ return out;
19253
+ }
19254
+ function selectorUnmatched(operation, name, what, values) {
19255
+ const live = [...values].map(([id, l]) => `${id} ${l}`).join("; ") || "(the picklist serves no values)";
19256
+ return new AutotaskConfigError(`${shortName(operation)}: ${name}: ${what}. Live values (id label): ${live}`, {
19257
+ operation,
19258
+ suggestedAction: `Pass ${name} as ids or exact labels from the live list.`
19259
+ });
19260
+ }
19261
+ var TENANT_HOURLY_LIMIT = 1e4;
19262
+ function tenantHourlyShare(calls) {
19263
+ return `${(calls / TENANT_HOURLY_LIMIT * 100).toFixed(2)}% of ${TENANT_HOURLY_LIMIT.toLocaleString("en-US")}/h`;
19264
+ }
19265
+ var isPosInt = (v) => Number.isSafeInteger(v) && v > 0;
19266
+ function checkIdList(name, v, max, problems, opts) {
19267
+ const ok = opts?.allowZero ? (x) => x === 0 || isPosInt(x) : isPosInt;
19268
+ if (!Array.isArray(v) || v.length === 0 || v.length > max || !v.every(ok)) {
19269
+ problems.push(`${name} must be a non-empty array of at most ${max} ${opts?.allowZero ? "non-negative" : "positive"} integer ids`);
19270
+ return void 0;
19271
+ }
19272
+ return [...new Set(v)].sort((a, b) => a - b);
19273
+ }
19274
+ function checkSelector(name, v, problems) {
19275
+ if (v === void 0) return void 0;
19276
+ if (!Array.isArray(v) || v.length === 0 || !v.every((x) => isPosInt(x) || typeof x === "string" && x.trim() !== "")) {
19277
+ problems.push(`${name} must be a non-empty array of picklist ids or labels`);
19278
+ return void 0;
19279
+ }
19280
+ return v;
19281
+ }
19282
+ function checkInt(name, v, def, max, problems) {
19283
+ if (v === void 0) return def;
19284
+ if (!Number.isInteger(v) || v < 1 || v > max) {
19285
+ problems.push(`${name} must be an integer 1..${max} (got ${String(v)})`);
19286
+ return def;
19287
+ }
19288
+ return v;
19289
+ }
19290
+ async function collectRows(res, filter, includeFields, page) {
19291
+ const out = [];
19292
+ for await (const r of res.query({ filter, includeFields, maxRecords: page, names: false })) out.push(r);
19293
+ return out;
19294
+ }
19295
+ function blindCountError(operation, subject, suggestedAction) {
19296
+ return new AutotaskError(`${shortName(operation)}: a gate count came back blind (unknown, not zero); ${subject} cannot be sized`, {
19297
+ code: "INVALID_RESPONSE",
19298
+ category: "server",
19299
+ operation,
19300
+ details: { reason: "blind_count" },
19301
+ suggestedAction
19302
+ });
19303
+ }
19304
+ function countMismatchError(operation, what, streamed, counted, rows) {
19305
+ const rowNote = rows !== void 0 && rows !== streamed ? ` (${rows} rows)` : "";
19306
+ return new AutotaskError(`${shortName(operation)}: the ${what} stream returned ${streamed} distinct ids${rowNote} but the gate count was ${counted} (the data changed mid-walk or a page dropped rows); the fold was discarded`, {
19307
+ code: "INVALID_RESPONSE",
19308
+ category: "server",
19309
+ operation,
19310
+ details: { reason: "count_mismatch", stream: what, streamed, counted },
19311
+ suggestedAction: "Retry the call."
19312
+ });
19313
+ }
19314
+ function compareIds(a, b) {
19315
+ for (let i = 0; i < a.length; i++) {
19316
+ const x = a[i] ?? null;
19317
+ const y = b[i] ?? null;
19318
+ if (x === y) continue;
19319
+ if (x === null) return -1;
19320
+ if (y === null) return 1;
19321
+ if (typeof x === "number" && typeof y === "number") return x - y;
19322
+ return String(x) < String(y) ? -1 : 1;
19323
+ }
19324
+ return 0;
19325
+ }
19326
+ var sortedRecord = (m) => Object.fromEntries([...m].sort((a, b) => a[0] - b[0]).map(([id, l]) => [String(id), l]));
19327
+ var shortName = (operation) => operation.split(".").pop() ?? operation;
19328
+
19329
+ // src/operations/nameBatch.ts
19330
+ var NAME_BATCH_CHUNK_SIZE = 250;
19331
+ function nameEntryKey(path) {
19332
+ return path + "\0name";
19333
+ }
19334
+ function nameEntrySnapshot(cache, path) {
19335
+ const value = cache?.get(nameEntryKey(path));
19336
+ if (value === void 0 || value === null || typeof value !== "object") return void 0;
19337
+ return () => value;
19338
+ }
19339
+ async function batchNameReads(http, entityPath, ids2, fields, operation) {
19340
+ const cache = http.readCache;
19341
+ const epoch = cache?.epoch ?? 0;
19342
+ const out = /* @__PURE__ */ new Map();
19343
+ const rows = await fetchIdChunks(http, entityPath, ids2, fields, operation, {
19344
+ chunkSize: NAME_BATCH_CHUNK_SIZE,
19345
+ maxRecords: NAME_BATCH_CHUNK_SIZE,
19346
+ onChunkFault: (chunk, err) => {
19347
+ if (!isAutotaskError(err) || err.code === "ABORTED") return false;
19348
+ const error = err.httpStatus !== void 0 ? { code: err.code, message: err.message, httpStatus: err.httpStatus } : { code: err.code, message: err.message };
19349
+ for (const id of chunk) out.set(String(id), { kind: "error", error });
19350
+ return true;
19351
+ }
19352
+ });
19353
+ for (const id of ids2) {
19354
+ const k = String(id);
19355
+ if (out.has(k)) continue;
19356
+ const record = rows.get(k);
19357
+ if (record === void 0) {
19358
+ out.set(k, { kind: "unreadable" });
19359
+ continue;
19360
+ }
19361
+ cache?.set(nameEntryKey(`${entityPath}/${k}`), record, epoch);
19362
+ out.set(k, { kind: "record", record });
19363
+ }
19364
+ return out;
19365
+ }
19366
+
19058
19367
  // src/operations/lineOfBusinessChain.ts
19059
19368
  function vendorId(value) {
19060
19369
  if (typeof value === "number") return Number.isSafeInteger(value) && value >= 1 ? value : void 0;
@@ -19135,7 +19444,7 @@ async function resolveLineOfBusinessChain(http, associationId, options) {
19135
19444
 
19136
19445
  // src/operations/compositeNames.ts
19137
19446
  var PICKLIST_VALUE_NOT_SERVED_NOTE = "The picklist is served to this API user, but this record's value is not in it (an inactive or unexposed value) \u2014 the label cannot be resolved and is null; refreshing the field catalog will not surface it. (A picklist the vendor does not expose at all is reported with the field-catalog honesty note instead.)";
19138
- var DEFAULT_MAX_NAME_READS = 20;
19447
+ var DEFAULT_MAX_NAME_READS = 50;
19139
19448
  var TICKET_LABEL_FIELDS = ["status", "priority", "ticketType", "issueType", "subIssueType", "source", "queueID"];
19140
19449
  function isVendorId(value) {
19141
19450
  if (typeof value === "number") return Number.isSafeInteger(value) && value >= 0;
@@ -19228,6 +19537,15 @@ var FK_NAME_FIELD = {
19228
19537
  product: "name",
19229
19538
  configurationItemCategory: "name"
19230
19539
  };
19540
+ var FK_BATCH_FIELDS = {
19541
+ role: ["name"],
19542
+ billingCode: ["name"],
19543
+ contract: ["contractName"],
19544
+ company: ["companyName"],
19545
+ ticket: ["ticketNumber", "title"],
19546
+ product: ["name"],
19547
+ configurationItemCategory: ["name"]
19548
+ };
19231
19549
  function fkName(record, table) {
19232
19550
  if (table === "ticket") {
19233
19551
  const parts = [record["ticketNumber"], record["title"]].filter((v) => typeof v === "string" && v.trim() !== "").map((v) => v.trim());
@@ -19252,6 +19570,8 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19252
19570
  const readCache = http.readCache;
19253
19571
  const section = { truncated: false, rows: {}, reasons: {} };
19254
19572
  let remaining = budget;
19573
+ let overBudget = 0;
19574
+ let unreadable = 0;
19255
19575
  const tasks = [];
19256
19576
  let contractLobPointer;
19257
19577
  let contractLobUnread;
@@ -19268,6 +19588,7 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19268
19588
  for (const id of overBudgetResource) {
19269
19589
  section.rows[`resource:${id}`] = { name: null, blind: false };
19270
19590
  section.truncated = true;
19591
+ overBudget += 1;
19271
19592
  }
19272
19593
  const overSet = new Set(overBudgetResource.map((id) => String(id)));
19273
19594
  const opIds = plan.resourceIds.filter((id) => !overSet.has(String(id)));
@@ -19277,6 +19598,7 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19277
19598
  for (const id of pass.slice(500)) {
19278
19599
  section.rows[`resource:${id}`] = { name: null, blind: false };
19279
19600
  section.truncated = true;
19601
+ overBudget += 1;
19280
19602
  }
19281
19603
  pass = pass.slice(0, 500);
19282
19604
  }
@@ -19305,48 +19627,89 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19305
19627
  product: client.products,
19306
19628
  configurationItemCategory: client.configurationItemCategories
19307
19629
  };
19630
+ const isLobContract = (fk2) => fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId);
19631
+ const fkRows = /* @__PURE__ */ new Map();
19632
+ const takeLobPointer = (fk2, record) => {
19633
+ if (plan.lineOfBusinessId === void 0 && isLobContract(fk2)) contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
19634
+ };
19635
+ const steps = [];
19636
+ const coldByTable = /* @__PURE__ */ new Map();
19308
19637
  for (const fk2 of plan.recordFks) {
19309
19638
  const key = `${fk2.table}:${fk2.id}`;
19310
- const snapshot = nameRecordSnapshot(readCache, `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`, fk2.id, FK_GET_OPERATION[fk2.table]);
19311
- const cold = snapshot === void 0;
19312
- if (cold) {
19313
- if (remaining < 1) {
19314
- tasks.push(async () => () => {
19315
- section.rows[key] = { name: null, blind: false };
19316
- });
19317
- section.truncated = true;
19318
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
19319
- contractLobUnread = "capped";
19320
- }
19321
- continue;
19322
- }
19323
- remaining -= 1;
19639
+ const path = `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`;
19640
+ const snapshot = nameRecordSnapshot(readCache, path, fk2.id, FK_GET_OPERATION[fk2.table]) ?? (isLobContract(fk2) ? void 0 : nameEntrySnapshot(readCache, path));
19641
+ if (snapshot !== void 0) {
19642
+ steps.push({ fk: fk2, snapshot });
19643
+ continue;
19644
+ }
19645
+ if (remaining < 1) {
19646
+ fkRows.set(key, { name: null, blind: false });
19647
+ overBudget += 1;
19648
+ section.truncated = true;
19649
+ if (isLobContract(fk2)) contractLobUnread = "capped";
19650
+ continue;
19324
19651
  }
19652
+ remaining -= 1;
19653
+ steps.push({ fk: fk2 });
19654
+ if (!isLobContract(fk2)) coldByTable.set(fk2.table, [...coldByTable.get(fk2.table) ?? [], fk2]);
19655
+ }
19656
+ const batched = /* @__PURE__ */ new Set();
19657
+ for (const { fk: fk2, snapshot } of steps) {
19658
+ const key = `${fk2.table}:${fk2.id}`;
19659
+ if (snapshot !== void 0) {
19660
+ tasks.push(async () => {
19661
+ const row = await fkRow(fk2, async () => snapshot());
19662
+ return () => {
19663
+ fkRows.set(key, row);
19664
+ };
19665
+ });
19666
+ continue;
19667
+ }
19668
+ const group = isLobContract(fk2) ? void 0 : coldByTable.get(fk2.table);
19669
+ if (group === void 0 || group.length === 1) {
19670
+ tasks.push(async () => {
19671
+ const row = await fkRow(fk2, async () => await holders[fk2.table].get(fk2.id));
19672
+ return () => {
19673
+ fkRows.set(key, row);
19674
+ };
19675
+ });
19676
+ continue;
19677
+ }
19678
+ if (batched.has(fk2.table)) continue;
19679
+ batched.add(fk2.table);
19680
+ const table = fk2.table;
19325
19681
  tasks.push(async () => {
19326
- let row;
19327
- try {
19328
- const record = snapshot !== void 0 ? snapshot() : await holders[fk2.table].get(fk2.id);
19329
- if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
19330
- contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
19331
- }
19332
- row = { name: fkName(record, fk2.table), blind: false };
19333
- } catch (err) {
19334
- if (err instanceof NotFoundError) {
19335
- row = { name: null, blind: true };
19336
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
19337
- row = { name: null, blind: false, error: faultRow(err) };
19338
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
19339
- contractLobUnread = "unresolved";
19682
+ const outcomes = await batchNameReads(http, FK_TABLE_PATH[table], group.map((g) => g.id), FK_BATCH_FIELDS[table], FK_GET_OPERATION[table].replace(/\.get$/, ".query"));
19683
+ return () => {
19684
+ for (const g of group) {
19685
+ const out = outcomes.get(String(g.id));
19686
+ const gKey = `${table}:${g.id}`;
19687
+ if (out.kind === "record") fkRows.set(gKey, { name: fkName(out.record, table), blind: false });
19688
+ else if (out.kind === "error") fkRows.set(gKey, { name: null, blind: false, error: out.error });
19689
+ else {
19690
+ fkRows.set(gKey, { name: null, blind: true, unreadable: true });
19691
+ unreadable += 1;
19340
19692
  }
19341
- } else {
19342
- throw err;
19343
19693
  }
19344
- }
19345
- return () => {
19346
- section.rows[key] = row;
19347
19694
  };
19348
19695
  });
19349
19696
  }
19697
+ async function fkRow(fk2, read) {
19698
+ try {
19699
+ const record = await read();
19700
+ takeLobPointer(fk2, record);
19701
+ return { name: fkName(record, fk2.table), blind: false };
19702
+ } catch (err) {
19703
+ if (err instanceof NotFoundError) {
19704
+ return { name: null, blind: true };
19705
+ }
19706
+ if (isAutotaskError(err) && err.code !== "ABORTED") {
19707
+ if (isLobContract(fk2)) contractLobUnread = "unresolved";
19708
+ return { name: null, blind: false, error: faultRow(err) };
19709
+ }
19710
+ throw err;
19711
+ }
19712
+ }
19350
19713
  let picklists = null;
19351
19714
  if (plan.labelFields.length > 0) {
19352
19715
  tasks.push(async () => {
@@ -19360,6 +19723,10 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19360
19723
  });
19361
19724
  }
19362
19725
  for (const merge of await readTasks(http, tasks)) merge();
19726
+ for (const fk2 of plan.recordFks) {
19727
+ const key = `${fk2.table}:${fk2.id}`;
19728
+ section.rows[key] = fkRows.get(key);
19729
+ }
19363
19730
  let lineOfBusiness2 = null;
19364
19731
  const lobId = plan.lineOfBusinessId ?? contractLobPointer;
19365
19732
  if (lobId !== void 0) {
@@ -19384,6 +19751,8 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19384
19751
  return {
19385
19752
  section,
19386
19753
  lineOfBusiness: lineOfBusiness2,
19754
+ overBudget,
19755
+ unreadable,
19387
19756
  resourceName: (id) => section.rows[`resource:${id}`]?.name ?? null,
19388
19757
  recordName: (table, id) => section.rows[`${table}:${id}`]?.name ?? null,
19389
19758
  labelFor: (field, value) => {
@@ -19425,7 +19794,24 @@ function same(sent, stored) {
19425
19794
  return String(sent) === String(stored);
19426
19795
  }
19427
19796
  function notPersistedFields(sent, stored) {
19428
- return Object.entries(sent).filter(([key, value]) => (value === null || typeof value !== "object") && stored[key] !== chunkBD4AUGCJ_cjs.REDACTED && !same(value, stored[key])).map(([key]) => key);
19797
+ return Object.entries(sent).filter(([key, value]) => (value === null || typeof value !== "object") && stored[key] !== chunkCM5O672I_cjs.REDACTED && !same(value, stored[key])).map(([key]) => key);
19798
+ }
19799
+
19800
+ // src/resources/special/inventoryLocations.ts
19801
+ var fail = (message) => {
19802
+ throw new AutotaskConfigError(`inventory_locations: ${message}`);
19803
+ };
19804
+ function admitInventoryLocation(value, creating) {
19805
+ if (!isRecord2(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail("data must be a plain record");
19806
+ const body = { ...value };
19807
+ for (const field of Object.keys(body)) if (!["locationName", "isActive"].includes(field)) fail(`${field} is not a writable InventoryLocations field`);
19808
+ if ((creating || Object.hasOwn(body, "locationName")) && (typeof body.locationName !== "string" || body.locationName.trim() === "" || body.locationName.length > 50)) fail("locationName is required and must be a nonblank string of at most 50 characters");
19809
+ if ((creating || Object.hasOwn(body, "isActive")) && typeof body.isActive !== "boolean") fail("isActive must be a boolean");
19810
+ if (!creating && !Object.keys(body).length) fail("update must contain locationName or isActive");
19811
+ return body;
19812
+ }
19813
+ function checkInventoryLocationCurrent(value, current) {
19814
+ if (value.isActive === false && current.isDefault !== false) fail("inactivation requires a fresh current isDefault value explicitly false; default or unknown locations cannot be inactivated");
19429
19815
  }
19430
19816
 
19431
19817
  // src/resources/base/types.ts
@@ -19594,6 +19980,7 @@ var MODEL_FIELD_SETS = {
19594
19980
  "expense_reports": ["id", "amountDue", "approvedDate", "approverID", "departmentNumber", "internalCurrencyCashAdvanceAmount", "internalCurrencyExpenseTotal", "name", "organizationalLevelAssociationID", "quickBooksReferenceNumber", "reimbursementCurrencyAmountDue", "reimbursementCurrencyCashAdvanceAmount", "reimbursementCurrencyID", "rejectionReason", "status", "submit", "submitDate", "submitterID", "weekEnding"],
19595
19981
  "holiday_sets": ["id", "holidaySetDescription", "holidaySetName"],
19596
19982
  "holidays": ["id", "holidayDate", "holidayName", "holidaySetID", "soapParentPropertyId"],
19983
+ "inventory_locations": ["id", "impersonatorCreatorResourceID", "isActive", "isDefault", "locationName", "resourceID"],
19597
19984
  "inventory_products": ["id", "availableUnits", "backOrderQuantity", "bin", "createDateTime", "createdByResourceID", "inventoryLocationID", "onHandUnits", "pickedUnits", "productID", "quantityMaximum", "quantityMinimum", "referenceNumber", "reservedUnits", "unitsOnOrder"],
19598
19985
  "invoice_templates": ["id", "coveredByBlockRetainerContractLabel", "coveredByRecurringServiceFixedPricePerTicketContractLabel", "currencyNegativeFormat", "currencyPositiveFormat", "dateFormat", "displayFixedPriceContractLabor", "displayRecurringServiceContractLabor", "displaySeparateLineItemForEachTax", "displayTaxCategory", "displayTaxCategorySuperscripts", "displayZeroAmountRecurringServicesAndBundles", "groupBy", "itemizeItemsInEachGroup", "itemizeServicesAndBundles", "name", "nonBillableLaborLabel", "numberFormat", "pageLayout", "pageNumberFormat", "paymentTerms", "rateCostExpression", "showGridHeader", "showVerticalGridLines", "sortBy", "timeFormat"],
19599
19986
  "invoices": ["id", "batchID", "comments", "companyID", "createDateTime", "creatorResourceID", "dueDate", "fromDate", "invoiceDateTime", "invoiceEditorTemplateID", "invoiceNumber", "invoiceTotal", "isVoided", "orderNumber", "paidDate", "paymentTerm", "taxGroup", "taxRegionName", "toDate", "totalTaxValue", "voidedByResourceID", "voidedDate", "webServiceDate"],
@@ -19833,21 +20220,21 @@ function validateRelationLeaves(resourceKey, conditions, op) {
19833
20220
  assertUndottedUdfField(c, op);
19834
20221
  const field = c.field;
19835
20222
  const [rel, sub, ...rest] = field.split(".");
19836
- const fail3 = (why) => {
20223
+ const fail4 = (why) => {
19837
20224
  throw new AutotaskConfigError(`${op}: relation filter "${field}" ${why} \u2014 the request was not issued`, {
19838
20225
  operation: op,
19839
20226
  suggestedAction: valid.length > 0 ? `Use ${valid.map((r) => `${r}.<${RELATION_TARGETS[r].resource} field>`).join(" or ")} (one hop; field names from operations.fieldCatalog).` : `${resourceKey} has no relation filters; filter on its own fields.`
19840
20227
  });
19841
20228
  };
19842
20229
  if (selfPrefixes(resourceKey).includes(rel)) {
19843
- if (rest.length > 0 || !sub) fail3("is not <resource>.<field> (multi-hop relations are not supported)");
20230
+ if (rest.length > 0 || !sub) fail4("is not <resource>.<field> (multi-hop relations are not supported)");
19844
20231
  continue;
19845
20232
  }
19846
- if (rest.length > 0 || !sub) fail3("is not <relation>.<field> (multi-hop relations are not supported)");
19847
- if (!valid.includes(rel)) fail3(`names an unknown relation for ${resourceKey} (valid: ${valid.join(", ") || "none"})`);
20233
+ if (rest.length > 0 || !sub) fail4("is not <relation>.<field> (multi-hop relations are not supported)");
20234
+ if (!valid.includes(rel)) fail4(`names an unknown relation for ${resourceKey} (valid: ${valid.join(", ") || "none"})`);
19848
20235
  const parentFields = MODEL_FIELD_SETS[RELATION_TARGETS[rel].resource];
19849
20236
  if (parentFields !== void 0 && modelFieldLookup(RELATION_TARGETS[rel].resource)?.(sub) !== true) {
19850
- fail3(`names a field unknown on ${RELATION_TARGETS[rel].resource}`);
20237
+ fail4(`names a field unknown on ${RELATION_TARGETS[rel].resource}`);
19851
20238
  }
19852
20239
  }
19853
20240
  };
@@ -19957,7 +20344,7 @@ var LABEL_NAME_MAX_CHARS = 200;
19957
20344
  function untrustedName(name) {
19958
20345
  if (name === null) return null;
19959
20346
  const [[capped]] = truncateNoteChars([{ v: name }], LABEL_NAME_MAX_CHARS, ["v"]);
19960
- return chunkBD4AUGCJ_cjs.wrapUntrusted(capped.v) ?? capped.v;
20347
+ return chunkCM5O672I_cjs.wrapUntrusted(capped.v) ?? capped.v;
19961
20348
  }
19962
20349
  function readNamesOpt(client, value, where) {
19963
20350
  if (value === void 0) return client?.config?.labels ?? false;
@@ -20000,11 +20387,13 @@ async function labelRows(client, resourceKey, rows) {
20000
20387
  }
20001
20388
  return r;
20002
20389
  });
20003
- const capHit = names?.section.truncated === true;
20390
+ const overBudget = names?.overBudget ?? 0;
20391
+ const unreadable = names?.unreadable ?? 0;
20004
20392
  const unresolved2 = Object.keys(names?.section.reasons ?? {});
20005
- if (capHit === false && unresolved2.length === 0) return { rows: out };
20393
+ if (overBudget === 0 && unreadable === 0 && unresolved2.length === 0) return { rows: out };
20006
20394
  const parts = [];
20007
- if (capHit) parts.push(`ids left unlabelled (their *Name is null): the per-call cap of ${DEFAULT_MAX_NAME_READS} uncached name reads was hit \u2014 names already read are cached, so repeating or narrowing the call labels more`);
20395
+ if (overBudget > 0) parts.push(`ids left unlabelled (their *Name is null): ${overBudget} id(s) over the per-call cap of ${DEFAULT_MAX_NAME_READS} uncached name reads \u2014 names already read are cached, so repeating or narrowing the call labels more`);
20396
+ if (unreadable > 0) parts.push(`${unreadable} id(s) not returned by the batched name read (their *Name is null): the record may be absent or not visible to this API user, so this is not a not-found`);
20008
20397
  if (unresolved2.length > 0) parts.push(`picklist label(s) unavailable for ${unresolved2.join(", ")} (see reasons)`);
20009
20398
  return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
20010
20399
  }
@@ -20173,7 +20562,7 @@ var QueryBase = class {
20173
20562
  }
20174
20563
  continueAcrossEmptyPage() {
20175
20564
  const { key } = this.config;
20176
- return isAuditLogResource(key) || isKnowledgeBaseRootResource(key);
20565
+ return isAuditLogResource(key) || isExactRecordResource(key);
20177
20566
  }
20178
20567
  /** @internal */
20179
20568
  readPage(body, page, pageSize, state2) {
@@ -20225,7 +20614,7 @@ var QueryBase = class {
20225
20614
  * (as queryBounded). Label siblings are opt-in (issue #287): the per-call
20226
20615
  * `names` key is the explicit override, absent = the client's `labels`
20227
20616
  * option (off by default). When on, labelling runs per page, so the cold
20228
- * name-read cap (20) applies per page; a capped id gets a null `*Name`
20617
+ * name-read cap (DEFAULT_MAX_NAME_READS) applies per page; a capped id gets a null `*Name`
20229
20618
  * (an iterator has no result envelope for the `names` summary). A
20230
20619
  * resource built without a client (bare `HttpClient`) yields raw rows.
20231
20620
  */
@@ -20570,7 +20959,7 @@ var QueryBase = class {
20570
20959
  }
20571
20960
  if (total <= BOUNDED_QUERY_MAX_LIMIT) {
20572
20961
  const { items: items2, pages: pages3, guard: guard2, sliced: sliced2, cursor: cursor2 } = await this.walkBounded(params, total);
20573
- if (this.walkTruncated(total, { itemsLength: items2.length, guard: guard2, sliced: sliced2, cursor: cursor2 }) || !this.hasCompleteKnowledgeBaseWindow(items2, total)) {
20962
+ if (this.walkTruncated(total, { itemsLength: items2.length, guard: guard2, sliced: sliced2, cursor: cursor2 }) || !this.hasCompleteExactRecordWindow(items2, total)) {
20574
20963
  throw this.latestWindowIncompleteError(total);
20575
20964
  }
20576
20965
  return this.finishLatest(items2, latest, pages3);
@@ -20579,11 +20968,11 @@ var QueryBase = class {
20579
20968
  probes += 1;
20580
20969
  if (probes > LATEST_MAX_COUNT_PROBES) throw this.latestThresholdUnresolvedError();
20581
20970
  };
20582
- const knowledgeBase = isKnowledgeBaseRootResource(this.config.key);
20583
- let lo = knowledgeBase ? -1n : 0n;
20971
+ const exactRecord = isExactRecordResource(this.config.key);
20972
+ let lo = exactRecord ? -1n : 0n;
20584
20973
  let hi;
20585
20974
  let aboveThreshold = 0;
20586
- if (isAuditLogResource(this.config.key) || knowledgeBase) {
20975
+ if (isAuditLogResource(this.config.key) || exactRecord) {
20587
20976
  hi = BigInt(MAX_AUDIT_ID);
20588
20977
  } else {
20589
20978
  for (let t = 1n; ; t = t << 1n) {
@@ -20604,17 +20993,17 @@ var QueryBase = class {
20604
20993
  aboveThreshold = above;
20605
20994
  } else lo = mid;
20606
20995
  }
20607
- if (knowledgeBase && aboveThreshold !== latest) throw this.latestWindowIncompleteError(latest + 1);
20996
+ if (exactRecord && aboveThreshold !== latest) throw this.latestWindowIncompleteError(latest + 1);
20608
20997
  const windowValue = hi <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(hi) : hi.toString();
20609
20998
  const window = [...baseConds, { op: "gte", field: "id", value: windowValue }];
20610
20999
  const { items, pages: pages2, guard, sliced, cursor } = await this.walkBounded({ ...params, filter: window }, latest + 1);
20611
- if (this.walkTruncated(latest + 1, { itemsLength: items.length, guard, sliced, cursor }) || !this.hasCompleteKnowledgeBaseWindow(items, latest + 1, hi)) {
21000
+ if (this.walkTruncated(latest + 1, { itemsLength: items.length, guard, sliced, cursor }) || !this.hasCompleteExactRecordWindow(items, latest + 1, hi)) {
20612
21001
  throw this.latestWindowIncompleteError(latest + 1);
20613
21002
  }
20614
21003
  return this.finishLatest(items, latest, pages2);
20615
21004
  }
20616
- hasCompleteKnowledgeBaseWindow(items, expected, minimum) {
20617
- if (!isKnowledgeBaseRootResource(this.config.key)) return true;
21005
+ hasCompleteExactRecordWindow(items, expected, minimum) {
21006
+ if (!isExactRecordResource(this.config.key)) return true;
20618
21007
  if (items.length !== expected) return false;
20619
21008
  const ids2 = items.map((item) => String(item.id));
20620
21009
  if (new Set(ids2).size !== expected) return false;
@@ -20761,10 +21150,12 @@ var MetaBase = class _MetaBase extends QueryBase {
20761
21150
  return cachedMetadataGet(this.http, this.config.key, kind, path, operation, unwrap, fresh, maxRetries);
20762
21151
  }
20763
21152
  /** `GET /V1.0/<E>/{id}` → `{ item }` unwrapped (`item: null` → NotFoundError). */
20764
- async getGlobal(id, fresh = false, maxRetries) {
21153
+ async getGlobal(id, fresh = false, maxRetries, checkedBaseUrl) {
20765
21154
  const numeric2 = parseIdentifier(id, "id");
20766
- const res = await this.cachedGet(`${this.resourcePath}/${numeric2}`, `${this.config.key}.get`, fresh, maxRetries);
20767
- return unwrapItem(res, numeric2, `${this.config.key}.get`, this.entityName);
21155
+ const path = `${this.resourcePath}/${numeric2}`;
21156
+ const operation = `${this.config.key}.get`;
21157
+ const res = checkedBaseUrl === void 0 ? await this.cachedGet(path, operation, fresh, maxRetries) : await this.http.request({ method: "GET", path, operation, maxRetries, checkedBaseUrl });
21158
+ return unwrapItem(res, numeric2, operation, this.entityName);
20768
21159
  }
20769
21160
  /**
20770
21161
  * V2 merge read: a FRESH single-record GET that skips response redaction
@@ -21281,26 +21672,26 @@ var MetaBase = class _MetaBase extends QueryBase {
21281
21672
 
21282
21673
  // src/resources/special/knowledgeBaseCategories.ts
21283
21674
  function admitKnowledgeBaseCategory(data, creating, staleToken) {
21284
- const fail3 = (message) => {
21675
+ const fail4 = (message) => {
21285
21676
  throw new AutotaskConfigError(`knowledge_base_categories: ${message}`);
21286
21677
  };
21287
- if (!creating && staleToken !== void 0) fail3("no documented stale timestamp is available");
21288
- if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
21678
+ if (!creating && staleToken !== void 0) fail4("no documented stale timestamp is available");
21679
+ if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail4("data must be a plain record");
21289
21680
  const body = { ...data };
21290
- for (const field of Object.keys(body)) if (!["name", "description", "parentCategoryID"].includes(field)) fail3(`${field} is not a writable KnowledgeBaseCategories field`);
21681
+ for (const field of Object.keys(body)) if (!["name", "description", "parentCategoryID"].includes(field)) fail4(`${field} is not a writable KnowledgeBaseCategories field`);
21291
21682
  for (const [field, max] of [["name", 50], ["description", 1e3]]) {
21292
21683
  const value = body[field];
21293
- if (value !== void 0 && (typeof value !== "string" || value.length > max)) fail3(`${field} must be a string of at most ${max} characters`);
21684
+ if (value !== void 0 && (typeof value !== "string" || value.length > max)) fail4(`${field} must be a string of at most ${max} characters`);
21294
21685
  }
21295
- if ((creating || body.name !== void 0) && (typeof body.name !== "string" || body.name.trim() === "")) fail3("name is required");
21296
- if (creating && body.parentCategoryID === void 0) fail3("parentCategoryID is required; choose a documented visible category rather than guessing a root id");
21686
+ if ((creating || body.name !== void 0) && (typeof body.name !== "string" || body.name.trim() === "")) fail4("name is required");
21687
+ if (creating && body.parentCategoryID === void 0) fail4("parentCategoryID is required; choose a documented visible category rather than guessing a root id");
21297
21688
  const parent = body.parentCategoryID;
21298
21689
  if (parent !== void 0) {
21299
- if (typeof parent !== "number") return fail3("parentCategoryID must be a numeric identifier");
21690
+ if (typeof parent !== "number") return fail4("parentCategoryID must be a numeric identifier");
21300
21691
  parseIdentifier(parent, "parentCategoryID");
21301
- if (parent > 2147483647) fail3("parentCategoryID must fit a signed 32-bit integer");
21692
+ if (parent > 2147483647) fail4("parentCategoryID must fit a signed 32-bit integer");
21302
21693
  }
21303
- if (!creating && !Object.values(body).some((value) => value !== void 0)) fail3("update must contain a writable field");
21694
+ if (!creating && !Object.values(body).some((value) => value !== void 0)) fail4("update must contain a writable field");
21304
21695
  return body;
21305
21696
  }
21306
21697
  function categoryReplacement(body) {
@@ -21314,45 +21705,45 @@ function categoryReplacement(body) {
21314
21705
  }
21315
21706
 
21316
21707
  // src/resources/special/knowledgeBaseArticles.ts
21317
- function fail(detail) {
21708
+ function fail2(detail) {
21318
21709
  throw new AutotaskConfigError(`knowledge_base_articles: ${detail}`);
21319
21710
  }
21320
21711
  function reference(value, name) {
21321
- if (typeof value !== "number") fail(`${name} must be a numeric identifier`);
21712
+ if (typeof value !== "number") fail2(`${name} must be a numeric identifier`);
21322
21713
  parseIdentifier(value, name);
21323
- if (value > 2147483647) fail(`${name} must fit a signed 32-bit integer`);
21714
+ if (value > 2147483647) fail2(`${name} must fit a signed 32-bit integer`);
21324
21715
  return value;
21325
21716
  }
21326
21717
  function articleParent(value) {
21327
21718
  const parent = parseIdentifier(value, "parentId");
21328
- if (typeof parent !== "number" || parent > 2147483647) fail("parentId must fit a signed 32-bit category identifier");
21329
- if (parent === 0) fail("parentId must name an article category");
21719
+ if (typeof parent !== "number" || parent > 2147483647) fail2("parentId must fit a signed 32-bit category identifier");
21720
+ if (parent === 0) fail2("parentId must name an article category");
21330
21721
  return parent;
21331
21722
  }
21332
21723
  function admitArticle(data, parentId, creating) {
21333
21724
  const parent = articleParent(parentId);
21334
- if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail("data must be a plain record");
21725
+ if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail2("data must be a plain record");
21335
21726
  const body = { ...data };
21336
21727
  const allowed = ["articleCategoryID", "publish", "title", "errorCodes", "keywords", "referenceLink", "isActive"];
21337
21728
  for (const key of Object.keys(body)) {
21338
- if (!allowed.includes(key)) fail(`${key} is not a writable article root field`);
21729
+ if (!allowed.includes(key)) fail2(`${key} is not a writable article root field`);
21339
21730
  if (key !== "articleCategoryID" && body[key] === void 0) delete body[key];
21340
21731
  }
21341
21732
  for (const [field, max] of [["title", 200], ["errorCodes", 200], ["keywords", 300], ["referenceLink", 500]]) {
21342
- if (Object.hasOwn(body, field) && (typeof body[field] !== "string" || body[field].length > max)) fail(`${field} must be a string of at most ${max} characters`);
21343
- }
21344
- if ((creating || Object.hasOwn(body, "title")) && (typeof body.title !== "string" || !body.title.trim())) fail("title is required and cannot be blank");
21345
- if (!creating && Object.hasOwn(body, "articleCategoryID")) fail("articleCategoryID is read-only after creation");
21346
- if (creating && String(reference(body.articleCategoryID, "articleCategoryID")) !== String(parent)) fail("articleCategoryID must match parentId");
21347
- if ((creating || Object.hasOwn(body, "publish")) && (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish) || body.publish < -2147483648 || body.publish > 2147483647)) fail("publish must be an int32 from current field metadata");
21348
- if (Object.hasOwn(body, "isActive") && typeof body.isActive !== "boolean") fail("isActive must be boolean");
21349
- if (!creating && !Object.keys(body).length) fail("update must contain a writable field");
21733
+ if (Object.hasOwn(body, field) && (typeof body[field] !== "string" || body[field].length > max)) fail2(`${field} must be a string of at most ${max} characters`);
21734
+ }
21735
+ if ((creating || Object.hasOwn(body, "title")) && (typeof body.title !== "string" || !body.title.trim())) fail2("title is required and cannot be blank");
21736
+ if (!creating && Object.hasOwn(body, "articleCategoryID")) fail2("articleCategoryID is read-only after creation");
21737
+ if (creating && String(reference(body.articleCategoryID, "articleCategoryID")) !== String(parent)) fail2("articleCategoryID must match parentId");
21738
+ if ((creating || Object.hasOwn(body, "publish")) && (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish) || body.publish < -2147483648 || body.publish > 2147483647)) fail2("publish must be an int32 from current field metadata");
21739
+ if (Object.hasOwn(body, "isActive") && typeof body.isActive !== "boolean") fail2("isActive must be boolean");
21740
+ if (!creating && !Object.keys(body).length) fail2("update must contain a writable field");
21350
21741
  return body;
21351
21742
  }
21352
21743
  async function guardArticle(http, parentId, id, maxRetries) {
21353
21744
  const parent = articleParent(parentId);
21354
21745
  const target = id === void 0 ? void 0 : parseIdentifier(id, "id");
21355
- if (target !== void 0 && (target === 0 || !isAuditDecimalId(String(target)))) fail("id must name an article within the signed 64-bit range");
21746
+ if (target !== void 0 && (target === 0 || !isAuditDecimalId(String(target)))) fail2("id must name an article within the signed 64-bit range");
21356
21747
  unwrapItem(await http.request({ method: "GET", path: `/V1.0/KnowledgeBaseCategories/${parent}`, operation: "knowledge_base_categories.get", maxRetries }), parent, "knowledge_base_categories.get", "article_category");
21357
21748
  if (target !== void 0) {
21358
21749
  return unwrapItem(await http.request({ method: "GET", path: `/V1.0/KnowledgeBaseCategories/${parent}/KnowledgeBaseArticles/${target}`, operation: "knowledge_base_articles.get", maxRetries }), target, "knowledge_base_articles.get", "article");
@@ -21361,7 +21752,7 @@ async function guardArticle(http, parentId, id, maxRetries) {
21361
21752
  }
21362
21753
  function assertArticlePublish(data, fields) {
21363
21754
  if (!Object.hasOwn(data, "publish")) return;
21364
- const unavailable = () => fail("publish requires an unambiguous active value in current field metadata");
21755
+ const unavailable = () => fail2("publish requires an unambiguous active value in current field metadata");
21365
21756
  if (!Array.isArray(fields)) unavailable();
21366
21757
  const rows = fields.filter((field) => isRecord2(field) && field.name === "publish");
21367
21758
  if (rows.length !== 1 || rows[0].isPickList !== true || rows[0].isReadOnly !== false || !Array.isArray(rows[0].picklistValues)) unavailable();
@@ -21567,23 +21958,27 @@ var MutationBase = class extends MetaBase {
21567
21958
  * write already happened, so a failed read-back is reported on the result
21568
21959
  * (`persistedCheckFailed`: the error code, or `UNKNOWN (<error name>)`), never thrown.
21569
21960
  */
21570
- async withPersistedCheck(result, data, opts, id, parentId) {
21961
+ async withPersistedCheck(result, data, opts, id, parentId, checkedBaseUrl) {
21571
21962
  if (opts.verifyPersisted !== true) return result;
21572
- const maxRetries = isKnowledgeBaseRootResource(this.config.key) ? opts.maxRetries : void 0;
21963
+ const maxRetries = isExactRecordResource(this.config.key) ? opts.maxRetries : void 0;
21573
21964
  try {
21574
- const stored = parentId === void 0 ? await this.getGlobal(id, true, maxRetries) : this.config.attachmentGet === true ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true, maxRetries);
21575
- return { ...result, notPersisted: notPersistedFields(data, stored) };
21965
+ const stored = parentId === void 0 ? await this.getGlobal(id, true, maxRetries, checkedBaseUrl) : this.config.attachmentGet === true ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true, maxRetries);
21966
+ const submitted = data;
21967
+ const persisted = stored;
21968
+ const notPersisted = this.config.key === "inventory_locations" ? Object.keys(submitted).filter((field) => submitted[field] !== persisted[field]) : notPersistedFields(submitted, persisted);
21969
+ return { ...result, notPersisted };
21576
21970
  } catch (err) {
21577
21971
  return { ...result, persistedCheckFailed: err instanceof AutotaskError ? err.code : `UNKNOWN (${err instanceof Error ? err.name : typeof err})` };
21578
21972
  }
21579
21973
  }
21580
- async updateGlobal(id, data, opts = {}, method = "PUT") {
21974
+ async updateGlobal(id, data, opts = {}, method = "PUT", checkedBaseUrl) {
21581
21975
  const numeric2 = parseIdentifier(id, "id");
21582
21976
  const operation = `${this.config.key}.update`;
21583
21977
  let body = this.normalizeMutationBody(data);
21584
- const collectionUpdate = this.config.collectionUpdate === true;
21978
+ const partialCollection = checkedBaseUrl !== void 0;
21979
+ const collectionUpdate = partialCollection || this.config.collectionUpdate === true;
21585
21980
  if (collectionUpdate) {
21586
- if (opts.raw !== true) {
21981
+ if (!partialCollection && opts.raw !== true) {
21587
21982
  let current;
21588
21983
  try {
21589
21984
  current = await this.getGlobalUnredacted(numeric2, { maxRetries: opts.maxRetries });
@@ -21607,7 +22002,9 @@ var MutationBase = class extends MetaBase {
21607
22002
  path: collectionUpdate ? this.resourcePath : `${this.resourcePath}/${numeric2}`,
21608
22003
  body,
21609
22004
  operation,
21610
- maxRetries: opts.maxRetries
22005
+ maxRetries: opts.maxRetries,
22006
+ // The preflight facts must be checked again before any later PATCH.
22007
+ ...partialCollection ? { maintenanceMaxWaitMs: 0, checkedBaseUrl } : {}
21611
22008
  });
21612
22009
  } catch (err) {
21613
22010
  if (method === "PATCH" || !this.putFallbackEligible(err)) throw err;
@@ -21634,7 +22031,7 @@ var MutationBase = class extends MetaBase {
21634
22031
  }
21635
22032
  return this.withPersistedCheck(unwrapOperation(retry, operation), data, opts, numeric2);
21636
22033
  }
21637
- return this.withPersistedCheck(unwrapOperation(res, operation), data, opts, numeric2);
22034
+ return this.withPersistedCheck(unwrapOperation(res, operation), data, opts, numeric2, void 0, checkedBaseUrl);
21638
22035
  }
21639
22036
  /** `DELETE /V1.0/<E>/{id}` → `{ id }` (OperationResultModel). A blank 2xx
21640
22037
  * (204 / empty body) is a valid vendor delete answer — synthesize the
@@ -21944,21 +22341,22 @@ var MutationBase = class extends MetaBase {
21944
22341
  * check (mismatch throws STALE_OBJECT) and the best-effort `diff`. NO
21945
22342
  * mutating request is issued.
21946
22343
  */
21947
- async runUpdateDryRun(id, data, opts = {}, parentId, currentRecord) {
22344
+ async runUpdateDryRun(id, data, opts = {}, parentId, currentRecord, partialCollection) {
21948
22345
  const operation = `${this.config.key}.update`;
21949
22346
  const checks = [];
21950
22347
  const warnings = [];
21951
22348
  checks.push({ name: "input-validation", ok: isRecord2(data) && Object.keys(data).length > 0 });
21952
22349
  const scopedUpdate = parentId !== void 0 && this.config.parentScopedPath !== void 0;
21953
- const collectionUpdate = scopedUpdate || this.config.collectionUpdate === true;
22350
+ const collectionUpdate = scopedUpdate || partialCollection !== void 0 || this.config.collectionUpdate === true;
21954
22351
  const path = scopedUpdate ? this.scopedCollectionPath(parentId) : collectionUpdate ? this.resourcePath : `${this.resourcePath}/${id}`;
21955
- const method = scopedUpdate ? "PATCH" : "PUT";
22352
+ const method = scopedUpdate || partialCollection !== void 0 ? "PATCH" : "PUT";
21956
22353
  let current;
21957
22354
  try {
21958
- current = currentRecord ?? (parentId === void 0 ? await this.getGlobal(id, true, this.config.key === "knowledge_base_categories" ? opts.maxRetries : void 0) : this.config.attachmentGet ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true));
22355
+ current = currentRecord ?? (parentId === void 0 ? await this.getGlobal(id, true, this.config.key === "knowledge_base_categories" || partialCollection !== void 0 ? opts.maxRetries : void 0) : this.config.attachmentGet ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true));
21959
22356
  } catch (err) {
21960
22357
  if (err instanceof NotFoundError) {
21961
- const updateReason = EMPTY_REASON_STAMPS[this.config.key]?.update;
22358
+ const reasons = EMPTY_REASON_STAMPS[this.config.key];
22359
+ const updateReason = reasons?.update ?? (partialCollection === void 0 ? void 0 : reasons?.get);
21962
22360
  checks.push({
21963
22361
  name: "current-record-exists",
21964
22362
  ok: false,
@@ -21973,18 +22371,19 @@ var MutationBase = class extends MetaBase {
21973
22371
  checks,
21974
22372
  impact: { affected: 1, scope: "single-record", reversible: true },
21975
22373
  warnings,
21976
- data,
22374
+ data: partialCollection === void 0 ? data : { ...data, id },
21977
22375
  ...updateReason !== void 0 ? { emptyReason: updateReason } : {}
21978
22376
  }, { redactPersonalData: this.http.redactPersonalData });
21979
22377
  }
21980
22378
  throw err;
21981
22379
  }
21982
22380
  checks.push({ name: "current-record-exists", ok: true });
22381
+ partialCollection?.checkCurrent(current);
21983
22382
  if (this.staleObjectCheck(current, opts, operation)) {
21984
22383
  checks.push({ name: "stale-check", ok: true });
21985
22384
  }
21986
22385
  let envelopeData = data;
21987
- if (this.config.key === "knowledge_base_articles") {
22386
+ if (partialCollection !== void 0 || this.config.key === "knowledge_base_articles") {
21988
22387
  envelopeData = { ...this.normalizeMutationBody(data), id };
21989
22388
  } else if (parentId === void 0 && this.config.collectionUpdate === true && opts.raw !== true) {
21990
22389
  const merged = mergePartialBody(current, this.normalizeMutationBody(data));
@@ -22061,34 +22460,34 @@ var BaseResource = class extends MutationBase {
22061
22460
  };
22062
22461
 
22063
22462
  // src/resources/special/taskPredecessors.ts
22064
- function fail2(detail) {
22463
+ function fail3(detail) {
22065
22464
  throw new AutotaskConfigError(`task_predecessors: ${detail}`);
22066
22465
  }
22067
22466
  function numeric(value, field) {
22068
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) fail2(`${field} must be a positive numeric identifier`);
22467
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) fail3(`${field} must be a positive numeric identifier`);
22069
22468
  return value;
22070
22469
  }
22071
22470
  function predecessorParent(value) {
22072
22471
  const parent = parseIdentifier(value, "parentId");
22073
- if (parent === 0) fail2("parentId must name a successor task");
22472
+ if (parent === 0) fail3("parentId must name a successor task");
22074
22473
  return parent;
22075
22474
  }
22076
22475
  function assertPredecessorBinding(value, parentId, id) {
22077
- if (!isRecord2(value)) fail2("the returned record must establish id and successorTaskID parent");
22078
- if (String(parseIdentifier(value.id, "record.id")) !== String(parseIdentifier(id, "id")) || String(parseIdentifier(value.successorTaskID, "record.successorTaskID")) !== String(predecessorParent(parentId))) fail2("the returned record must match id and successorTaskID parent");
22476
+ if (!isRecord2(value)) fail3("the returned record must establish id and successorTaskID parent");
22477
+ if (String(parseIdentifier(value.id, "record.id")) !== String(parseIdentifier(id, "id")) || String(parseIdentifier(value.successorTaskID, "record.successorTaskID")) !== String(predecessorParent(parentId))) fail3("the returned record must match id and successorTaskID parent");
22079
22478
  }
22080
22479
  function admitTaskPredecessor(data, parentId, creating) {
22081
22480
  const parent = predecessorParent(parentId);
22082
- if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail2("data must be a plain record");
22481
+ if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
22083
22482
  const payload = { ...data };
22084
22483
  const allowed = creating ? ["predecessorTaskID", "successorTaskID", "lagDays"] : ["lagDays"];
22085
- if (Object.keys(payload).some((key) => !allowed.includes(key))) fail2(creating ? "only predecessorTaskID, successorTaskID and lagDays are writable on create" : "only lagDays can be updated");
22086
- if ((!creating || payload.lagDays !== void 0) && (typeof payload.lagDays !== "number" || !Number.isInteger(payload.lagDays) || payload.lagDays < -2147483648 || payload.lagDays > 2147483647)) fail2("lagDays must be an int32 integer");
22484
+ if (Object.keys(payload).some((key) => !allowed.includes(key))) fail3(creating ? "only predecessorTaskID, successorTaskID and lagDays are writable on create" : "only lagDays can be updated");
22485
+ if ((!creating || payload.lagDays !== void 0) && (typeof payload.lagDays !== "number" || !Number.isInteger(payload.lagDays) || payload.lagDays < -2147483648 || payload.lagDays > 2147483647)) fail3("lagDays must be an int32 integer");
22087
22486
  if (creating) {
22088
22487
  const successor = numeric(payload.successorTaskID, "successorTaskID");
22089
22488
  const predecessor = numeric(payload.predecessorTaskID, "predecessorTaskID");
22090
- if (String(successor) !== String(parent)) fail2("successorTaskID must match parentId");
22091
- if (predecessor === successor) fail2("predecessorTaskID and successorTaskID must be distinct");
22489
+ if (String(successor) !== String(parent)) fail3("successorTaskID must match parentId");
22490
+ if (predecessor === successor) fail3("predecessorTaskID and successorTaskID must be distinct");
22092
22491
  }
22093
22492
  return payload;
22094
22493
  }
@@ -22097,50 +22496,137 @@ async function guardTaskPredecessor(http, parentId, id, data) {
22097
22496
  let row = data;
22098
22497
  if (id !== void 0) {
22099
22498
  const target = parseIdentifier(id, "id");
22100
- if (target === 0) fail2("id must name a predecessor relationship");
22499
+ if (target === 0) fail3("id must name a predecessor relationship");
22101
22500
  row = unwrapItem(await http.request({ method: "GET", path: `/V1.0/Tasks/${parent}/Predecessors/${target}`, operation: "task_predecessors.get" }), target, "task_predecessors.get", "task_predecessor");
22102
22501
  assertPredecessorBinding(row, parent, target);
22103
22502
  }
22104
22503
  const predecessor = numeric(row?.predecessorTaskID, "predecessorTaskID");
22105
22504
  const successor = numeric(row?.successorTaskID, "successorTaskID");
22106
- if (predecessor === successor) fail2("predecessorTaskID and successorTaskID must be distinct");
22505
+ if (predecessor === successor) fail3("predecessorTaskID and successorTaskID must be distinct");
22107
22506
  const projects = [];
22108
22507
  for (const taskId of [predecessor, successor]) {
22109
22508
  const task = unwrapItem(await http.request({ method: "GET", path: `/V1.0/Tasks/${taskId}`, operation: "tasks.get" }), taskId, "tasks.get", "task");
22110
- if (String(parseIdentifier(task.id, "task.id")) !== String(taskId)) fail2("the returned task must match its requested id");
22509
+ if (String(parseIdentifier(task.id, "task.id")) !== String(taskId)) fail3("the returned task must match its requested id");
22111
22510
  projects.push(numeric(task.projectID, "task.projectID"));
22112
22511
  }
22113
- if (projects[0] !== projects[1]) fail2("predecessor and successor tasks must belong to the same project");
22512
+ if (projects[0] !== projects[1]) fail3("predecessor and successor tasks must belong to the same project");
22114
22513
  }
22115
22514
 
22116
22515
  // src/resources/special/taskNotes.ts
22117
22516
  var WRITABLE = /* @__PURE__ */ new Set(["id", "itemId", "createdByContactID", "description", "noteType", "publish", "taskID", "title"]);
22118
22517
  function admitTaskNote(data, parentId, creating) {
22119
22518
  const parent = parseIdentifier(parentId, "parentId");
22120
- const fail3 = (message) => {
22519
+ const fail4 = (message) => {
22121
22520
  throw new AutotaskConfigError(`task_notes: ${message}`);
22122
22521
  };
22123
- if (data === null || typeof data !== "object" || Array.isArray(data)) fail3("data must be a record");
22522
+ if (data === null || typeof data !== "object" || Array.isArray(data)) fail4("data must be a record");
22124
22523
  const body = data;
22125
- for (const key of Object.keys(body)) if (!WRITABLE.has(key)) fail3(`${key} is not a writable TaskNotes field`);
22524
+ for (const key of Object.keys(body)) if (!WRITABLE.has(key)) fail4(`${key} is not a writable TaskNotes field`);
22126
22525
  for (const [field, maximum] of [["description", 3200], ["title", 250]]) {
22127
22526
  const value = body[field];
22128
- if (value !== void 0 && (typeof value !== "string" || value.length > maximum)) fail3(`${field} must be a string of at most ${maximum} characters`);
22527
+ if (value !== void 0 && (typeof value !== "string" || value.length > maximum)) fail4(`${field} must be a string of at most ${maximum} characters`);
22129
22528
  }
22130
- if (creating && (typeof body.description !== "string" || body.description.trim() === "")) fail3("description is required");
22529
+ if (creating && (typeof body.description !== "string" || body.description.trim() === "")) fail4("description is required");
22131
22530
  for (const field of ["noteType", "publish"]) {
22132
22531
  const value = body[field];
22133
- if ((creating || value !== void 0) && (typeof value !== "number" || !Number.isSafeInteger(value))) fail3(`${field} must be an integer from the current field metadata`);
22532
+ if ((creating || value !== void 0) && (typeof value !== "number" || !Number.isSafeInteger(value))) fail4(`${field} must be an integer from the current field metadata`);
22134
22533
  }
22135
- if (creating && body.taskID === void 0) fail3("taskID is required in the create body and must match parentId");
22534
+ if (creating && body.taskID === void 0) fail4("taskID is required in the create body and must match parentId");
22136
22535
  for (const field of ["createdByContactID", "taskID"]) {
22137
22536
  if (body[field] !== void 0) {
22138
- if (typeof body[field] !== "number") fail3(`${field} must be a numeric identifier`);
22537
+ if (typeof body[field] !== "number") fail4(`${field} must be a numeric identifier`);
22139
22538
  const id = parseIdentifier(body[field], field);
22140
- if (field === "taskID" && String(id) !== String(parent)) fail3("taskID must match the parentId path argument");
22539
+ if (field === "taskID" && String(id) !== String(parent)) fail4("taskID must match the parentId path argument");
22540
+ }
22541
+ }
22542
+ if (!creating && !Object.keys(body).some((key) => key !== "id" && key !== "itemId")) fail4("update must contain a writable field");
22543
+ }
22544
+
22545
+ // src/operations/invoke/fieldSuggest.ts
22546
+ var MAX_SUGGESTIONS = 3;
22547
+ var MIN_SUBSTRING_CHARS = 4;
22548
+ var GENERIC_TOKENS = /* @__PURE__ */ new Set(["date", "time", "datetime", "day", "is", "number", "type", "name", "last", "on", "at", "id"]);
22549
+ var DATE_TOKENS = /* @__PURE__ */ new Set(["date", "time", "datetime", "day", "on", "at"]);
22550
+ var TOKEN_SYNONYMS = [["install", "purchase", "purchased"]];
22551
+ var SYNONYM_OF = new Map(TOKEN_SYNONYMS.flatMap((group) => group.map((t) => [t, group[0]])));
22552
+ var Tier = { Substring: 0, Tokens: 1, Edit: 2, Generic: 3, SameType: 4, Rest: 5 };
22553
+ function tokens(name) {
22554
+ return (name.match(/[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+/g) ?? []).map((t) => t.toLowerCase());
22555
+ }
22556
+ function normalTokens(name) {
22557
+ return new Set(tokens(name).map((t) => SYNONYM_OF.get(t) ?? t));
22558
+ }
22559
+ function editDistance(a, b, cap = Number.POSITIVE_INFINITY) {
22560
+ if (Math.abs(a.length - b.length) > cap) return cap + 1;
22561
+ const far = Number.isFinite(cap) ? cap + 1 : a.length + b.length + 1;
22562
+ const band = Number.isFinite(cap) ? cap : a.length + b.length;
22563
+ let prev2 = new Int32Array(b.length + 1).fill(far);
22564
+ let prev = Int32Array.from({ length: b.length + 1 }, (_, j) => j <= band ? j : far);
22565
+ let cur = new Int32Array(b.length + 1).fill(far);
22566
+ for (let i = 1; i <= a.length; i += 1) {
22567
+ const lo = Math.max(1, i - band);
22568
+ const hi = Math.min(b.length, i + band);
22569
+ cur.fill(far);
22570
+ cur[0] = i <= band ? i : far;
22571
+ let rowMin = cur[0];
22572
+ for (let j = lo; j <= hi; j += 1) {
22573
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
22574
+ let v = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
22575
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, prev2[j - 2] + 1);
22576
+ cur[j] = v;
22577
+ if (v < rowMin) rowMin = v;
22578
+ }
22579
+ if (rowMin > cap) return cap + 1;
22580
+ [prev2, prev, cur] = [prev, cur, prev2];
22581
+ }
22582
+ return Math.min(prev[b.length], cap + 1);
22583
+ }
22584
+ function looksLikeDate(name) {
22585
+ return tokens(name).some((t) => DATE_TOKENS.has(t));
22586
+ }
22587
+ var MAX_EDITS = 6;
22588
+ var DISTANCE_CAP = 8;
22589
+ function score(unknown, candidate2) {
22590
+ const u = unknown.lower;
22591
+ const c = candidate2.lower;
22592
+ const [shorter, longer] = u.length <= c.length ? [u, c] : [c, u];
22593
+ let shared = 0;
22594
+ let meaningful = 0;
22595
+ for (const t of candidate2.tokens) {
22596
+ if (!unknown.tokens.has(t)) continue;
22597
+ shared += 1;
22598
+ if (!GENERIC_TOKENS.has(t)) meaningful += 1;
22599
+ }
22600
+ const threshold = Math.min(MAX_EDITS, Math.max(1, Math.floor(longer.length * 0.3)));
22601
+ const distance = editDistance(u, c, DISTANCE_CAP);
22602
+ const shorterGeneric = shorter === u ? unknown.allGeneric : [...candidate2.tokens].every((t) => GENERIC_TOKENS.has(t));
22603
+ if (shorter.length >= MIN_SUBSTRING_CHARS && longer.includes(shorter) && !shorterGeneric) return { tier: Tier.Substring, shared, distance };
22604
+ if (meaningful > 0) return { tier: Tier.Tokens, shared, distance };
22605
+ if (shorter.length >= 3 && distance <= threshold) return { tier: Tier.Edit, shared, distance };
22606
+ if (shared > 0) return { tier: Tier.Generic, shared, distance };
22607
+ if (candidate2.isDate && unknown.isDate) return { tier: Tier.SameType, shared, distance };
22608
+ return { tier: Tier.Rest, shared, distance };
22609
+ }
22610
+ var better = (a, b) => a.tier - b.tier || b.shared - a.shared || a.distance - b.distance;
22611
+ var isClose = (s) => s.tier <= Tier.Edit;
22612
+ function rankFieldNames(unknown, known, dateFields = []) {
22613
+ const dates = new Set(dateFields);
22614
+ const candidates = known.map((name) => ({ name, lower: name.toLowerCase(), tokens: normalTokens(name), isDate: dates.has(name) }));
22615
+ const best = /* @__PURE__ */ new Map();
22616
+ const suggestions = [];
22617
+ for (const name of new Set(unknown)) {
22618
+ const probeTokens = normalTokens(name);
22619
+ const probe = { lower: name.toLowerCase(), tokens: probeTokens, isDate: looksLikeDate(name), allGeneric: [...probeTokens].every((t) => GENERIC_TOKENS.has(t)) };
22620
+ const scored = candidates.map((c, index) => ({ k: c.name, index, s: score(probe, c) }));
22621
+ for (const { k, s } of scored) {
22622
+ const prev = best.get(k);
22623
+ if (prev === void 0 || better(s, prev) < 0) best.set(k, s);
22141
22624
  }
22625
+ const close = scored.filter((x) => isClose(x.s)).sort((a, b) => better(a.s, b.s) || a.index - b.index);
22626
+ if (close.length > 0) suggestions.push({ name, candidates: close.slice(0, MAX_SUGGESTIONS).map((x) => x.k) });
22142
22627
  }
22143
- if (!creating && !Object.keys(body).some((key) => key !== "id" && key !== "itemId")) fail3("update must contain a writable field");
22628
+ const ordered = known.map((k, index) => ({ k, index, s: best.get(k) ?? { tier: Tier.Rest, shared: 0, distance: 0 } })).sort((a, b) => a.s.tier === Tier.Rest && b.s.tier === Tier.Rest ? a.index - b.index : better(a.s, b.s) || a.index - b.index).map((x) => x.k);
22629
+ return { ordered, suggestions };
22144
22630
  }
22145
22631
 
22146
22632
  // src/operations/invoke/fieldNames.ts
@@ -22158,6 +22644,14 @@ async function liveFieldNames(holder) {
22158
22644
  var UNKNOWN_NAME_LIST_CAP = 20;
22159
22645
  var UNKNOWN_NAME_DISPLAY_CHARS = 40;
22160
22646
  var ENTITY_NAME_LIST_CAP = 20;
22647
+ var REFUSAL_MAX_CHARS = 3e3;
22648
+ var SUGGESTED_NAME_CAP = 5;
22649
+ function didYouMeanClause(suggestions, take = SUGGESTED_NAME_CAP) {
22650
+ const shown = suggestions.slice(0, take);
22651
+ if (shown.length === 0) return "";
22652
+ const cut = (n) => n.length > UNKNOWN_NAME_DISPLAY_CHARS ? `${n.slice(0, UNKNOWN_NAME_DISPLAY_CHARS)}\u2026` : n;
22653
+ return ` \u2014 did you mean: ${shown.map((s) => `"${cut(s.name)}" -> ${s.candidates.map(cut).join(", ")}`).join("; ")}`;
22654
+ }
22161
22655
  function formatUnknownNameList(names, cap = UNKNOWN_NAME_LIST_CAP) {
22162
22656
  const listed = names.slice(0, cap).map((n) => `"${n.length > UNKNOWN_NAME_DISPLAY_CHARS ? `${n.slice(0, UNKNOWN_NAME_DISPLAY_CHARS)}\u2026` : n}"`).join(", ");
22163
22657
  const more = names.length > cap ? ` (and ${names.length - cap} more)` : "";
@@ -22240,10 +22734,16 @@ function unknownNamesRefusal(record, authority, known, unknownInclude, unknownFi
22240
22734
  if (unknownInclude.length > 0) parts.push(`includeFields has unknown field name(s) ${formatUnknownNameList(unknownInclude)}`);
22241
22735
  if (unknownFilter.length > 0) parts.push(`filter condition(s) carry unknown field name(s) ${formatUnknownNameList(unknownFilter)}`);
22242
22736
  const wireClause = record.operation === "count" ? "the count request was not issued" : "the query POST was not issued";
22243
- const head = `invoke: "${record.id}" ${parts.join("; ")} against ${authority}`;
22737
+ const base = `invoke: "${record.id}" ${parts.join("; ")} against ${authority}`;
22738
+ const ranked = [...unknownInclude.slice(0, UNKNOWN_NAME_LIST_CAP), ...unknownFilter.slice(0, UNKNOWN_NAME_LIST_CAP)];
22739
+ const { ordered, suggestions } = rankFieldNames(ranked, known, MODEL_DATE_FIELDS[record.resource]);
22244
22740
  const count = known.length > ENTITY_NAME_LIST_CAP ? `${known.length}, first ${ENTITY_NAME_LIST_CAP}` : `${known.length}`;
22245
- const withList = `${head} \u2014 fields available on ${record.resource} (${count}): ${formatUnknownNameList(known, ENTITY_NAME_LIST_CAP)} \u2014 ${wireClause}`;
22246
- const message = known.length === 0 ? `${head} \u2014 ${wireClause}` : withList.length <= 3e3 ? withList : `${head} \u2014 ${record.resource} has ${known.length} fields; use operations.fieldCatalog resources: ["${record.resource}"] for the full set \u2014 ${wireClause}`;
22741
+ const pointer = `${record.resource} has ${known.length} fields; use operations.fieldCatalog resources: ["${record.resource}"] for the full set`;
22742
+ let take = SUGGESTED_NAME_CAP;
22743
+ while (take > 0 && `${base}${didYouMeanClause(suggestions, take)} \u2014 ${pointer} \u2014 ${wireClause}`.length > REFUSAL_MAX_CHARS) take -= 1;
22744
+ const head = `${base}${didYouMeanClause(suggestions, take)}`;
22745
+ const withList = `${head} \u2014 fields available on ${record.resource} (${count}): ${formatUnknownNameList(ordered, ENTITY_NAME_LIST_CAP)} \u2014 ${wireClause}`;
22746
+ const message = known.length === 0 ? `${head} \u2014 ${wireClause}` : withList.length <= REFUSAL_MAX_CHARS ? withList : `${head} \u2014 ${pointer} \u2014 ${wireClause}`;
22247
22747
  return new AutotaskConfigError(
22248
22748
  message,
22249
22749
  {
@@ -22309,38 +22809,38 @@ function isBase64(value) {
22309
22809
  }
22310
22810
  function admitTaskAttachment(data, parentId) {
22311
22811
  const parent = parseIdentifier(parentId, "parentId");
22312
- const fail3 = (message) => {
22812
+ const fail4 = (message) => {
22313
22813
  throw new AutotaskConfigError(`task_attachments: ${message}`);
22314
22814
  };
22315
- if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
22815
+ if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail4("data must be a plain record");
22316
22816
  const body = data;
22317
- for (const field of Object.keys(body)) if (!WRITABLE2.has(field)) fail3(`${field} is not a supported create field`);
22817
+ for (const field of Object.keys(body)) if (!WRITABLE2.has(field)) fail4(`${field} is not a supported create field`);
22318
22818
  for (const field of ["attachmentType", "fullPath", "title"]) {
22319
- if (typeof body[field] !== "string" || body[field].trim() === "") fail3(`${field} is required and must be a non-empty string`);
22819
+ if (typeof body[field] !== "string" || body[field].trim() === "") fail4(`${field} is required and must be a non-empty string`);
22320
22820
  }
22321
- if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail3("publish must be an integer from current field metadata");
22821
+ if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail4("publish must be an integer from current field metadata");
22322
22822
  for (const field of ["data", "contentType"]) {
22323
- if (body[field] !== void 0 && typeof body[field] !== "string") fail3(`${field} must be a string`);
22823
+ if (body[field] !== void 0 && typeof body[field] !== "string") fail4(`${field} must be a string`);
22324
22824
  }
22325
22825
  if (body.attachmentType === "FILE_ATTACHMENT") {
22326
- if (typeof body.data !== "string" || body.data === "") return fail3("FILE_ATTACHMENT requires non-empty base64 data");
22327
- if (!isBase64(body.data)) fail3("FILE_ATTACHMENT data must be base64 encoded");
22826
+ if (typeof body.data !== "string" || body.data === "") return fail4("FILE_ATTACHMENT requires non-empty base64 data");
22827
+ if (!isBase64(body.data)) fail4("FILE_ATTACHMENT data must be base64 encoded");
22328
22828
  }
22329
22829
  if (body.taskID !== void 0) {
22330
- if (typeof body.taskID !== "number") fail3("taskID must be a numeric identifier");
22331
- if (String(parseIdentifier(body.taskID, "taskID")) !== String(parent)) fail3("taskID must match the parentId path argument");
22830
+ if (typeof body.taskID !== "number") fail4("taskID must be a numeric identifier");
22831
+ if (String(parseIdentifier(body.taskID, "taskID")) !== String(parent)) fail4("taskID must match the parentId path argument");
22332
22832
  }
22333
22833
  if (body.parentAttachmentID !== void 0) {
22334
- if (typeof body.parentAttachmentID !== "number") fail3("parentAttachmentID must be a numeric identifier");
22834
+ if (typeof body.parentAttachmentID !== "number") fail4("parentAttachmentID must be a numeric identifier");
22335
22835
  parseIdentifier(body.parentAttachmentID, "parentAttachmentID");
22336
22836
  }
22337
22837
  }
22338
22838
  function admitFileAttachment(resource, data, parentId) {
22339
22839
  parseIdentifier(parentId, "parentId");
22340
- const fail3 = (message) => {
22840
+ const fail4 = (message) => {
22341
22841
  throw new AutotaskConfigError(`${resource}: ${message}`);
22342
22842
  };
22343
- if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
22843
+ if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail4("data must be a plain record");
22344
22844
  const body = data;
22345
22845
  const reference2 = {
22346
22846
  project_attachments: void 0,
@@ -22353,20 +22853,20 @@ function admitFileAttachment(resource, data, parentId) {
22353
22853
  configuration_item_attachments: "parentAttachmentID",
22354
22854
  configuration_item_note_attachments: void 0
22355
22855
  }[resource];
22356
- for (const field of Object.keys(body)) if (!FILE_WRITABLE.has(field) && field !== reference2) fail3(`${field} is not a supported create field`);
22357
- if (body.attachmentType !== "FILE_ATTACHMENT") fail3("attachmentType must explicitly be FILE_ATTACHMENT; other attachment types are unsupported");
22856
+ for (const field of Object.keys(body)) if (!FILE_WRITABLE.has(field) && field !== reference2) fail4(`${field} is not a supported create field`);
22857
+ if (body.attachmentType !== "FILE_ATTACHMENT") fail4("attachmentType must explicitly be FILE_ATTACHMENT; other attachment types are unsupported");
22358
22858
  const maxLength = resource === "project_attachments" ? void 0 : 255;
22359
22859
  for (const field of ["fullPath", "title"]) {
22360
22860
  const value = body[field];
22361
22861
  const requirement = `${field} is required and must be a nonblank string${maxLength === void 0 ? "" : ` of at most ${maxLength} characters`}`;
22362
- if (typeof value !== "string" || value.trim() === "") return fail3(requirement);
22363
- if (maxLength !== void 0 && value.length > maxLength) fail3(requirement);
22862
+ if (typeof value !== "string" || value.trim() === "") return fail4(requirement);
22863
+ if (maxLength !== void 0 && value.length > maxLength) fail4(requirement);
22364
22864
  }
22365
- if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail3("publish must be an integer from current field metadata");
22366
- if (typeof body.data !== "string" || !isBase64(body.data)) fail3("FILE_ATTACHMENT requires nonempty base64 data");
22865
+ if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail4("publish must be an integer from current field metadata");
22866
+ if (typeof body.data !== "string" || !isBase64(body.data)) fail4("FILE_ATTACHMENT requires nonempty base64 data");
22367
22867
  if (reference2 !== void 0 && body[reference2] !== void 0) {
22368
- if (typeof body[reference2] !== "number") fail3(`${reference2} must be a numeric identifier`);
22369
- if (parseIdentifier(body[reference2], reference2) === 0) fail3(`${reference2} must be positive`);
22868
+ if (typeof body[reference2] !== "number") fail4(`${reference2} must be a numeric identifier`);
22869
+ if (parseIdentifier(body[reference2], reference2) === 0) fail4(`${reference2} must be positive`);
22370
22870
  }
22371
22871
  }
22372
22872
  function admitScopedAttachmentQuery(resource, params) {
@@ -23215,6 +23715,16 @@ var SIMPLE_RESOURCES = [
23215
23715
  helpers: { search: false, resolve: true, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
23216
23716
  opForms: { get: "scoped", create: "scoped", update: "scoped", delete: "scoped" }
23217
23717
  },
23718
+ {
23719
+ key: "inventory_locations",
23720
+ accessor: "inventoryLocations",
23721
+ resourcePath: "/V1.0/InventoryLocations",
23722
+ deletable: false,
23723
+ udfCapable: false,
23724
+ ops: { query: true, queryAll: false, count: true, get: true, create: true, update: true, delete: false, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
23725
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
23726
+ opForms: { get: "global", create: "global", update: "global" }
23727
+ },
23218
23728
  {
23219
23729
  key: "invoice_templates",
23220
23730
  accessor: "invoiceTemplates",
@@ -24110,7 +24620,7 @@ var GenericResource = class extends BaseResource {
24110
24620
  if (["company_attachments", "company_note_attachments", "configuration_item_attachments", "configuration_item_note_attachments", "contract_note_attachments", "expense_report_attachments", "project_attachments", "project_note_attachments", "resource_attachments", "sales_order_attachments", "task_attachments", "task_note_attachments"].includes(config.key)) this.getUdfInfo = async () => {
24111
24621
  throw new OperationNotSupportedError(config.key, "getUdfInfo");
24112
24622
  };
24113
- if (config.ops?.create === false || isScopedAttachmentResource(config.key) || ["company_attachments", "task_predecessors", "knowledge_base_articles"].includes(config.key)) this.createIfNotExists = async () => {
24623
+ if (config.ops?.create === false || isScopedAttachmentResource(config.key) || ["company_attachments", "task_predecessors", "knowledge_base_articles", "inventory_locations"].includes(config.key)) this.createIfNotExists = async () => {
24114
24624
  throw new OperationNotSupportedError(config.key, "createIfNotExists");
24115
24625
  };
24116
24626
  if (config.key === "knowledge_base_categories") {
@@ -24225,9 +24735,9 @@ var GenericResource = class extends BaseResource {
24225
24735
  return this.createScopedRaw(parentId, data2, opts2);
24226
24736
  }
24227
24737
  if (this.config.opForms?.create === "scoped") throw new OperationNotSupportedError(this.config.key, "create");
24228
- const data = this.config.key === "knowledge_base_categories" ? admitKnowledgeBaseCategory(a, true) : a;
24738
+ const data = this.config.key === "knowledge_base_categories" ? admitKnowledgeBaseCategory(a, true) : this.config.key === "inventory_locations" ? admitInventoryLocation(a, true) : a;
24229
24739
  const supplied = b;
24230
- const opts = this.config.key === "knowledge_base_categories" ? snapshotMutationOptions(supplied) : supplied ?? {};
24740
+ const opts = ["knowledge_base_categories", "inventory_locations"].includes(this.config.key) ? snapshotMutationOptions(supplied) : supplied ?? {};
24231
24741
  if (opts.dryRun === true) return this.runCreateDryRun(data);
24232
24742
  return this.createGlobal(data, opts);
24233
24743
  }
@@ -24254,8 +24764,24 @@ var GenericResource = class extends BaseResource {
24254
24764
  }
24255
24765
  if (this.config.opForms?.update === "scoped") throw new OperationNotSupportedError(this.config.key, "update");
24256
24766
  const category = this.config.key === "knowledge_base_categories";
24257
- const id = category ? parseIdentifier(a, "id") : a;
24767
+ const location = this.config.key === "inventory_locations";
24768
+ const id = category || location ? parseIdentifier(a, "id") : a;
24258
24769
  const supplied = c;
24770
+ if (location) {
24771
+ const body = admitInventoryLocation(b, false);
24772
+ const opts2 = snapshotMutationOptions(supplied);
24773
+ if (opts2.lastModifiedDate !== void 0) throw new AutotaskConfigError("inventory_locations: no documented stale timestamp is available");
24774
+ const checkCurrent = (current) => checkInventoryLocationCurrent(body, current);
24775
+ if (opts2.dryRun === true) return this.runUpdateDryRun(id, body, opts2, void 0, void 0, { checkCurrent });
24776
+ const checkedBaseUrl = this.http.baseUrl;
24777
+ try {
24778
+ checkCurrent(await this.getGlobal(id, true, opts2.maxRetries, checkedBaseUrl));
24779
+ } catch (error) {
24780
+ if (error instanceof AutotaskError) Object.assign(error, { notSent: true });
24781
+ throw error;
24782
+ }
24783
+ return this.updateGlobal(id, body, opts2, "PATCH", checkedBaseUrl);
24784
+ }
24259
24785
  const opts = category ? snapshotMutationOptions(supplied) : supplied ?? {};
24260
24786
  if (category && opts.raw === true) throw new AutotaskConfigError("knowledge_base_categories: raw update is unsupported; a fresh merge is required");
24261
24787
  const data = category ? admitKnowledgeBaseCategory(b, false, opts.lastModifiedDate) : b;
@@ -24308,7 +24834,7 @@ var GenericResource = class extends BaseResource {
24308
24834
  /** Get the record with its primary context records in one call (each part a
24309
24835
  * single-record fetch; no sub-lists; absent/dangling references come back null).
24310
24836
  * `names: true` (projects) adds the opt-in name siblings + the top-level `names`
24311
- * section; `maxNameReads` may lower the name-read budget (default 20), never raise it. */
24837
+ * section; `maxNameReads` may lower the name-read budget (default 50), never raise it. */
24312
24838
  async getContext(id, opts = {}) {
24313
24839
  this.requireHelper("getContext");
24314
24840
  const cfg = this.config;
@@ -24481,7 +25007,7 @@ function prepare(query, opts) {
24481
25007
  function companyPieces(terms) {
24482
25008
  return textFragments(terms);
24483
25009
  }
24484
- function score(record, terms, source) {
25010
+ function score2(record, terms, source) {
24485
25011
  const match = scoreTerms(terms, companyTerms(record.companyName ?? ""));
24486
25012
  return match === void 0 ? void 0 : { record, source, ...match };
24487
25013
  }
@@ -24511,7 +25037,7 @@ async function searchFuzzy(resource, query, opts = {}) {
24511
25037
  const validIndex = index?.revision() === revision;
24512
25038
  for (const row of validIndex ? indexed : []) if (typeof row.id === "number") merged.set(row.id, { row, source: "index" });
24513
25039
  for (const row of live) if (typeof row.id === "number") merged.set(row.id, { row: slimCompany(row), source: merged.has(row.id) ? "both" : "live" });
24514
- const ranked = [...merged.values()].filter(({ row }) => opts.includeInactive || row.isActive === true).map(({ row, source }) => score(row, terms, source)).filter((row) => row !== void 0).sort((a, b) => compareTermScores(a, b) || Number(b.record.isActive === true) - Number(a.record.isActive === true) || (a.record.id ?? 0) - (b.record.id ?? 0));
25040
+ const ranked = [...merged.values()].filter(({ row }) => opts.includeInactive || row.isActive === true).map(({ row, source }) => score2(row, terms, source)).filter((row) => row !== void 0).sort((a, b) => compareTermScores(a, b) || Number(b.record.isActive === true) - Number(a.record.isActive === true) || (a.record.id ?? 0) - (b.record.id ?? 0));
24515
25041
  const items = ranked.slice(0, limit);
24516
25042
  if (opts.includeFamily) {
24517
25043
  const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
@@ -24984,11 +25510,6 @@ function monthsBefore(date, months) {
24984
25510
  return new Date(Date.UTC(y, m - 1 - months, Math.min(d, lastDay))).toISOString().slice(0, 10);
24985
25511
  }
24986
25512
 
24987
- // src/resources/special/_shared/numbers.ts
24988
- function num(v) {
24989
- return typeof v === "number" && Number.isFinite(v) ? v : 0;
24990
- }
24991
-
24992
25513
  // src/resources/special/companies/shared.ts
24993
25514
  var DEFAULT_LIMIT = 25;
24994
25515
  var MAX_LIMIT = 500;
@@ -26034,7 +26555,7 @@ function dateBucketLabel(value, bucket) {
26034
26555
  var queryResourceKeysPromise = null;
26035
26556
  function queryResourceKeys() {
26036
26557
  if (queryResourceKeysPromise === null) {
26037
- queryResourceKeysPromise = chunkEYRQUMA2_cjs.loadCapabilityRecords().then((records) => {
26558
+ queryResourceKeysPromise = chunkSHJ7EOBW_cjs.loadCapabilityRecords().then((records) => {
26038
26559
  const s = /* @__PURE__ */ new Set();
26039
26560
  for (const rec of records) if (rec.operation === "query") s.add(rec.resource);
26040
26561
  return s;
@@ -26156,7 +26677,7 @@ function parseTopAndLimit(opts, problems) {
26156
26677
  return { top, limit };
26157
26678
  }
26158
26679
  async function checkFieldNames(resourceKey, conditions, opts, problems) {
26159
- const records = resourceKey === void 0 ? [] : await chunkEYRQUMA2_cjs.loadCapabilityRecords();
26680
+ const records = resourceKey === void 0 ? [] : await chunkSHJ7EOBW_cjs.loadCapabilityRecords();
26160
26681
  const record = resourceKey === void 0 ? void 0 : records.find((r) => r.resource === resourceKey && r.operation === "query");
26161
26682
  if (record === void 0) return void 0;
26162
26683
  const strings = (v) => Array.isArray(v) ? v.filter((f) => typeof f === "string" && f.trim() !== "") : [];
@@ -26278,167 +26799,6 @@ async function aggregate(client, operation, filter, opts = {}) {
26278
26799
  return result;
26279
26800
  }
26280
26801
 
26281
- // src/resources/special/_shared/finance.ts
26282
- function budgetExceededError(operation, message, details, suggestedAction) {
26283
- return new AutotaskError(message, { code: "BUDGET_EXCEEDED", category: "policy", operation, details, suggestedAction });
26284
- }
26285
- function makeCallBudget(budget, onExceed) {
26286
- let spent = 0;
26287
- return {
26288
- spend() {
26289
- if (spent >= budget) throw onExceed(spent);
26290
- spent += 1;
26291
- },
26292
- spent: () => spent
26293
- };
26294
- }
26295
- function countingHttp(raw, spend) {
26296
- const http = Object.create(raw);
26297
- http.request = (o) => {
26298
- spend();
26299
- return raw.request(o);
26300
- };
26301
- return http;
26302
- }
26303
- function idChunks(ids2, size) {
26304
- const out = [];
26305
- for (let i = 0; i < ids2.length; i += size) out.push(ids2.slice(i, i + size));
26306
- return out;
26307
- }
26308
- async function fetchIdChunks(http, entityPath, ids2, fields, operation, opts) {
26309
- const chunkSize = opts?.chunkSize ?? 250;
26310
- const out = /* @__PURE__ */ new Map();
26311
- for (const chunk of idChunks(ids2, chunkSize)) {
26312
- opts?.budgetSpend?.();
26313
- const chunkKeys = new Set(chunk.map((id) => String(id)));
26314
- try {
26315
- const req = buildQueryRequest(http.baseUrl, entityPath, {
26316
- filter: [{ field: "id", op: "in", value: chunk }],
26317
- maxRecords: opts?.maxRecords ?? chunkSize,
26318
- includeFields: fields
26319
- });
26320
- const res = await http.request({ ...req, operation });
26321
- const { items: rows } = unwrapItems(res, operation);
26322
- for (const row of rows) {
26323
- const k = String(row["id"]);
26324
- if (!chunkKeys.has(k)) continue;
26325
- out.set(k, row);
26326
- }
26327
- } catch (err) {
26328
- if (opts?.onChunkFault?.(chunk, err) !== true) throw err;
26329
- }
26330
- }
26331
- return out;
26332
- }
26333
- function internalAmount(row, internalKey, localKey) {
26334
- const v = row[internalKey];
26335
- return typeof v === "number" && Number.isFinite(v) ? v : num(row[localKey]);
26336
- }
26337
- function toCents(v) {
26338
- return Math.round(num(v) * 100);
26339
- }
26340
- async function readPicklists(http, entityPath, operation) {
26341
- const res = await http.request({ method: "GET", path: `${entityPath}/entityInformation/fields`, operation });
26342
- const body = typeof res === "object" && res !== null ? res : {};
26343
- const fields = Array.isArray(body["fields"]) ? body["fields"] : [];
26344
- const out = /* @__PURE__ */ new Map();
26345
- for (const f of fields) {
26346
- if (f["isPickList"] !== true || typeof f["name"] !== "string" || !Array.isArray(f["picklistValues"])) continue;
26347
- const values = /* @__PURE__ */ new Map();
26348
- for (const p of f["picklistValues"]) {
26349
- const id = typeof p["value"] === "string" ? Number.parseInt(p["value"], 10) : Number.NaN;
26350
- if (Number.isFinite(id)) values.set(id, String(p["label"] ?? ""));
26351
- }
26352
- out.set(f["name"], values);
26353
- }
26354
- return out;
26355
- }
26356
- function resolveSelector(operation, name, sel, values) {
26357
- const out = /* @__PURE__ */ new Map();
26358
- const misses = [];
26359
- for (const s of sel) {
26360
- const hits = typeof s === "number" ? values.has(s) ? [s] : [] : [...values].filter(([, l]) => l.trim().toLowerCase() === s.trim().toLowerCase()).map(([id]) => id);
26361
- if (hits.length === 0) misses.push(JSON.stringify(s));
26362
- for (const h of hits) out.set(h, values.get(h));
26363
- }
26364
- if (misses.length > 0) throw selectorUnmatched(operation, name, `${misses.join(", ")} matched no live value`, values);
26365
- return out;
26366
- }
26367
- function selectorUnmatched(operation, name, what, values) {
26368
- const live = [...values].map(([id, l]) => `${id} ${l}`).join("; ") || "(the picklist serves no values)";
26369
- return new AutotaskConfigError(`${shortName(operation)}: ${name}: ${what}. Live values (id label): ${live}`, {
26370
- operation,
26371
- suggestedAction: `Pass ${name} as ids or exact labels from the live list.`
26372
- });
26373
- }
26374
- var TENANT_HOURLY_LIMIT = 1e4;
26375
- function tenantHourlyShare(calls) {
26376
- return `${(calls / TENANT_HOURLY_LIMIT * 100).toFixed(2)}% of ${TENANT_HOURLY_LIMIT.toLocaleString("en-US")}/h`;
26377
- }
26378
- var isPosInt = (v) => Number.isSafeInteger(v) && v > 0;
26379
- function checkIdList(name, v, max, problems, opts) {
26380
- const ok = opts?.allowZero ? (x) => x === 0 || isPosInt(x) : isPosInt;
26381
- if (!Array.isArray(v) || v.length === 0 || v.length > max || !v.every(ok)) {
26382
- problems.push(`${name} must be a non-empty array of at most ${max} ${opts?.allowZero ? "non-negative" : "positive"} integer ids`);
26383
- return void 0;
26384
- }
26385
- return [...new Set(v)].sort((a, b) => a - b);
26386
- }
26387
- function checkSelector(name, v, problems) {
26388
- if (v === void 0) return void 0;
26389
- if (!Array.isArray(v) || v.length === 0 || !v.every((x) => isPosInt(x) || typeof x === "string" && x.trim() !== "")) {
26390
- problems.push(`${name} must be a non-empty array of picklist ids or labels`);
26391
- return void 0;
26392
- }
26393
- return v;
26394
- }
26395
- function checkInt(name, v, def, max, problems) {
26396
- if (v === void 0) return def;
26397
- if (!Number.isInteger(v) || v < 1 || v > max) {
26398
- problems.push(`${name} must be an integer 1..${max} (got ${String(v)})`);
26399
- return def;
26400
- }
26401
- return v;
26402
- }
26403
- async function collectRows(res, filter, includeFields, page) {
26404
- const out = [];
26405
- for await (const r of res.query({ filter, includeFields, maxRecords: page, names: false })) out.push(r);
26406
- return out;
26407
- }
26408
- function blindCountError(operation, subject, suggestedAction) {
26409
- return new AutotaskError(`${shortName(operation)}: a gate count came back blind (unknown, not zero); ${subject} cannot be sized`, {
26410
- code: "INVALID_RESPONSE",
26411
- category: "server",
26412
- operation,
26413
- details: { reason: "blind_count" },
26414
- suggestedAction
26415
- });
26416
- }
26417
- function countMismatchError(operation, what, streamed, counted, rows) {
26418
- const rowNote = rows !== void 0 && rows !== streamed ? ` (${rows} rows)` : "";
26419
- return new AutotaskError(`${shortName(operation)}: the ${what} stream returned ${streamed} distinct ids${rowNote} but the gate count was ${counted} (the data changed mid-walk or a page dropped rows); the fold was discarded`, {
26420
- code: "INVALID_RESPONSE",
26421
- category: "server",
26422
- operation,
26423
- details: { reason: "count_mismatch", stream: what, streamed, counted },
26424
- suggestedAction: "Retry the call."
26425
- });
26426
- }
26427
- function compareIds(a, b) {
26428
- for (let i = 0; i < a.length; i++) {
26429
- const x = a[i] ?? null;
26430
- const y = b[i] ?? null;
26431
- if (x === y) continue;
26432
- if (x === null) return -1;
26433
- if (y === null) return 1;
26434
- if (typeof x === "number" && typeof y === "number") return x - y;
26435
- return String(x) < String(y) ? -1 : 1;
26436
- }
26437
- return 0;
26438
- }
26439
- var sortedRecord = (m) => Object.fromEntries([...m].sort((a, b) => a[0] - b[0]).map(([id, l]) => [String(id), l]));
26440
- var shortName = (operation) => operation.split(".").pop() ?? operation;
26441
-
26442
26802
  // src/operations/fetchByIds.ts
26443
26803
  var FETCH_BY_IDS_MAX_ITEMS = 500;
26444
26804
  var FETCH_BY_IDS_CHUNK_SIZE = 250;
@@ -26514,8 +26874,9 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
26514
26874
  try {
26515
26875
  const id = parseIdentifier(item.id, `${at}.id`);
26516
26876
  const audit = isAuditLogResource(resourceKey);
26517
- if ((audit || isKnowledgeBaseRootResource(resourceKey)) && !isAuditDecimalId(String(id))) {
26518
- problems.push(`${at}.id: ${audit ? "audit log" : "Knowledge Base record"} ID must be a non-negative signed 64-bit integer`);
26877
+ if ((audit || isExactRecordResource(resourceKey)) && !isAuditDecimalId(String(id))) {
26878
+ const label = audit ? "audit log" : resourceKey === "inventory_locations" ? "inventory location" : "Knowledge Base record";
26879
+ problems.push(`${at}.id: ${label} ID must be a non-negative signed 64-bit integer`);
26519
26880
  }
26520
26881
  } catch {
26521
26882
  if (typeof item.id === "string") {
@@ -26809,7 +27170,7 @@ async function uiLink(client, input) {
26809
27170
  var indexPromise = null;
26810
27171
  function operationIndex() {
26811
27172
  if (indexPromise === null) {
26812
- indexPromise = chunkEYRQUMA2_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
27173
+ indexPromise = chunkSHJ7EOBW_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
26813
27174
  }
26814
27175
  return indexPromise;
26815
27176
  }
@@ -26830,7 +27191,7 @@ async function sanitiseResult(client, result, operation) {
26830
27191
  );
26831
27192
  }
26832
27193
  const fields = record.metadata?.untrustedFields;
26833
- return chunkBD4AUGCJ_cjs.deepMarkUntrusted(result, Array.isArray(fields) ? fields : []);
27194
+ return chunkCM5O672I_cjs.deepMarkUntrusted(result, Array.isArray(fields) ? fields : []);
26834
27195
  }
26835
27196
 
26836
27197
  // src/resources/special/invoices.ts
@@ -28881,7 +29242,7 @@ function buildMiscoding(fc, crossTimeEntries, unresolvedRefs) {
28881
29242
  return [...miscoding.values()].sort((a, b) => a.entryId - b.entryId).slice(0, fc.v.limit);
28882
29243
  }
28883
29244
  function vendorLabel(value, fallback) {
28884
- return typeof value === "string" && value !== "" ? chunkBD4AUGCJ_cjs.wrapUntrusted(value) ?? value : fallback;
29245
+ return typeof value === "string" && value !== "" ? chunkCM5O672I_cjs.wrapUntrusted(value) ?? value : fallback;
28885
29246
  }
28886
29247
  function openTicketItems(fc) {
28887
29248
  const { openStatusSet } = fc.f.open;
@@ -29145,16 +29506,16 @@ function latchingHttp(raw, spend) {
29145
29506
  }
29146
29507
  };
29147
29508
  observeRecordReadFailures(http, latch);
29148
- const fail3 = (err) => {
29509
+ const fail4 = (err) => {
29149
29510
  latch(err);
29150
29511
  throw err;
29151
29512
  };
29152
29513
  http.request = (o) => {
29153
29514
  if (fatal) throw fatal;
29154
29515
  try {
29155
- return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail3);
29516
+ return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail4);
29156
29517
  } catch (err) {
29157
- return fail3(err);
29518
+ return fail4(err);
29158
29519
  }
29159
29520
  };
29160
29521
  return { http, fatal: () => fatal, signal };