node-autotask 0.85.0 → 0.87.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 (40) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/MCP_TOOL_CATALOG.json +336 -9
  3. package/README.md +1 -1
  4. package/capabilities.json +1411 -218
  5. package/dist/capabilities-data.js +1562 -369
  6. package/dist/capabilities.cjs +4 -4
  7. package/dist/capabilities.js +1 -1
  8. package/dist/{chunk-7GNZT7Y7.cjs → chunk-CUZJJCI5.cjs} +1231 -438
  9. package/dist/{chunk-GTTAPAGP.js → chunk-EXNDYJPG.js} +3 -3
  10. package/dist/{chunk-EPJG7M5C.js → chunk-G57Q7OAC.js} +2 -2
  11. package/dist/{chunk-L6YCH2I4.js → chunk-GAFG7RHG.js} +1226 -433
  12. package/dist/{chunk-PBOH2OHJ.cjs → chunk-HUA4WB4N.cjs} +32 -30
  13. package/dist/{chunk-HF5YG4TV.js → chunk-NXSQXXNK.js} +4 -2
  14. package/dist/{chunk-JV6MX2U3.cjs → chunk-RU4ECNQN.cjs} +200 -200
  15. package/dist/{chunk-JCKYM7FD.cjs → chunk-YVNGUGG6.cjs} +3 -3
  16. package/dist/{index-rWcPjRpX.d.ts → index-CsL5gGJo.d.ts} +33 -13
  17. package/dist/{index-CCW_EpLg.d.cts → index-Cxfr_DOD.d.cts} +76 -3
  18. package/dist/{index-CCW_EpLg.d.ts → index-Cxfr_DOD.d.ts} +76 -3
  19. package/dist/{index-DkyNXWyt.d.cts → index-DGiua9uK.d.cts} +33 -13
  20. package/dist/index.cjs +84 -84
  21. package/dist/index.d.cts +3 -3
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +5 -5
  24. package/dist/operations/index.cjs +51 -51
  25. package/dist/operations/index.d.cts +5 -20
  26. package/dist/operations/index.d.ts +5 -20
  27. package/dist/operations/index.js +2 -2
  28. package/dist/pool.cjs +12 -12
  29. package/dist/pool.d.cts +1 -1
  30. package/dist/pool.d.ts +1 -1
  31. package/dist/pool.js +4 -4
  32. package/dist/resources/index.cjs +27 -27
  33. package/dist/resources/index.d.cts +2 -2
  34. package/dist/resources/index.d.ts +2 -2
  35. package/dist/resources/index.js +3 -3
  36. package/dist/types/index.d.cts +1 -1
  37. package/dist/types/index.d.ts +1 -1
  38. package/docs/API.md +4 -2
  39. package/docs/VENDOR-QUIRKS.md +34 -17
  40. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkJCKYM7FD_cjs = require('./chunk-JCKYM7FD.cjs');
3
+ var chunkYVNGUGG6_cjs = require('./chunk-YVNGUGG6.cjs');
4
4
  var chunkBD4AUGCJ_cjs = require('./chunk-BD4AUGCJ.cjs');
5
5
  var crypto = require('crypto');
6
6
  var async_hooks = require('async_hooks');
@@ -1452,6 +1452,15 @@ function isAuditDecimalId(id) {
1452
1452
  function isRecord2(value) {
1453
1453
  return typeof value === "object" && value !== null && !Array.isArray(value);
1454
1454
  }
1455
+ function snapshotFields(record, keys) {
1456
+ const captured = { ...record };
1457
+ for (const key of keys) {
1458
+ if (Object.hasOwn(captured, key)) continue;
1459
+ const value = Reflect.get(record, key);
1460
+ if (value !== void 0) captured[key] = value;
1461
+ }
1462
+ return captured;
1463
+ }
1455
1464
  function isIdentifierCandidate(value) {
1456
1465
  return typeof value === "number" || typeof value === "string" && /^\d+$/.test(value.trim());
1457
1466
  }
@@ -1614,11 +1623,66 @@ function buildFilter(conditions) {
1614
1623
  function normalizedConditions(filter) {
1615
1624
  if (filter === void 0 || filter === null) return void 0;
1616
1625
  if (Array.isArray(filter)) return normalizeInValues(filter);
1617
- if (isRecord2(filter) && Array.isArray(filter.filter)) return normalizeInValues(filter.filter);
1618
- throw new AutotaskConfigError(
1626
+ if (isRecord2(filter)) {
1627
+ const conditions = filter.filter;
1628
+ if (Array.isArray(conditions)) return normalizeInValues(conditions);
1629
+ }
1630
+ throw invalidFilterShape(filter);
1631
+ }
1632
+ function invalidFilterShape(filter) {
1633
+ return new AutotaskConfigError(
1619
1634
  `filter must be a conditions array or { filter: [...] } (e.g. { filter: [{ field: 'status', op: 'eq', value: 'Open' }] }) \u2014 got ${refusedFilterShape(filter)}`
1620
1635
  );
1621
1636
  }
1637
+ function snapshotCondition(condition) {
1638
+ if (!isRecord2(condition)) return condition;
1639
+ const captured = snapshotFields(condition, ["op", "field", "udf", "value", "items"]);
1640
+ delete captured.toJSON;
1641
+ for (const [key, value] of Object.entries(captured)) {
1642
+ if (key.toLowerCase() !== "udf") continue;
1643
+ if (value !== void 0 && typeof value !== "boolean") {
1644
+ throw new AutotaskConfigError("The filter udf flag must be a boolean.");
1645
+ }
1646
+ if (key !== "udf") {
1647
+ if (Object.hasOwn(captured, "udf")) throw new AutotaskConfigError("The filter udf flag must appear once.");
1648
+ delete captured[key];
1649
+ captured.udf = value;
1650
+ }
1651
+ }
1652
+ if (Array.isArray(captured.value)) {
1653
+ const values2 = captured.value;
1654
+ captured.value = Array.from({ length: values2.length }, (_, i) => values2[i]);
1655
+ }
1656
+ const values = Array.isArray(captured.value) ? captured.value : [captured.value];
1657
+ if (values.some((value) => typeof value === "number" && !Number.isFinite(value))) {
1658
+ throw new AutotaskConfigError("Numeric filter values must be finite.");
1659
+ }
1660
+ if (Array.isArray(captured.items)) captured.items = snapshotConditions(captured.items);
1661
+ return captured;
1662
+ }
1663
+ function snapshotConditions(conditions) {
1664
+ return Array.from({ length: conditions.length }, (_, i) => snapshotCondition(conditions[i]));
1665
+ }
1666
+ function snapshotQueryFilter(filter) {
1667
+ if (filter == null) return filter;
1668
+ if (Array.isArray(filter)) return snapshotConditions(filter);
1669
+ if (isRecord2(filter)) {
1670
+ const conditions = filter.filter;
1671
+ if (Array.isArray(conditions)) return { filter: snapshotConditions(conditions) };
1672
+ }
1673
+ throw invalidFilterShape(filter);
1674
+ }
1675
+ function snapshotQueryBag(bag, keys) {
1676
+ const snapshot = snapshotFields(bag, keys);
1677
+ const captured = snapshot;
1678
+ if (captured.filter !== void 0) captured.filter = snapshotQueryFilter(captured.filter);
1679
+ if (Array.isArray(captured.includeFields)) {
1680
+ const fields = captured.includeFields;
1681
+ captured.includeFields = Array.from({ length: fields.length }, (_, i) => fields[i]);
1682
+ }
1683
+ if (isRecord2(captured.walk)) captured.walk = snapshotFields(captured.walk, ["maxRows"]);
1684
+ return snapshot;
1685
+ }
1622
1686
  function normalizeInValues(conditions, path = "filter") {
1623
1687
  const out = conditions.map((cond, i) => normalizeInCondition(cond, `${path}[${i}]`));
1624
1688
  return out.every((cond, i) => cond === conditions[i]) ? conditions : out;
@@ -1630,13 +1694,13 @@ function normalizeInCondition(cond, path) {
1630
1694
  return items === cond.items ? cond : { ...cond, items };
1631
1695
  }
1632
1696
  if (cond.op !== "in" && cond.op !== "notIn" || typeof cond.value !== "string") return cond;
1633
- const tokens = cond.value.split(",").map((t) => t.trim()).filter((t) => t.length > 0);
1634
- if (tokens.length === 0) {
1697
+ const tokens2 = cond.value.split(",").map((t) => t.trim()).filter((t) => t.length > 0);
1698
+ if (tokens2.length === 0) {
1635
1699
  throw new AutotaskConfigError(
1636
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")`
1637
1701
  );
1638
1702
  }
1639
- 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);
1640
1704
  return { ...cond, value };
1641
1705
  }
1642
1706
  function refusedFilterShape(filter) {
@@ -1646,22 +1710,22 @@ function refusedFilterShape(filter) {
1646
1710
  if (t === "object" || t === "function") return "an object";
1647
1711
  return t === "string" ? "a string" : `a ${t}`;
1648
1712
  }
1649
- function assertQueryFilterForWire(conditions, operation, auditIds) {
1713
+ function assertQueryFilterForWire(conditions, operation, exactIdLabel) {
1650
1714
  if (!Array.isArray(conditions)) return;
1651
1715
  for (const input of conditions) {
1652
1716
  if (!isRecord2(input)) continue;
1653
- const c = auditIds ? {} : input;
1654
- if (auditIds) {
1717
+ const c = exactIdLabel === void 0 ? input : {};
1718
+ if (exactIdLabel !== void 0) {
1655
1719
  for (const [key, value] of Object.entries(input)) {
1656
1720
  const lower = key.toLowerCase();
1657
1721
  if (!["op", "field", "value", "items", "udf"].includes(lower)) continue;
1658
1722
  if (Object.hasOwn(c, lower)) {
1659
- throw new AutotaskConfigError("Audit filter predicates must provide each field once.", { operation });
1723
+ throw new AutotaskConfigError("Exact-ID filter predicates must provide each field once.", { operation });
1660
1724
  }
1661
1725
  c[lower] = value;
1662
1726
  }
1663
1727
  }
1664
- if (Array.isArray(c.items)) assertQueryFilterForWire(c.items, operation, auditIds);
1728
+ if (Array.isArray(c.items)) assertQueryFilterForWire(c.items, operation, exactIdLabel);
1665
1729
  if (c.udf === true || typeof c.field !== "string") continue;
1666
1730
  if (c.field.includes(".")) {
1667
1731
  throw new AutotaskConfigError(
@@ -1669,11 +1733,11 @@ function assertQueryFilterForWire(conditions, operation, auditIds) {
1669
1733
  { operation, suggestedAction: "Use a query surface that resolves relation filters (query, queryAll, queryBounded, count, operations.aggregate), or filter by the <relation>ID field directly." }
1670
1734
  );
1671
1735
  }
1672
- if (auditIds && c.field.trim().toLowerCase() === "id") {
1736
+ if (exactIdLabel !== void 0 && c.field.trim().toLowerCase() === "id") {
1673
1737
  const values = Array.isArray(c.value) ? c.value : [c.value];
1674
1738
  if (c.value === void 0 && (c.op === "exist" || c.op === "notExist")) continue;
1675
1739
  if (values.length === 0 || values.some((value) => typeof value === "number" ? !Number.isSafeInteger(value) || value < 0 : typeof value !== "string" || !isAuditDecimalId(value))) {
1676
- throw new AutotaskConfigError(`${operation}: audit log ID filters require a safe integer or an exact decimal string.`, {
1740
+ throw new AutotaskConfigError(`${operation}: ${exactIdLabel} ID filters require a safe integer or an exact decimal string.`, {
1677
1741
  operation,
1678
1742
  suggestedAction: "Pass each large ID as an exact decimal string."
1679
1743
  });
@@ -10760,6 +10824,120 @@ var RELATIONSHIP_MAP = {
10760
10824
  "zoneFacts": null,
10761
10825
  "deleteBoundary": null,
10762
10826
  "markerField": null
10827
+ },
10828
+ "knowledge_base_categories": {
10829
+ "resource": "knowledge_base_categories",
10830
+ "apiEntity": "KnowledgeBaseCategory",
10831
+ "kind": "entity",
10832
+ "path": "KnowledgeBaseCategories",
10833
+ "parentScoped": false,
10834
+ "tier": "extended",
10835
+ "workflowResource": false,
10836
+ "group": "B",
10837
+ "parent": null,
10838
+ "children": [
10839
+ {
10840
+ "resource": "knowledge_base_articles",
10841
+ "apiEntity": "KnowledgeBaseArticle",
10842
+ "parentField": "articleCategoryID",
10843
+ "parentSegment": "KnowledgeBaseArticles",
10844
+ "tier": "extended",
10845
+ "workflowResource": false,
10846
+ "specialOps": [],
10847
+ "searchCovers": null,
10848
+ "scopedOps": {
10849
+ "create": true,
10850
+ "query": true,
10851
+ "update": true,
10852
+ "delete": true
10853
+ }
10854
+ }
10855
+ ],
10856
+ "naturalKeys": {
10857
+ "hasSearch": false,
10858
+ "searchCovers": null,
10859
+ "findBy": []
10860
+ },
10861
+ "blindSurfaces": null,
10862
+ "zoneFacts": {
10863
+ "createGuidance": {
10864
+ "createOp": "knowledge_base_categories.create",
10865
+ "parentScoped": false,
10866
+ "liveProvenPrefix": [],
10867
+ "unproven": true,
10868
+ "blocker": {
10869
+ "kind": "unknown",
10870
+ "message": "Knowledgebase category creation is documented but not verified; hierarchy and API-user security restrict use.",
10871
+ "remedy": "Discover a visible parent category and preview; hierarchy and permission checks remain vendor-owned.",
10872
+ "requires": {
10873
+ "allOf": [
10874
+ "name",
10875
+ "parentCategoryID"
10876
+ ]
10877
+ }
10878
+ },
10879
+ "vendorEvidence": [
10880
+ "https://www.autotask.net/help/developerhelp/content/apis/rest/Entities/KnowledgeBaseCategoriesEntity.htm"
10881
+ ],
10882
+ "deleteBoundary": {
10883
+ "available": true,
10884
+ "note": "Category DELETE reassigns associated articles to the parent; it does not restore previous article placement."
10885
+ }
10886
+ }
10887
+ },
10888
+ "deleteBoundary": null,
10889
+ "markerField": null
10890
+ },
10891
+ "knowledge_base_articles": {
10892
+ "resource": "knowledge_base_articles",
10893
+ "apiEntity": "KnowledgeBaseArticle",
10894
+ "kind": "entity",
10895
+ "path": "KnowledgeBaseArticles",
10896
+ "parentScoped": true,
10897
+ "tier": "extended",
10898
+ "workflowResource": false,
10899
+ "group": "B",
10900
+ "parent": {
10901
+ "resource": "knowledge_base_categories",
10902
+ "segment": "KnowledgeBaseArticles",
10903
+ "field": "articleCategoryID"
10904
+ },
10905
+ "children": [],
10906
+ "naturalKeys": {
10907
+ "hasSearch": false,
10908
+ "searchCovers": null,
10909
+ "findBy": []
10910
+ },
10911
+ "blindSurfaces": null,
10912
+ "zoneFacts": {
10913
+ "createGuidance": {
10914
+ "createOp": "knowledge_base_articles.create",
10915
+ "parentScoped": true,
10916
+ "liveProvenPrefix": [],
10917
+ "unproven": true,
10918
+ "blocker": {
10919
+ "kind": "unknown",
10920
+ "message": "Knowledgebase article creation is documented; API-user permissions and hidden draft restrictions remain conditional.",
10921
+ "remedy": "Choose a visible category, inspect publish field metadata and preview the article root. Content is a separate workflow.",
10922
+ "requires": {
10923
+ "allOf": [
10924
+ "articleCategoryID",
10925
+ "publish",
10926
+ "title"
10927
+ ]
10928
+ }
10929
+ },
10930
+ "vendorEvidence": [
10931
+ "https://autotask.net/help/developerhelp/Content/APIs/REST/Entities/KnowledgeBaseArticlesEntity.htm"
10932
+ ],
10933
+ "deleteBoundary": {
10934
+ "available": true,
10935
+ "note": null
10936
+ }
10937
+ }
10938
+ },
10939
+ "deleteBoundary": null,
10940
+ "markerField": null
10763
10941
  }
10764
10942
  };
10765
10943
  var BLIND_SURFACE_STAMPS = {
@@ -13814,6 +13992,57 @@ var CREATE_GUIDANCE = {
13814
13992
  "note": null
13815
13993
  }
13816
13994
  },
13995
+ {
13996
+ "resource": "knowledge_base_articles",
13997
+ "createOp": "knowledge_base_articles.create",
13998
+ "parentScoped": true,
13999
+ "liveProvenPrefix": [],
14000
+ "unproven": true,
14001
+ "blocker": {
14002
+ "kind": "unknown",
14003
+ "message": "Knowledgebase article creation is documented; API-user permissions and hidden draft restrictions remain conditional.",
14004
+ "remedy": "Choose a visible category, inspect publish field metadata and preview the article root. Content is a separate workflow.",
14005
+ "requires": {
14006
+ "allOf": [
14007
+ "articleCategoryID",
14008
+ "publish",
14009
+ "title"
14010
+ ]
14011
+ }
14012
+ },
14013
+ "vendorEvidence": [
14014
+ "https://autotask.net/help/developerhelp/Content/APIs/REST/Entities/KnowledgeBaseArticlesEntity.htm"
14015
+ ],
14016
+ "deleteBoundary": {
14017
+ "available": true,
14018
+ "note": null
14019
+ }
14020
+ },
14021
+ {
14022
+ "resource": "knowledge_base_categories",
14023
+ "createOp": "knowledge_base_categories.create",
14024
+ "parentScoped": false,
14025
+ "liveProvenPrefix": [],
14026
+ "unproven": true,
14027
+ "blocker": {
14028
+ "kind": "unknown",
14029
+ "message": "Knowledgebase category creation is documented but not verified; hierarchy and API-user security restrict use.",
14030
+ "remedy": "Discover a visible parent category and preview; hierarchy and permission checks remain vendor-owned.",
14031
+ "requires": {
14032
+ "allOf": [
14033
+ "name",
14034
+ "parentCategoryID"
14035
+ ]
14036
+ }
14037
+ },
14038
+ "vendorEvidence": [
14039
+ "https://www.autotask.net/help/developerhelp/content/apis/rest/Entities/KnowledgeBaseCategoriesEntity.htm"
14040
+ ],
14041
+ "deleteBoundary": {
14042
+ "available": true,
14043
+ "note": "Category DELETE reassigns associated articles to the parent; it does not restore previous article placement."
14044
+ }
14045
+ },
13817
14046
  {
13818
14047
  "resource": "opportunities",
13819
14048
  "createOp": "opportunities.create",
@@ -15318,7 +15547,7 @@ var CREATE_GUIDANCE = {
15318
15547
  }
15319
15548
  ],
15320
15549
  "counts": {
15321
- "total": 114,
15550
+ "total": 116,
15322
15551
  "byKind": {
15323
15552
  "ok": 41,
15324
15553
  "blind-reference": 16,
@@ -15328,7 +15557,7 @@ var CREATE_GUIDANCE = {
15328
15557
  "resource-role-pair": 2,
15329
15558
  "delete-absent": 0,
15330
15559
  "non-mutable": 0,
15331
- "unknown": 38
15560
+ "unknown": 40
15332
15561
  }
15333
15562
  }
15334
15563
  };
@@ -16097,6 +16326,16 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
16097
16326
  ],
16098
16327
  "deleted_ticket_logs": [
16099
16328
  "ticketTitle"
16329
+ ],
16330
+ "knowledge_base_categories": [
16331
+ "description",
16332
+ "name"
16333
+ ],
16334
+ "knowledge_base_articles": [
16335
+ "errorCodes",
16336
+ "keywords",
16337
+ "referenceLink",
16338
+ "title"
16100
16339
  ]
16101
16340
  };
16102
16341
 
@@ -16552,38 +16791,121 @@ function auditReadTarget(path, operation) {
16552
16791
  }
16553
16792
  return target;
16554
16793
  }
16555
- function decodeResponseJson(text, auditTarget) {
16556
- if (auditTarget === void 0) return JSON.parse(text);
16557
- if (auditTarget === "query/count") {
16794
+ function isKnowledgeBaseRootResource(resource) {
16795
+ return resource === "knowledge_base_categories" || resource === "knowledge_base_articles";
16796
+ }
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);
16800
+ if (match === null) return void 0;
16801
+ const suffix = match[1]?.toLowerCase();
16802
+ if (suffix === "query/count") return suffix;
16803
+ if (suffix?.startsWith("query")) return "query";
16804
+ if (suffix !== void 0 && !isAuditDecimalId(suffix)) {
16805
+ throw new AutotaskConfigError("Knowledge Base record ID must be a non-negative signed 64-bit integer.", { operation });
16806
+ }
16807
+ return method === "GET" ? suffix === void 0 ? void 0 : "item" : "mutation";
16808
+ }
16809
+ function isNonNegativeInt64(id) {
16810
+ return typeof id === "number" ? Number.isSafeInteger(id) && id >= 0 : typeof id === "string" && isAuditDecimalId(id);
16811
+ }
16812
+ function validateKnowledgeBaseResponse(body, target, path, method, requestBody, operation) {
16813
+ const invalid = (message) => {
16814
+ throw new AutotaskError(message, { code: "INVALID_RESPONSE", category: "server", operation, suggestedAction: INVALID_SHAPE_ACTION });
16815
+ };
16816
+ if (target === "query/count") {
16817
+ unwrapQueryCount(body, operation);
16818
+ return;
16819
+ }
16820
+ if (target === "query") {
16821
+ if (!isRecord2(body) || !Array.isArray(body.items) || !isRecord2(body.pageDetails)) {
16822
+ return invalid("Expected a Knowledge Base query page with paging details");
16823
+ }
16824
+ if (!body.items.every(hasExactRecordId)) invalid("Expected valid record IDs in the Knowledge Base query response");
16825
+ if (body.pageDetails.count !== body.items.length) {
16826
+ invalid("The Knowledge Base page record count did not match its rows");
16827
+ }
16828
+ const cursor = body.pageDetails.nextPageUrl;
16829
+ if (cursor !== null && (typeof cursor !== "string" || cursor.trim() === "")) {
16830
+ invalid("Expected a valid Knowledge Base query cursor or an explicit end of results");
16831
+ }
16832
+ return;
16833
+ }
16834
+ const parts = path.replace(/\/$/, "").split("/");
16835
+ const expectedId = parts.at(-1);
16836
+ if (target === "mutation") {
16837
+ 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");
16839
+ const expected = method === "DELETE" ? expectedId : isRecord2(requestBody) ? requestBody.id : void 0;
16840
+ if (expected !== void 0 && String(id) !== String(expected)) {
16841
+ invalid("The mutation response identified a different record. Re-read the requested record before retrying.");
16842
+ }
16843
+ return;
16844
+ }
16845
+ const item = isRecord2(body) ? body.item : void 0;
16846
+ if (item === null) return;
16847
+ if (!isRecord2(item) || !isNonNegativeInt64(item.id)) {
16848
+ return invalid("Expected a Knowledge Base item envelope with a valid record ID");
16849
+ }
16850
+ const resource = parts.at(-2)?.toLowerCase() === "knowledgebasearticles" ? "article" : "category";
16851
+ if (String(item.id) !== expectedId) {
16852
+ throw new AutotaskConfigError(`returned ${resource} id must match the requested id`, { operation });
16853
+ }
16854
+ if (parts.length === 6) {
16855
+ const parent = item.articleCategoryID;
16856
+ if (typeof parent !== "number" || !Number.isInteger(parent) || parent <= 0 || parent > 2147483647) {
16857
+ invalid("Expected a valid category ID in the Knowledge Base article response");
16858
+ }
16859
+ if (String(parent) !== parts[3]) {
16860
+ throw new AutotaskConfigError("returned article category must match parentId", { operation });
16861
+ }
16862
+ }
16863
+ }
16864
+ function serializeKnowledgeBaseUpdate(body, operation) {
16865
+ if (!isRecord2(body) || typeof body.id !== "string") return JSON.stringify(body);
16866
+ if (!isAuditDecimalId(body.id)) {
16867
+ throw new AutotaskConfigError("Knowledge Base update id must be a non-negative signed 64-bit integer.", { operation });
16868
+ }
16869
+ const { rawJSON } = JSON;
16870
+ return JSON.stringify({ ...body, id: rawJSON(body.id) });
16871
+ }
16872
+ function decodeResponseJson(text, auditTarget, knowledgeBaseTarget) {
16873
+ const target = auditTarget ?? knowledgeBaseTarget;
16874
+ if (target === void 0) return JSON.parse(text);
16875
+ if (target === "query/count") {
16558
16876
  return JSON.parse(text, (key, value, context) => key === "queryCount" && typeof value === "number" && !isAuditDecimalId(context?.source ?? "") ? null : value);
16559
16877
  }
16560
16878
  const idTokens = /* @__PURE__ */ new WeakMap();
16879
+ const receiptTokens = /* @__PURE__ */ new WeakMap();
16561
16880
  const body = JSON.parse(text, function(key, value, context) {
16562
- if (key === "id" && typeof value === "number" && context?.source !== void 0) {
16563
- idTokens.set(this, context.source);
16881
+ if (typeof value === "number" && context?.source !== void 0) {
16882
+ if (key === "id") idTokens.set(this, context.source);
16883
+ if (key === "itemId" && target === "mutation") receiptTokens.set(this, context.source);
16564
16884
  }
16565
16885
  return value;
16566
16886
  });
16567
- const rows = isRecord2(body) ? auditTarget === "query" ? body.items : [body.item] : void 0;
16887
+ const rows = isRecord2(body) ? target === "query" ? body.items : [target === "mutation" ? body : body.item] : void 0;
16568
16888
  if (Array.isArray(rows)) {
16569
16889
  for (const row of rows) {
16570
- if (!isRecord2(row) || typeof row.id !== "number") continue;
16571
- const token = idTokens.get(row);
16572
- if (token === void 0 || !isAuditDecimalId(token)) row.id = null;
16573
- else if (!Number.isSafeInteger(row.id)) row.id = token;
16890
+ if (!isRecord2(row)) continue;
16891
+ const key = target === "mutation" && row.itemId !== void 0 ? "itemId" : "id";
16892
+ const value = row[key];
16893
+ if (typeof value !== "number") continue;
16894
+ const token = (key === "id" ? idTokens : receiptTokens).get(row);
16895
+ if (token === void 0 || !isAuditDecimalId(token)) row[key] = null;
16896
+ else if (!Number.isSafeInteger(value)) row[key] = token;
16574
16897
  }
16575
16898
  }
16576
16899
  return body;
16577
16900
  }
16578
- function isAuditItem(item) {
16901
+ function hasExactRecordId(item) {
16579
16902
  if (!isRecord2(item)) return false;
16580
- const { id } = item;
16581
- return typeof id === "number" ? Number.isSafeInteger(id) && id >= 0 : typeof id === "string" && isAuditDecimalId(id);
16903
+ return isNonNegativeInt64(item.id);
16582
16904
  }
16583
16905
  function isAuditPage(body) {
16584
16906
  if (!Array.isArray(body.items) || !isRecord2(body.pageDetails)) return false;
16585
16907
  const { nextPageUrl } = body.pageDetails;
16586
- return (nextPageUrl === null || typeof nextPageUrl === "string" && nextPageUrl.trim() !== "") && body.items.every(isAuditItem);
16908
+ return (nextPageUrl === null || typeof nextPageUrl === "string" && nextPageUrl.trim() !== "") && body.items.every(hasExactRecordId);
16587
16909
  }
16588
16910
  function validateAuditResponse(body, target, operation) {
16589
16911
  if (target === void 0) return;
@@ -16591,7 +16913,7 @@ function validateAuditResponse(body, target, operation) {
16591
16913
  unwrapQueryCount(body, operation);
16592
16914
  return;
16593
16915
  }
16594
- const valid = isRecord2(body) && (target === "query" ? isAuditPage(body) : body.item === null || isAuditItem(body.item) && String(body.item.id) === target);
16916
+ const valid = isRecord2(body) && (target === "query" ? isAuditPage(body) : body.item === null || hasExactRecordId(body.item) && String(body.item.id) === target);
16595
16917
  if (!valid) {
16596
16918
  throw new AutotaskError("Expected a valid audit log response for the requested path.", {
16597
16919
  code: "INVALID_RESPONSE",
@@ -16626,7 +16948,7 @@ function attachEmptyReasonDetails(err) {
16626
16948
  } : {
16627
16949
  surface,
16628
16950
  kind: "not-found",
16629
- note: isDeletedAuditRead(surface) ? "No audit log entry at this ID was visible to this API user." : `no ${resource} record exists at this id (a miss is the data, not an error condition)`,
16951
+ note: isDeletedAuditRead(surface) ? "No audit log entry at this ID was visible to this API user." : resource === "knowledge_base_articles" ? "No published article at this ID was visible to this API user." : `no ${resource} record exists at this id (a miss is the data, not an error condition)`,
16630
16952
  authority: `${resource}.query`,
16631
16953
  remedy: `query the ${resource} collection (a bounded queryBounded walk) or verify the id from the authority surface \u2014 do not retry the same get`
16632
16954
  };
@@ -17191,11 +17513,14 @@ var HttpClient = class {
17191
17513
  }
17192
17514
  let parsed;
17193
17515
  try {
17194
- parsed = decodeResponseJson(text, s.auditTarget);
17516
+ parsed = decodeResponseJson(text, s.auditTarget, s.knowledgeBaseTarget);
17195
17517
  } catch {
17196
17518
  return this.handleNonJson2xx(s, res, status, text);
17197
17519
  }
17198
17520
  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);
17523
+ }
17199
17524
  return {
17200
17525
  done: true,
17201
17526
  value: opts.skipResponseRedaction ? parsed : redactResponseBody(parsed, { redactPersonalData: this.redactPersonalData }),
@@ -17399,8 +17724,15 @@ var HttpClient = class {
17399
17724
  const queryRoute = /\/query(?:\/|$)/i.test(route);
17400
17725
  const getQuery = method === "GET" && queryRoute && requestUrl.search !== "";
17401
17726
  if (getQuery) assertGetQueryUrlLength(url);
17402
- const bodyText = opts.body !== void 0 ? JSON.stringify(opts.body) : void 0;
17403
- if (queryRoute) assertQueryFilters(opts, requestUrl, auditTarget === "query" || auditTarget === "query/count", bodyText);
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);
17730
+ if (queryRoute) {
17731
+ 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;
17734
+ assertQueryFilters(opts, requestUrl, bodyText, exactIdLabel);
17735
+ }
17404
17736
  opts = { ...opts, path };
17405
17737
  if (bodyText !== void 0) headers["Content-Type"] = "application/json";
17406
17738
  const correlationId = newCorrelationId();
@@ -17414,6 +17746,7 @@ var HttpClient = class {
17414
17746
  getQuery,
17415
17747
  method,
17416
17748
  auditTarget,
17749
+ knowledgeBaseTarget,
17417
17750
  url,
17418
17751
  headers,
17419
17752
  bodyText,
@@ -17506,26 +17839,26 @@ function isMaintenancePage(status, contentType, text) {
17506
17839
  return true;
17507
17840
  }
17508
17841
  }
17509
- function assertQueryFilters(opts, url, auditIds, bodyText) {
17842
+ function assertQueryFilters(opts, url, bodyText, exactIdLabel) {
17510
17843
  const operation = opts.operation ?? opts.path.split("?", 1)[0];
17511
17844
  const validate7 = (value) => {
17512
17845
  if (value === null || typeof value !== "object") return;
17513
17846
  for (const [key, filter] of Object.entries(value)) {
17514
- if (key.toLowerCase() === "filter") assertQueryFilterForWire(filter, operation, auditIds);
17847
+ if (key.toLowerCase() === "filter") assertQueryFilterForWire(filter, operation, exactIdLabel);
17515
17848
  }
17516
17849
  };
17517
- const parse = (json) => auditIds ? JSON.parse(
17850
+ const parse = (json) => exactIdLabel !== void 0 ? JSON.parse(
17518
17851
  json,
17519
17852
  (_key, value, context) => typeof value === "number" && context?.source !== void 0 && !isAuditDecimalId(context.source) ? null : value
17520
17853
  ) : JSON.parse(json);
17521
- validate7(auditIds && bodyText !== void 0 ? parse(bodyText) : opts.body);
17854
+ validate7(exactIdLabel !== void 0 && bodyText !== void 0 ? parse(bodyText) : opts.body);
17522
17855
  for (const [key, search] of url.searchParams) {
17523
17856
  if (key.toLowerCase() !== "search") continue;
17524
17857
  let parsed;
17525
17858
  try {
17526
17859
  parsed = parse(search);
17527
17860
  } catch {
17528
- if (auditIds) throw new AutotaskConfigError("Expected a JSON search object for the audit query.", { operation });
17861
+ if (exactIdLabel !== void 0) throw new AutotaskConfigError(`Expected a JSON search object for the ${exactIdLabel} query.`, { operation });
17529
17862
  continue;
17530
17863
  }
17531
17864
  validate7(parsed);
@@ -17994,13 +18327,13 @@ async function runBounded(fn, items, opts) {
17994
18327
  const results = new Array(items.length);
17995
18328
  let next = 0;
17996
18329
  let failure;
17997
- const fail2 = (error, index) => {
18330
+ const fail3 = (error, index) => {
17998
18331
  if (failure === void 0 || opts.orderedErrors === true && index < failure.index) failure = { error, index };
17999
18332
  };
18000
18333
  const worker = async () => {
18001
18334
  while (failure === void 0 && next < items.length) {
18002
18335
  if (signal?.aborted) {
18003
- fail2(signal.reason, -1);
18336
+ fail3(signal.reason, -1);
18004
18337
  return;
18005
18338
  }
18006
18339
  const i = next++;
@@ -18010,7 +18343,7 @@ async function runBounded(fn, items, opts) {
18010
18343
  results[i] = settle ? { status: "fulfilled", value } : value;
18011
18344
  } catch (error) {
18012
18345
  if (settle) results[i] = { status: "rejected", reason: error };
18013
- else fail2(error, i);
18346
+ else fail3(error, i);
18014
18347
  }
18015
18348
  }
18016
18349
  };
@@ -18066,7 +18399,7 @@ async function capabilitySets() {
18066
18399
  const fieldOps = /* @__PURE__ */ new Map();
18067
18400
  const udfCapable = /* @__PURE__ */ new Set();
18068
18401
  const resources = /* @__PURE__ */ new Set();
18069
- for (const rec of await chunkJCKYM7FD_cjs.loadCapabilityRecords()) {
18402
+ for (const rec of await chunkYVNGUGG6_cjs.loadCapabilityRecords()) {
18070
18403
  if (rec.resource === "operations") continue;
18071
18404
  resources.add(rec.resource);
18072
18405
  if (rec.operation === "getFieldInfo") fieldOps.set(rec.resource, rec);
@@ -18077,7 +18410,7 @@ async function capabilitySets() {
18077
18410
  var derivedIndexPromise = null;
18078
18411
  function derivedIndexLoad() {
18079
18412
  if (derivedIndexPromise === null) {
18080
- derivedIndexPromise = chunkJCKYM7FD_cjs.loadCapabilityRecords().then((records) => {
18413
+ derivedIndexPromise = chunkYVNGUGG6_cjs.loadCapabilityRecords().then((records) => {
18081
18414
  const index = /* @__PURE__ */ new Map();
18082
18415
  for (const rec of records) {
18083
18416
  const declared = rec.metadata?.derivedFields;
@@ -18535,6 +18868,13 @@ function mergePartialBody(current, data) {
18535
18868
  }
18536
18869
  return merged;
18537
18870
  }
18871
+ function snapshotMutationOptions(options) {
18872
+ const { dryRun, lastModifiedDate, maxRetries, raw, verifyPersisted } = options ?? {};
18873
+ if (dryRun !== void 0 && typeof dryRun !== "boolean") {
18874
+ throw new AutotaskConfigError("dryRun must be a boolean");
18875
+ }
18876
+ return { dryRun, lastModifiedDate, maxRetries, raw, verifyPersisted };
18877
+ }
18538
18878
  function normalizeUdfInput(value) {
18539
18879
  if (Array.isArray(value)) {
18540
18880
  return value.map((entry) => {
@@ -18715,37 +19055,241 @@ async function expandResourceNames(client, ids2, opts = {}) {
18715
19055
  return { results, resolved, blind, failed };
18716
19056
  }
18717
19057
 
18718
- // src/operations/lineOfBusinessChain.ts
18719
- function vendorId(value) {
18720
- if (typeof value === "number") return Number.isSafeInteger(value) && value >= 1 ? value : void 0;
18721
- if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
18722
- const n = Number(value.trim());
18723
- return Number.isSafeInteger(n) && n >= 1 ? n : void 0;
18724
- }
18725
- return void 0;
19058
+ // src/resources/special/_shared/numbers.ts
19059
+ function num(v) {
19060
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
18726
19061
  }
18727
- async function resolveLineOfBusinessChain(http, associationId, options) {
18728
- const operation = options.operation ?? "compositeNames";
18729
- const degrade = options.onError === "degrade";
18730
- const get = (path) => {
18731
- const res = http.request({ method: "GET", path, operation }).then((body) => {
18732
- const b = body;
18733
- if (b === null || !("item" in b) || b.item === null || b.item === void 0) return null;
18734
- return b.item;
18735
- });
18736
- if (!degrade) {
18737
- return res.catch((e) => {
18738
- if (e instanceof NotFoundError) return null;
18739
- throw e;
19062
+
19063
+ // src/resources/special/_shared/finance.ts
19064
+ function budgetExceededError(operation, message, details, suggestedAction) {
19065
+ return new AutotaskError(message, { code: "BUDGET_EXCEEDED", category: "policy", operation, details, suggestedAction });
19066
+ }
19067
+ function makeCallBudget(budget, onExceed) {
19068
+ let spent = 0;
19069
+ return {
19070
+ spend() {
19071
+ if (spent >= budget) throw onExceed(spent);
19072
+ spent += 1;
19073
+ },
19074
+ spent: () => spent
19075
+ };
19076
+ }
19077
+ function countingHttp(raw, spend) {
19078
+ const http = Object.create(raw);
19079
+ http.request = (o) => {
19080
+ spend();
19081
+ return raw.request(o);
19082
+ };
19083
+ return http;
19084
+ }
19085
+ function idChunks(ids2, size) {
19086
+ const out = [];
19087
+ for (let i = 0; i < ids2.length; i += size) out.push(ids2.slice(i, i + size));
19088
+ return out;
19089
+ }
19090
+ async function fetchIdChunks(http, entityPath, ids2, fields, operation, opts) {
19091
+ const chunkSize = opts?.chunkSize ?? 250;
19092
+ const out = /* @__PURE__ */ new Map();
19093
+ for (const chunk of idChunks(ids2, chunkSize)) {
19094
+ opts?.budgetSpend?.();
19095
+ const chunkKeys = new Set(chunk.map((id) => String(id)));
19096
+ try {
19097
+ const req = buildQueryRequest(http.baseUrl, entityPath, {
19098
+ filter: [{ field: "id", op: "in", value: chunk }],
19099
+ maxRecords: opts?.maxRecords ?? chunkSize,
19100
+ includeFields: fields
18740
19101
  });
19102
+ const res = await http.request({ ...req, operation });
19103
+ const { items: rows } = unwrapItems(res, operation);
19104
+ for (const row of rows) {
19105
+ const k = String(row["id"]);
19106
+ if (!chunkKeys.has(k)) continue;
19107
+ out.set(k, row);
19108
+ }
19109
+ } catch (err) {
19110
+ if (opts?.onChunkFault?.(chunk, err) !== true) throw err;
18741
19111
  }
18742
- return res.catch((e) => {
18743
- if (e instanceof NotFoundError || isAutotaskError(e) && e.code !== "ABORTED") return null;
18744
- throw e;
18745
- });
18746
- };
18747
- let remaining = options.budget;
18748
- if (remaining < 1) {
19112
+ }
19113
+ return out;
19114
+ }
19115
+ function internalAmount(row, internalKey, localKey) {
19116
+ const v = row[internalKey];
19117
+ return typeof v === "number" && Number.isFinite(v) ? v : num(row[localKey]);
19118
+ }
19119
+ function toCents(v) {
19120
+ return Math.round(num(v) * 100);
19121
+ }
19122
+ async function readPicklists(http, entityPath, operation) {
19123
+ const res = await http.request({ method: "GET", path: `${entityPath}/entityInformation/fields`, operation });
19124
+ const body = typeof res === "object" && res !== null ? res : {};
19125
+ const fields = Array.isArray(body["fields"]) ? body["fields"] : [];
19126
+ const out = /* @__PURE__ */ new Map();
19127
+ for (const f of fields) {
19128
+ if (f["isPickList"] !== true || typeof f["name"] !== "string" || !Array.isArray(f["picklistValues"])) continue;
19129
+ const values = /* @__PURE__ */ new Map();
19130
+ for (const p of f["picklistValues"]) {
19131
+ const id = typeof p["value"] === "string" ? Number.parseInt(p["value"], 10) : Number.NaN;
19132
+ if (Number.isFinite(id)) values.set(id, String(p["label"] ?? ""));
19133
+ }
19134
+ out.set(f["name"], values);
19135
+ }
19136
+ return out;
19137
+ }
19138
+ function resolveSelector(operation, name, sel, values) {
19139
+ const out = /* @__PURE__ */ new Map();
19140
+ const misses = [];
19141
+ for (const s of sel) {
19142
+ const hits = typeof s === "number" ? values.has(s) ? [s] : [] : [...values].filter(([, l]) => l.trim().toLowerCase() === s.trim().toLowerCase()).map(([id]) => id);
19143
+ if (hits.length === 0) misses.push(JSON.stringify(s));
19144
+ for (const h of hits) out.set(h, values.get(h));
19145
+ }
19146
+ if (misses.length > 0) throw selectorUnmatched(operation, name, `${misses.join(", ")} matched no live value`, values);
19147
+ return out;
19148
+ }
19149
+ function selectorUnmatched(operation, name, what, values) {
19150
+ const live = [...values].map(([id, l]) => `${id} ${l}`).join("; ") || "(the picklist serves no values)";
19151
+ return new AutotaskConfigError(`${shortName(operation)}: ${name}: ${what}. Live values (id label): ${live}`, {
19152
+ operation,
19153
+ suggestedAction: `Pass ${name} as ids or exact labels from the live list.`
19154
+ });
19155
+ }
19156
+ var TENANT_HOURLY_LIMIT = 1e4;
19157
+ function tenantHourlyShare(calls) {
19158
+ return `${(calls / TENANT_HOURLY_LIMIT * 100).toFixed(2)}% of ${TENANT_HOURLY_LIMIT.toLocaleString("en-US")}/h`;
19159
+ }
19160
+ var isPosInt = (v) => Number.isSafeInteger(v) && v > 0;
19161
+ function checkIdList(name, v, max, problems, opts) {
19162
+ const ok = opts?.allowZero ? (x) => x === 0 || isPosInt(x) : isPosInt;
19163
+ if (!Array.isArray(v) || v.length === 0 || v.length > max || !v.every(ok)) {
19164
+ problems.push(`${name} must be a non-empty array of at most ${max} ${opts?.allowZero ? "non-negative" : "positive"} integer ids`);
19165
+ return void 0;
19166
+ }
19167
+ return [...new Set(v)].sort((a, b) => a - b);
19168
+ }
19169
+ function checkSelector(name, v, problems) {
19170
+ if (v === void 0) return void 0;
19171
+ if (!Array.isArray(v) || v.length === 0 || !v.every((x) => isPosInt(x) || typeof x === "string" && x.trim() !== "")) {
19172
+ problems.push(`${name} must be a non-empty array of picklist ids or labels`);
19173
+ return void 0;
19174
+ }
19175
+ return v;
19176
+ }
19177
+ function checkInt(name, v, def, max, problems) {
19178
+ if (v === void 0) return def;
19179
+ if (!Number.isInteger(v) || v < 1 || v > max) {
19180
+ problems.push(`${name} must be an integer 1..${max} (got ${String(v)})`);
19181
+ return def;
19182
+ }
19183
+ return v;
19184
+ }
19185
+ async function collectRows(res, filter, includeFields, page) {
19186
+ const out = [];
19187
+ for await (const r of res.query({ filter, includeFields, maxRecords: page, names: false })) out.push(r);
19188
+ return out;
19189
+ }
19190
+ function blindCountError(operation, subject, suggestedAction) {
19191
+ return new AutotaskError(`${shortName(operation)}: a gate count came back blind (unknown, not zero); ${subject} cannot be sized`, {
19192
+ code: "INVALID_RESPONSE",
19193
+ category: "server",
19194
+ operation,
19195
+ details: { reason: "blind_count" },
19196
+ suggestedAction
19197
+ });
19198
+ }
19199
+ function countMismatchError(operation, what, streamed, counted, rows) {
19200
+ const rowNote = rows !== void 0 && rows !== streamed ? ` (${rows} rows)` : "";
19201
+ 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`, {
19202
+ code: "INVALID_RESPONSE",
19203
+ category: "server",
19204
+ operation,
19205
+ details: { reason: "count_mismatch", stream: what, streamed, counted },
19206
+ suggestedAction: "Retry the call."
19207
+ });
19208
+ }
19209
+ function compareIds(a, b) {
19210
+ for (let i = 0; i < a.length; i++) {
19211
+ const x = a[i] ?? null;
19212
+ const y = b[i] ?? null;
19213
+ if (x === y) continue;
19214
+ if (x === null) return -1;
19215
+ if (y === null) return 1;
19216
+ if (typeof x === "number" && typeof y === "number") return x - y;
19217
+ return String(x) < String(y) ? -1 : 1;
19218
+ }
19219
+ return 0;
19220
+ }
19221
+ var sortedRecord = (m) => Object.fromEntries([...m].sort((a, b) => a[0] - b[0]).map(([id, l]) => [String(id), l]));
19222
+ var shortName = (operation) => operation.split(".").pop() ?? operation;
19223
+
19224
+ // src/operations/nameBatch.ts
19225
+ var NAME_BATCH_CHUNK_SIZE = 250;
19226
+ function nameEntryKey(path) {
19227
+ return path + "\0name";
19228
+ }
19229
+ function nameEntrySnapshot(cache, path) {
19230
+ const value = cache?.get(nameEntryKey(path));
19231
+ if (value === void 0 || value === null || typeof value !== "object") return void 0;
19232
+ return () => value;
19233
+ }
19234
+ async function batchNameReads(http, entityPath, ids2, fields, operation) {
19235
+ const cache = http.readCache;
19236
+ const epoch = cache?.epoch ?? 0;
19237
+ const out = /* @__PURE__ */ new Map();
19238
+ const rows = await fetchIdChunks(http, entityPath, ids2, fields, operation, {
19239
+ chunkSize: NAME_BATCH_CHUNK_SIZE,
19240
+ maxRecords: NAME_BATCH_CHUNK_SIZE,
19241
+ onChunkFault: (chunk, err) => {
19242
+ if (!isAutotaskError(err) || err.code === "ABORTED") return false;
19243
+ const error = err.httpStatus !== void 0 ? { code: err.code, message: err.message, httpStatus: err.httpStatus } : { code: err.code, message: err.message };
19244
+ for (const id of chunk) out.set(String(id), { kind: "error", error });
19245
+ return true;
19246
+ }
19247
+ });
19248
+ for (const id of ids2) {
19249
+ const k = String(id);
19250
+ if (out.has(k)) continue;
19251
+ const record = rows.get(k);
19252
+ if (record === void 0) {
19253
+ out.set(k, { kind: "unreadable" });
19254
+ continue;
19255
+ }
19256
+ cache?.set(nameEntryKey(`${entityPath}/${k}`), record, epoch);
19257
+ out.set(k, { kind: "record", record });
19258
+ }
19259
+ return out;
19260
+ }
19261
+
19262
+ // src/operations/lineOfBusinessChain.ts
19263
+ function vendorId(value) {
19264
+ if (typeof value === "number") return Number.isSafeInteger(value) && value >= 1 ? value : void 0;
19265
+ if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
19266
+ const n = Number(value.trim());
19267
+ return Number.isSafeInteger(n) && n >= 1 ? n : void 0;
19268
+ }
19269
+ return void 0;
19270
+ }
19271
+ async function resolveLineOfBusinessChain(http, associationId, options) {
19272
+ const operation = options.operation ?? "compositeNames";
19273
+ const degrade = options.onError === "degrade";
19274
+ const get = (path) => {
19275
+ const res = http.request({ method: "GET", path, operation }).then((body) => {
19276
+ const b = body;
19277
+ if (b === null || !("item" in b) || b.item === null || b.item === void 0) return null;
19278
+ return b.item;
19279
+ });
19280
+ if (!degrade) {
19281
+ return res.catch((e) => {
19282
+ if (e instanceof NotFoundError) return null;
19283
+ throw e;
19284
+ });
19285
+ }
19286
+ return res.catch((e) => {
19287
+ if (e instanceof NotFoundError || isAutotaskError(e) && e.code !== "ABORTED") return null;
19288
+ throw e;
19289
+ });
19290
+ };
19291
+ let remaining = options.budget;
19292
+ if (remaining < 1) {
18749
19293
  return {
18750
19294
  lineOfBusiness: { association: null, organizationalLevel2: null, organizationalLevel1: null, markers: { association: "capped", organizationalLevel2: "capped", organizationalLevel1: "capped" } },
18751
19295
  used: 0,
@@ -18795,7 +19339,7 @@ async function resolveLineOfBusinessChain(http, associationId, options) {
18795
19339
 
18796
19340
  // src/operations/compositeNames.ts
18797
19341
  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.)";
18798
- var DEFAULT_MAX_NAME_READS = 20;
19342
+ var DEFAULT_MAX_NAME_READS = 50;
18799
19343
  var TICKET_LABEL_FIELDS = ["status", "priority", "ticketType", "issueType", "subIssueType", "source", "queueID"];
18800
19344
  function isVendorId(value) {
18801
19345
  if (typeof value === "number") return Number.isSafeInteger(value) && value >= 0;
@@ -18888,6 +19432,15 @@ var FK_NAME_FIELD = {
18888
19432
  product: "name",
18889
19433
  configurationItemCategory: "name"
18890
19434
  };
19435
+ var FK_BATCH_FIELDS = {
19436
+ role: ["name"],
19437
+ billingCode: ["name"],
19438
+ contract: ["contractName"],
19439
+ company: ["companyName"],
19440
+ ticket: ["ticketNumber", "title"],
19441
+ product: ["name"],
19442
+ configurationItemCategory: ["name"]
19443
+ };
18891
19444
  function fkName(record, table) {
18892
19445
  if (table === "ticket") {
18893
19446
  const parts = [record["ticketNumber"], record["title"]].filter((v) => typeof v === "string" && v.trim() !== "").map((v) => v.trim());
@@ -18912,6 +19465,8 @@ async function resolveCompositeNames(http, plan, opts = {}) {
18912
19465
  const readCache = http.readCache;
18913
19466
  const section = { truncated: false, rows: {}, reasons: {} };
18914
19467
  let remaining = budget;
19468
+ let overBudget = 0;
19469
+ let unreadable = 0;
18915
19470
  const tasks = [];
18916
19471
  let contractLobPointer;
18917
19472
  let contractLobUnread;
@@ -18928,6 +19483,7 @@ async function resolveCompositeNames(http, plan, opts = {}) {
18928
19483
  for (const id of overBudgetResource) {
18929
19484
  section.rows[`resource:${id}`] = { name: null, blind: false };
18930
19485
  section.truncated = true;
19486
+ overBudget += 1;
18931
19487
  }
18932
19488
  const overSet = new Set(overBudgetResource.map((id) => String(id)));
18933
19489
  const opIds = plan.resourceIds.filter((id) => !overSet.has(String(id)));
@@ -18937,6 +19493,7 @@ async function resolveCompositeNames(http, plan, opts = {}) {
18937
19493
  for (const id of pass.slice(500)) {
18938
19494
  section.rows[`resource:${id}`] = { name: null, blind: false };
18939
19495
  section.truncated = true;
19496
+ overBudget += 1;
18940
19497
  }
18941
19498
  pass = pass.slice(0, 500);
18942
19499
  }
@@ -18965,48 +19522,89 @@ async function resolveCompositeNames(http, plan, opts = {}) {
18965
19522
  product: client.products,
18966
19523
  configurationItemCategory: client.configurationItemCategories
18967
19524
  };
19525
+ const isLobContract = (fk2) => fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId);
19526
+ const fkRows = /* @__PURE__ */ new Map();
19527
+ const takeLobPointer = (fk2, record) => {
19528
+ if (plan.lineOfBusinessId === void 0 && isLobContract(fk2)) contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
19529
+ };
19530
+ const steps = [];
19531
+ const coldByTable = /* @__PURE__ */ new Map();
18968
19532
  for (const fk2 of plan.recordFks) {
18969
19533
  const key = `${fk2.table}:${fk2.id}`;
18970
- const snapshot = nameRecordSnapshot(readCache, `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`, fk2.id, FK_GET_OPERATION[fk2.table]);
18971
- const cold = snapshot === void 0;
18972
- if (cold) {
18973
- if (remaining < 1) {
18974
- tasks.push(async () => () => {
18975
- section.rows[key] = { name: null, blind: false };
18976
- });
18977
- section.truncated = true;
18978
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
18979
- contractLobUnread = "capped";
18980
- }
18981
- continue;
18982
- }
18983
- remaining -= 1;
19534
+ const path = `${FK_TABLE_PATH[fk2.table]}/${fk2.id}`;
19535
+ const snapshot = nameRecordSnapshot(readCache, path, fk2.id, FK_GET_OPERATION[fk2.table]) ?? (isLobContract(fk2) ? void 0 : nameEntrySnapshot(readCache, path));
19536
+ if (snapshot !== void 0) {
19537
+ steps.push({ fk: fk2, snapshot });
19538
+ continue;
19539
+ }
19540
+ if (remaining < 1) {
19541
+ fkRows.set(key, { name: null, blind: false });
19542
+ overBudget += 1;
19543
+ section.truncated = true;
19544
+ if (isLobContract(fk2)) contractLobUnread = "capped";
19545
+ continue;
19546
+ }
19547
+ remaining -= 1;
19548
+ steps.push({ fk: fk2 });
19549
+ if (!isLobContract(fk2)) coldByTable.set(fk2.table, [...coldByTable.get(fk2.table) ?? [], fk2]);
19550
+ }
19551
+ const batched = /* @__PURE__ */ new Set();
19552
+ for (const { fk: fk2, snapshot } of steps) {
19553
+ const key = `${fk2.table}:${fk2.id}`;
19554
+ if (snapshot !== void 0) {
19555
+ tasks.push(async () => {
19556
+ const row = await fkRow(fk2, async () => snapshot());
19557
+ return () => {
19558
+ fkRows.set(key, row);
19559
+ };
19560
+ });
19561
+ continue;
18984
19562
  }
19563
+ const group = isLobContract(fk2) ? void 0 : coldByTable.get(fk2.table);
19564
+ if (group === void 0 || group.length === 1) {
19565
+ tasks.push(async () => {
19566
+ const row = await fkRow(fk2, async () => await holders[fk2.table].get(fk2.id));
19567
+ return () => {
19568
+ fkRows.set(key, row);
19569
+ };
19570
+ });
19571
+ continue;
19572
+ }
19573
+ if (batched.has(fk2.table)) continue;
19574
+ batched.add(fk2.table);
19575
+ const table = fk2.table;
18985
19576
  tasks.push(async () => {
18986
- let row;
18987
- try {
18988
- const record = snapshot !== void 0 ? snapshot() : await holders[fk2.table].get(fk2.id);
18989
- if (fk2.table === "contract" && plan.lineOfBusinessId === void 0 && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
18990
- contractLobPointer = vendorId(record["organizationalLevelAssociationID"]);
18991
- }
18992
- row = { name: fkName(record, fk2.table), blind: false };
18993
- } catch (err) {
18994
- if (err instanceof NotFoundError) {
18995
- row = { name: null, blind: true };
18996
- } else if (isAutotaskError(err) && err.code !== "ABORTED") {
18997
- row = { name: null, blind: false, error: faultRow(err) };
18998
- if (fk2.table === "contract" && plan.lineOfBusinessContractId !== void 0 && String(fk2.id) === String(plan.lineOfBusinessContractId)) {
18999
- contractLobUnread = "unresolved";
19577
+ 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"));
19578
+ return () => {
19579
+ for (const g of group) {
19580
+ const out = outcomes.get(String(g.id));
19581
+ const gKey = `${table}:${g.id}`;
19582
+ if (out.kind === "record") fkRows.set(gKey, { name: fkName(out.record, table), blind: false });
19583
+ else if (out.kind === "error") fkRows.set(gKey, { name: null, blind: false, error: out.error });
19584
+ else {
19585
+ fkRows.set(gKey, { name: null, blind: true, unreadable: true });
19586
+ unreadable += 1;
19000
19587
  }
19001
- } else {
19002
- throw err;
19003
19588
  }
19004
- }
19005
- return () => {
19006
- section.rows[key] = row;
19007
19589
  };
19008
19590
  });
19009
19591
  }
19592
+ async function fkRow(fk2, read) {
19593
+ try {
19594
+ const record = await read();
19595
+ takeLobPointer(fk2, record);
19596
+ return { name: fkName(record, fk2.table), blind: false };
19597
+ } catch (err) {
19598
+ if (err instanceof NotFoundError) {
19599
+ return { name: null, blind: true };
19600
+ }
19601
+ if (isAutotaskError(err) && err.code !== "ABORTED") {
19602
+ if (isLobContract(fk2)) contractLobUnread = "unresolved";
19603
+ return { name: null, blind: false, error: faultRow(err) };
19604
+ }
19605
+ throw err;
19606
+ }
19607
+ }
19010
19608
  let picklists = null;
19011
19609
  if (plan.labelFields.length > 0) {
19012
19610
  tasks.push(async () => {
@@ -19020,6 +19618,10 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19020
19618
  });
19021
19619
  }
19022
19620
  for (const merge of await readTasks(http, tasks)) merge();
19621
+ for (const fk2 of plan.recordFks) {
19622
+ const key = `${fk2.table}:${fk2.id}`;
19623
+ section.rows[key] = fkRows.get(key);
19624
+ }
19023
19625
  let lineOfBusiness2 = null;
19024
19626
  const lobId = plan.lineOfBusinessId ?? contractLobPointer;
19025
19627
  if (lobId !== void 0) {
@@ -19044,6 +19646,8 @@ async function resolveCompositeNames(http, plan, opts = {}) {
19044
19646
  return {
19045
19647
  section,
19046
19648
  lineOfBusiness: lineOfBusiness2,
19649
+ overBudget,
19650
+ unreadable,
19047
19651
  resourceName: (id) => section.rows[`resource:${id}`]?.name ?? null,
19048
19652
  recordName: (table, id) => section.rows[`${table}:${id}`]?.name ?? null,
19049
19653
  labelFor: (field, value) => {
@@ -19157,14 +19761,14 @@ function cachedRead(http, cache, key, path, operation, request, fresh, shouldSto
19157
19761
  throw failure;
19158
19762
  });
19159
19763
  }
19160
- function cachedRecordGet(http, path, operation, fresh = false) {
19764
+ function cachedRecordGet(http, path, operation, fresh = false, maxRetries) {
19161
19765
  return cachedRead(
19162
19766
  http,
19163
19767
  http.readCache,
19164
19768
  path,
19165
19769
  path,
19166
19770
  operation,
19167
- (signal) => http.request({ method: "GET", path, operation, signal }),
19771
+ (signal) => http.request({ method: "GET", path, operation, signal, maxRetries }),
19168
19772
  fresh
19169
19773
  );
19170
19774
  }
@@ -19257,6 +19861,8 @@ var MODEL_FIELD_SETS = {
19257
19861
  "inventory_products": ["id", "availableUnits", "backOrderQuantity", "bin", "createDateTime", "createdByResourceID", "inventoryLocationID", "onHandUnits", "pickedUnits", "productID", "quantityMaximum", "quantityMinimum", "referenceNumber", "reservedUnits", "unitsOnOrder"],
19258
19862
  "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"],
19259
19863
  "invoices": ["id", "batchID", "comments", "companyID", "createDateTime", "creatorResourceID", "dueDate", "fromDate", "invoiceDateTime", "invoiceEditorTemplateID", "invoiceNumber", "invoiceTotal", "isVoided", "orderNumber", "paidDate", "paymentTerm", "taxGroup", "taxRegionName", "toDate", "totalTaxValue", "voidedByResourceID", "voidedDate", "webServiceDate"],
19864
+ "knowledge_base_articles": ["id", "createdByResourceID", "createdDateTime", "articleCategoryID", "errorCodes", "isActive", "keywords", "lastModifiedByResourceID", "lastModifiedDateTime", "publish", "referenceLink", "title", "soapParentPropertyId"],
19865
+ "knowledge_base_categories": ["id", "description", "name", "parentCategoryID"],
19260
19866
  "notification_history": ["id", "companyID", "entityNumber", "entityTitle", "initiatingContactID", "initiatingResourceID", "isActive", "isDeleted", "isTemplateJob", "notificationHistoryTypeID", "notificationSentTime", "opportunityID", "projectID", "quoteID", "recipientDisplayName", "recipientEmailAddress", "taskID", "templateName", "ticketID", "timeEntryID"],
19261
19867
  "opportunities": ["id", "advancedField1", "advancedField2", "advancedField3", "advancedField4", "advancedField5", "amount", "assessmentScore", "barriers", "closedDate", "companyID", "contactID", "cost", "createDate", "creatorResourceID", "description", "helpNeeded", "impersonatorCreatorResourceID", "lastActivity", "leadSource", "lossReason", "lossReasonDetail", "lostDate", "market", "monthlyCost", "monthlyRevenue", "nextStep", "onetimeCost", "onetimeRevenue", "opportunityCategoryID", "organizationalLevelAssociationID", "ownerResourceID", "primaryCompetitor", "probability", "productID", "projectedCloseDate", "promisedFulfillmentDate", "promotionName", "quarterlyCost", "quarterlyRevenue", "rating", "relationshipAssessmentScore", "revenueSpread", "revenueSpreadUnit", "salesOrderID", "salesProcessPercentComplete", "semiannualCost", "semiannualRevenue", "stage", "startDate", "status", "technicalAssessmentScore", "throughDate", "title", "totalAmountMonths", "useQuoteTotals", "winReason", "winReasonDetail", "yearlyCost", "yearlyRevenue", "userDefinedFields"],
19262
19868
  "opportunity_attachments": ["id", "attachDate", "attachedByContactID", "attachedByResourceID", "attachmentType", "contentType", "creatorType", "fileSize", "fullPath", "impersonatorCreatorResourceID", "opportunityID", "parentAttachmentID", "parentID", "publish", "title", "data", "parentType", "soapParentPropertyId", "isTaskAttachment"],
@@ -19371,6 +19977,7 @@ var MODEL_DATE_FIELDS = {
19371
19977
  "holidays": ["holidayDate"],
19372
19978
  "inventory_products": ["createDateTime"],
19373
19979
  "invoices": ["createDateTime", "dueDate", "fromDate", "invoiceDateTime", "paidDate", "toDate", "voidedDate", "webServiceDate"],
19980
+ "knowledge_base_articles": ["createdDateTime", "lastModifiedDateTime"],
19374
19981
  "notification_history": ["notificationSentTime"],
19375
19982
  "opportunities": ["closedDate", "createDate", "lastActivity", "lostDate", "projectedCloseDate", "promisedFulfillmentDate", "startDate", "throughDate"],
19376
19983
  "opportunity_attachments": ["attachDate"],
@@ -19490,21 +20097,21 @@ function validateRelationLeaves(resourceKey, conditions, op) {
19490
20097
  assertUndottedUdfField(c, op);
19491
20098
  const field = c.field;
19492
20099
  const [rel, sub, ...rest] = field.split(".");
19493
- const fail2 = (why) => {
20100
+ const fail3 = (why) => {
19494
20101
  throw new AutotaskConfigError(`${op}: relation filter "${field}" ${why} \u2014 the request was not issued`, {
19495
20102
  operation: op,
19496
20103
  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.`
19497
20104
  });
19498
20105
  };
19499
20106
  if (selfPrefixes(resourceKey).includes(rel)) {
19500
- if (rest.length > 0 || !sub) fail2("is not <resource>.<field> (multi-hop relations are not supported)");
20107
+ if (rest.length > 0 || !sub) fail3("is not <resource>.<field> (multi-hop relations are not supported)");
19501
20108
  continue;
19502
20109
  }
19503
- if (rest.length > 0 || !sub) fail2("is not <relation>.<field> (multi-hop relations are not supported)");
19504
- if (!valid.includes(rel)) fail2(`names an unknown relation for ${resourceKey} (valid: ${valid.join(", ") || "none"})`);
20110
+ if (rest.length > 0 || !sub) fail3("is not <relation>.<field> (multi-hop relations are not supported)");
20111
+ if (!valid.includes(rel)) fail3(`names an unknown relation for ${resourceKey} (valid: ${valid.join(", ") || "none"})`);
19505
20112
  const parentFields = MODEL_FIELD_SETS[RELATION_TARGETS[rel].resource];
19506
20113
  if (parentFields !== void 0 && modelFieldLookup(RELATION_TARGETS[rel].resource)?.(sub) !== true) {
19507
- fail2(`names a field unknown on ${RELATION_TARGETS[rel].resource}`);
20114
+ fail3(`names a field unknown on ${RELATION_TARGETS[rel].resource}`);
19508
20115
  }
19509
20116
  }
19510
20117
  };
@@ -19657,11 +20264,13 @@ async function labelRows(client, resourceKey, rows) {
19657
20264
  }
19658
20265
  return r;
19659
20266
  });
19660
- const capHit = names?.section.truncated === true;
20267
+ const overBudget = names?.overBudget ?? 0;
20268
+ const unreadable = names?.unreadable ?? 0;
19661
20269
  const unresolved2 = Object.keys(names?.section.reasons ?? {});
19662
- if (capHit === false && unresolved2.length === 0) return { rows: out };
20270
+ if (overBudget === 0 && unreadable === 0 && unresolved2.length === 0) return { rows: out };
19663
20271
  const parts = [];
19664
- 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`);
20272
+ 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`);
20273
+ 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`);
19665
20274
  if (unresolved2.length > 0) parts.push(`picklist label(s) unavailable for ${unresolved2.join(", ")} (see reasons)`);
19666
20275
  return { rows: out, names: { note: parts.join("; "), ...Object.keys(names.section.reasons).length > 0 ? { reasons: names.section.reasons } : {} } };
19667
20276
  }
@@ -19725,6 +20334,18 @@ function assertPageReadActive(operation) {
19725
20334
  }
19726
20335
 
19727
20336
  // src/resources/base/query.ts
20337
+ var QUERY_BAG_KEYS = [
20338
+ "filter",
20339
+ "includeFields",
20340
+ "maxRecords",
20341
+ "maxTotalRecords",
20342
+ "via",
20343
+ "names",
20344
+ "limit",
20345
+ "latest",
20346
+ "noteChars",
20347
+ "walk"
20348
+ ];
19728
20349
  var QueryBase = class {
19729
20350
  httpClient;
19730
20351
  config;
@@ -19775,7 +20396,7 @@ var QueryBase = class {
19775
20396
  if (page === 1) {
19776
20397
  const filter = normalizedConditions(params.filter);
19777
20398
  if (filter !== void 0 && isAuditLogResource(this.config.key)) {
19778
- assertQueryFilterForWire(normalizeInValues(filter), operation, true);
20399
+ assertQueryFilterForWire(normalizeInValues(filter), operation, "audit log");
19779
20400
  }
19780
20401
  const req = buildQueryRequest(this.http.baseUrl, this.resourcePath, { ...params, maxRecords: pageSize });
19781
20402
  if (req.body !== void 0) req.body = JSON.parse(JSON.stringify(req.body));
@@ -19791,7 +20412,7 @@ var QueryBase = class {
19791
20412
  operation
19792
20413
  });
19793
20414
  }
19794
- const cursorResource = isAuditLogResource(this.config.key) ? this.resourcePath : void 0;
20415
+ const cursorResource = this.continueAcrossEmptyPage() ? this.resourcePath : void 0;
19795
20416
  if (state2.initialRequest?.method === "GET") {
19796
20417
  const path = cursorToPath(this.http.baseUrl, cursor, cursorResource);
19797
20418
  const separator = path.indexOf("?");
@@ -19816,6 +20437,10 @@ var QueryBase = class {
19816
20437
  });
19817
20438
  return this.readPage(res, page, pageSize, state2);
19818
20439
  }
20440
+ continueAcrossEmptyPage() {
20441
+ const { key } = this.config;
20442
+ return isAuditLogResource(key) || isKnowledgeBaseRootResource(key);
20443
+ }
19819
20444
  /** @internal */
19820
20445
  readPage(body, page, pageSize, state2) {
19821
20446
  const { items, pageDetails } = unwrapItems(body, `${this.config.key}.query`);
@@ -19842,6 +20467,15 @@ var QueryBase = class {
19842
20467
  walkPageSize(params) {
19843
20468
  return clampPageSize(params?.maxRecords ?? this.defaultPageSize);
19844
20469
  }
20470
+ snapshotKnowledgeBaseQuery(params) {
20471
+ if (isKnowledgeBaseRootResource(this.config.key) && isRecord2(params)) {
20472
+ const captured = snapshotQueryBag(params, QUERY_BAG_KEYS);
20473
+ const conditions = Array.isArray(captured.filter) ? captured.filter : captured.filter?.filter;
20474
+ if (conditions?.length === 0) delete captured.filter;
20475
+ return captured;
20476
+ }
20477
+ return params;
20478
+ }
19845
20479
  /** Issue #281: relation filters (`ticket.<field>` …) resolve before a walk,
19846
20480
  * through the same rewrite as queryBounded / count. `undefined` = no parent
19847
20481
  * matched, so nothing can match (the walk is skipped: zero child wire). */
@@ -19857,7 +20491,7 @@ var QueryBase = class {
19857
20491
  * (as queryBounded). Label siblings are opt-in (issue #287): the per-call
19858
20492
  * `names` key is the explicit override, absent = the client's `labels`
19859
20493
  * option (off by default). When on, labelling runs per page, so the cold
19860
- * name-read cap (20) applies per page; a capped id gets a null `*Name`
20494
+ * name-read cap (DEFAULT_MAX_NAME_READS) applies per page; a capped id gets a null `*Name`
19861
20495
  * (an iterator has no result envelope for the `names` summary). A
19862
20496
  * resource built without a client (bare `HttpClient`) yields raw rows.
19863
20497
  */
@@ -19868,10 +20502,10 @@ var QueryBase = class {
19868
20502
  const walk = await this.relationWalkParams(rest, `${this.config.key}.query`);
19869
20503
  if (walk === void 0) return;
19870
20504
  if (!label || client === void 0) {
19871
- yield* paginateItems(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: isAuditLogResource(this.config.key) });
20505
+ yield* paginateItems(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: this.continueAcrossEmptyPage() });
19872
20506
  return;
19873
20507
  }
19874
- for await (const page of paginate(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: isAuditLogResource(this.config.key) })) {
20508
+ for await (const page of paginate(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: this.continueAcrossEmptyPage() })) {
19875
20509
  const labelled = await labelRows(client, this.config.key, page.items);
19876
20510
  yield* labelled.rows;
19877
20511
  }
@@ -19880,13 +20514,13 @@ var QueryBase = class {
19880
20514
  async *queryPageIter(params) {
19881
20515
  const walk = await this.relationWalkParams(params, `${this.config.key}.query`);
19882
20516
  if (walk === void 0) return;
19883
- yield* paginate(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: isAuditLogResource(this.config.key) });
20517
+ yield* paginate(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: this.continueAcrossEmptyPage() });
19884
20518
  }
19885
20519
  /** Collect every item across all pages (the resource `queryAll` surface; 1000-page guarded; relation filters resolve first, #281). */
19886
20520
  async queryAllItems(params) {
19887
- const walk = await this.relationWalkParams(params, `${this.config.key}.query`);
20521
+ const walk = await this.relationWalkParams(this.snapshotKnowledgeBaseQuery(params), `${this.config.key}.query`);
19888
20522
  if (walk === void 0) return [];
19889
- return collectAll(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: isAuditLogResource(this.config.key), maxRecords: walk.maxTotalRecords });
20523
+ return collectAll(this.pageFetcher(walk), { pageSize: this.walkPageSize(walk), continueOnEmpty: this.continueAcrossEmptyPage(), maxRecords: walk.maxTotalRecords });
19890
20524
  }
19891
20525
  /**
19892
20526
  * `queryBounded` — server-side pagination (the MCP query surface): ONE call
@@ -19938,6 +20572,7 @@ var QueryBase = class {
19938
20572
  "queryBounded: params must be an object { filter?, limit?, latest?, includeFields? } \u2014 a bare conditions array is not accepted (wrap it: { filter: [...] })"
19939
20573
  );
19940
20574
  }
20575
+ params = this.snapshotKnowledgeBaseQuery(params);
19941
20576
  const limit = params?.limit ?? BOUNDED_QUERY_DEFAULT_LIMIT;
19942
20577
  if (!Number.isInteger(limit) || limit < 1 || limit > BOUNDED_QUERY_MAX_LIMIT) {
19943
20578
  throw new AutotaskConfigError(
@@ -19973,6 +20608,9 @@ var QueryBase = class {
19973
20608
  const cap = maxRows ?? limit;
19974
20609
  const labelPages = maxRows !== void 0 && readNamesOpt(this.http.client, params?.names, `${this.config.key}.query`);
19975
20610
  let walkParams = params ?? {};
20611
+ if (latest !== void 0 && !isKnowledgeBaseRootResource(this.config.key)) {
20612
+ walkParams = snapshotQueryBag(walkParams, QUERY_BAG_KEYS);
20613
+ }
19976
20614
  const relation = await rewriteRelationFilters(this.http, this.config.key, normalizedConditions(walkParams.filter), `${this.config.key}.query`);
19977
20615
  if (relation?.never === true) return { items: [], fetched: 0, hasMore: false, pagesWalked: 0, relationNote: relation.note, ...maxRows === void 0 ? {} : { truncated: false } };
19978
20616
  if (relation !== void 0) walkParams = { ...walkParams, filter: relation.conditions };
@@ -20062,7 +20700,7 @@ var QueryBase = class {
20062
20700
  if (consume === void 0) items.push(...take);
20063
20701
  else await consume(take, pages2);
20064
20702
  if (fetched >= limit) break;
20065
- if (!page.hasMore || page.items.length === 0 && !isAuditLogResource(this.config.key)) break;
20703
+ if (!page.hasMore || page.items.length === 0 && !this.continueAcrossEmptyPage()) break;
20066
20704
  }
20067
20705
  const names = nameNotes.size === 0 ? void 0 : {
20068
20706
  note: [...nameNotes].join("; "),
@@ -20198,7 +20836,7 @@ var QueryBase = class {
20198
20836
  }
20199
20837
  if (total <= BOUNDED_QUERY_MAX_LIMIT) {
20200
20838
  const { items: items2, pages: pages3, guard: guard2, sliced: sliced2, cursor: cursor2 } = await this.walkBounded(params, total);
20201
- if (this.walkTruncated(total, { itemsLength: items2.length, guard: guard2, sliced: sliced2, cursor: cursor2 })) {
20839
+ if (this.walkTruncated(total, { itemsLength: items2.length, guard: guard2, sliced: sliced2, cursor: cursor2 }) || !this.hasCompleteKnowledgeBaseWindow(items2, total)) {
20202
20840
  throw this.latestWindowIncompleteError(total);
20203
20841
  }
20204
20842
  return this.finishLatest(items2, latest, pages3);
@@ -20207,9 +20845,11 @@ var QueryBase = class {
20207
20845
  probes += 1;
20208
20846
  if (probes > LATEST_MAX_COUNT_PROBES) throw this.latestThresholdUnresolvedError();
20209
20847
  };
20210
- let lo = 0n;
20848
+ const knowledgeBase = isKnowledgeBaseRootResource(this.config.key);
20849
+ let lo = knowledgeBase ? -1n : 0n;
20211
20850
  let hi;
20212
- if (isAuditLogResource(this.config.key)) {
20851
+ let aboveThreshold = 0;
20852
+ if (isAuditLogResource(this.config.key) || knowledgeBase) {
20213
20853
  hi = BigInt(MAX_AUDIT_ID);
20214
20854
  } else {
20215
20855
  for (let t = 1n; ; t = t << 1n) {
@@ -20224,17 +20864,28 @@ var QueryBase = class {
20224
20864
  while (hi - lo > 1n) {
20225
20865
  const mid = lo + hi >> 1n;
20226
20866
  spend();
20227
- if (await this.countAboveId(baseConds, mid) <= latest) hi = mid;
20228
- else lo = mid;
20867
+ const above = await this.countAboveId(baseConds, mid);
20868
+ if (above <= latest) {
20869
+ hi = mid;
20870
+ aboveThreshold = above;
20871
+ } else lo = mid;
20229
20872
  }
20873
+ if (knowledgeBase && aboveThreshold !== latest) throw this.latestWindowIncompleteError(latest + 1);
20230
20874
  const windowValue = hi <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(hi) : hi.toString();
20231
20875
  const window = [...baseConds, { op: "gte", field: "id", value: windowValue }];
20232
20876
  const { items, pages: pages2, guard, sliced, cursor } = await this.walkBounded({ ...params, filter: window }, latest + 1);
20233
- if (this.walkTruncated(latest + 1, { itemsLength: items.length, guard, sliced, cursor })) {
20877
+ if (this.walkTruncated(latest + 1, { itemsLength: items.length, guard, sliced, cursor }) || !this.hasCompleteKnowledgeBaseWindow(items, latest + 1, hi)) {
20234
20878
  throw this.latestWindowIncompleteError(latest + 1);
20235
20879
  }
20236
20880
  return this.finishLatest(items, latest, pages2);
20237
20881
  }
20882
+ hasCompleteKnowledgeBaseWindow(items, expected, minimum) {
20883
+ if (!isKnowledgeBaseRootResource(this.config.key)) return true;
20884
+ if (items.length !== expected) return false;
20885
+ const ids2 = items.map((item) => String(item.id));
20886
+ if (new Set(ids2).size !== expected) return false;
20887
+ return minimum === void 0 || ids2.includes(String(minimum)) && ids2.every((id) => BigInt(id) >= minimum);
20888
+ }
20238
20889
  /** The shared `latest` completion: the (provably complete or
20239
20890
  * stamp-scoped) set sorted id-descending, top N taken. `hasMore: false`
20240
20891
  * — the result is complete FOR THE REQUEST (the table may hold more
@@ -20303,6 +20954,7 @@ var QueryBase = class {
20303
20954
  * or, on a plan-pinned blind surface, the `{ count: 0, blindSurface }`
20304
20955
  * typed sentinel (S12-C T10; see `BlindCountResult`). */
20305
20956
  async countGlobal(params) {
20957
+ params = this.snapshotKnowledgeBaseQuery(params);
20306
20958
  const relation = await rewriteRelationFilters(this.http, this.config.key, normalizedConditions(params?.filter), `${this.config.key}.count`);
20307
20959
  if (relation?.never === true) return 0;
20308
20960
  const conditions = relation !== void 0 ? relation.conditions : normalizedConditions(params?.filter);
@@ -20348,8 +21000,8 @@ var MetaBase = class _MetaBase extends QueryBase {
20348
21000
  * Equivalent non-fresh misses share one request through the cache loader;
20349
21001
  * the ambient signal belongs to this subscriber, never to the shared wire.
20350
21002
  * @internal */
20351
- async cachedGet(path, operation, fresh = false) {
20352
- return cachedRecordGet(this.http, path, operation, fresh);
21003
+ async cachedGet(path, operation, fresh = false, maxRetries) {
21004
+ return cachedRecordGet(this.http, path, operation, fresh, maxRetries);
20353
21005
  }
20354
21006
  /**
20355
21007
  * Entity-metadata read through the default-on field cache (issue #31;
@@ -20371,13 +21023,13 @@ var MetaBase = class _MetaBase extends QueryBase {
20371
21023
  * skips the lookup: fetch live and refresh the entries.
20372
21024
  * @internal
20373
21025
  */
20374
- async cachedMeta(kind, path, operation, unwrap, fresh = false) {
20375
- return cachedMetadataGet(this.http, this.config.key, kind, path, operation, unwrap, fresh);
21026
+ async cachedMeta(kind, path, operation, unwrap, fresh = false, maxRetries) {
21027
+ return cachedMetadataGet(this.http, this.config.key, kind, path, operation, unwrap, fresh, maxRetries);
20376
21028
  }
20377
21029
  /** `GET /V1.0/<E>/{id}` → `{ item }` unwrapped (`item: null` → NotFoundError). */
20378
- async getGlobal(id, fresh = false) {
21030
+ async getGlobal(id, fresh = false, maxRetries) {
20379
21031
  const numeric2 = parseIdentifier(id, "id");
20380
- const res = await this.cachedGet(`${this.resourcePath}/${numeric2}`, `${this.config.key}.get`, fresh);
21032
+ const res = await this.cachedGet(`${this.resourcePath}/${numeric2}`, `${this.config.key}.get`, fresh, maxRetries);
20381
21033
  return unwrapItem(res, numeric2, `${this.config.key}.get`, this.entityName);
20382
21034
  }
20383
21035
  /**
@@ -20422,9 +21074,9 @@ var MetaBase = class _MetaBase extends QueryBase {
20422
21074
  return unwrapItem(res, numeric2, `${this.config.key}.get`, this.entityName);
20423
21075
  }
20424
21076
  /** Parent-scoped `GET .../{parentId}/<Child>/{id}` → `{ item }` unwrapped. */
20425
- async getScopedRaw(parentId, id, fresh = false) {
21077
+ async getScopedRaw(parentId, id, fresh = false, maxRetries) {
20426
21078
  const numeric2 = parseIdentifier(id, "id");
20427
- const res = await this.cachedGet(this.scopedItemPath(parentId, id), `${this.config.key}.get`, fresh);
21079
+ const res = await this.cachedGet(this.scopedItemPath(parentId, id), `${this.config.key}.get`, fresh, maxRetries);
20428
21080
  return unwrapItem(res, numeric2, `${this.config.key}.get`, this.entityName);
20429
21081
  }
20430
21082
  /**
@@ -20491,6 +21143,9 @@ var MetaBase = class _MetaBase extends QueryBase {
20491
21143
  async getFieldInfo() {
20492
21144
  return await this.metadataRead("fields");
20493
21145
  }
21146
+ async getFreshFieldInfo(maxRetries) {
21147
+ return await this.metadataRead("fields", void 0, true, maxRetries);
21148
+ }
20494
21149
  /** `GET /V1.0/<E>/entityInformation/userDefinedFields` → `{ fields }` unwrapped.
20495
21150
  * Goes through the field cache when it is present (issue #80:
20496
21151
  * default-on; `cache: false` = the bit-for-bit uncached wire
@@ -20509,7 +21164,7 @@ var MetaBase = class _MetaBase extends QueryBase {
20509
21164
  if (this[reader] !== _MetaBase.prototype[reader] || this.cachedMeta !== _MetaBase.prototype.cachedMeta) return { guard };
20510
21165
  return { guard, projected: this.metadataRead(kind, projector) };
20511
21166
  }
20512
- metadataRead(kind, projector) {
21167
+ metadataRead(kind, projector, fresh = false, maxRetries) {
20513
21168
  const suffix = kind === "info" ? "" : kind === "fields" ? "/fields" : "/userDefinedFields";
20514
21169
  const operation = kind === "info" ? "getEntityInfo" : kind === "fields" ? "getFieldInfo" : "getUdfInfo";
20515
21170
  const path = `${this.resourcePath}/entityInformation${suffix}`;
@@ -20521,7 +21176,7 @@ var MetaBase = class _MetaBase extends QueryBase {
20521
21176
  }
20522
21177
  return body.info;
20523
21178
  };
20524
- return projector === void 0 ? this.cachedMeta(kind, path, `${this.config.key}.${operation}`, unwrap) : cachedMetadataGet(this.http, this.config.key, kind, path, `${this.config.key}.${operation}`, unwrap, false, void 0, projector);
21179
+ return projector === void 0 ? this.cachedMeta(kind, path, `${this.config.key}.${operation}`, unwrap, fresh, maxRetries) : cachedMetadataGet(this.http, this.config.key, kind, path, `${this.config.key}.${operation}`, unwrap, false, void 0, projector);
20525
21180
  }
20526
21181
  /** @internal */
20527
21182
  unwrapFields(body, envelopeName) {
@@ -20890,6 +21545,104 @@ var MetaBase = class _MetaBase extends QueryBase {
20890
21545
  }
20891
21546
  };
20892
21547
 
21548
+ // src/resources/special/knowledgeBaseCategories.ts
21549
+ function admitKnowledgeBaseCategory(data, creating, staleToken) {
21550
+ const fail3 = (message) => {
21551
+ throw new AutotaskConfigError(`knowledge_base_categories: ${message}`);
21552
+ };
21553
+ if (!creating && staleToken !== void 0) fail3("no documented stale timestamp is available");
21554
+ if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
21555
+ const body = { ...data };
21556
+ for (const field of Object.keys(body)) if (!["name", "description", "parentCategoryID"].includes(field)) fail3(`${field} is not a writable KnowledgeBaseCategories field`);
21557
+ for (const [field, max] of [["name", 50], ["description", 1e3]]) {
21558
+ const value = body[field];
21559
+ if (value !== void 0 && (typeof value !== "string" || value.length > max)) fail3(`${field} must be a string of at most ${max} characters`);
21560
+ }
21561
+ if ((creating || body.name !== void 0) && (typeof body.name !== "string" || body.name.trim() === "")) fail3("name is required");
21562
+ if (creating && body.parentCategoryID === void 0) fail3("parentCategoryID is required; choose a documented visible category rather than guessing a root id");
21563
+ const parent = body.parentCategoryID;
21564
+ if (parent !== void 0) {
21565
+ if (typeof parent !== "number") return fail3("parentCategoryID must be a numeric identifier");
21566
+ parseIdentifier(parent, "parentCategoryID");
21567
+ if (parent > 2147483647) fail3("parentCategoryID must fit a signed 32-bit integer");
21568
+ }
21569
+ if (!creating && !Object.values(body).some((value) => value !== void 0)) fail3("update must contain a writable field");
21570
+ return body;
21571
+ }
21572
+ function categoryReplacement(body) {
21573
+ const { id, name, description, parentCategoryID } = body;
21574
+ const writable = admitKnowledgeBaseCategory({
21575
+ name,
21576
+ parentCategoryID,
21577
+ ...description === void 0 ? {} : { description }
21578
+ }, true);
21579
+ return { id, ...writable };
21580
+ }
21581
+
21582
+ // src/resources/special/knowledgeBaseArticles.ts
21583
+ function fail(detail) {
21584
+ throw new AutotaskConfigError(`knowledge_base_articles: ${detail}`);
21585
+ }
21586
+ function reference(value, name) {
21587
+ if (typeof value !== "number") fail(`${name} must be a numeric identifier`);
21588
+ parseIdentifier(value, name);
21589
+ if (value > 2147483647) fail(`${name} must fit a signed 32-bit integer`);
21590
+ return value;
21591
+ }
21592
+ function articleParent(value) {
21593
+ const parent = parseIdentifier(value, "parentId");
21594
+ if (typeof parent !== "number" || parent > 2147483647) fail("parentId must fit a signed 32-bit category identifier");
21595
+ if (parent === 0) fail("parentId must name an article category");
21596
+ return parent;
21597
+ }
21598
+ function admitArticle(data, parentId, creating) {
21599
+ const parent = articleParent(parentId);
21600
+ if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail("data must be a plain record");
21601
+ const body = { ...data };
21602
+ const allowed = ["articleCategoryID", "publish", "title", "errorCodes", "keywords", "referenceLink", "isActive"];
21603
+ for (const key of Object.keys(body)) {
21604
+ if (!allowed.includes(key)) fail(`${key} is not a writable article root field`);
21605
+ if (key !== "articleCategoryID" && body[key] === void 0) delete body[key];
21606
+ }
21607
+ for (const [field, max] of [["title", 200], ["errorCodes", 200], ["keywords", 300], ["referenceLink", 500]]) {
21608
+ if (Object.hasOwn(body, field) && (typeof body[field] !== "string" || body[field].length > max)) fail(`${field} must be a string of at most ${max} characters`);
21609
+ }
21610
+ if ((creating || Object.hasOwn(body, "title")) && (typeof body.title !== "string" || !body.title.trim())) fail("title is required and cannot be blank");
21611
+ if (!creating && Object.hasOwn(body, "articleCategoryID")) fail("articleCategoryID is read-only after creation");
21612
+ if (creating && String(reference(body.articleCategoryID, "articleCategoryID")) !== String(parent)) fail("articleCategoryID must match parentId");
21613
+ 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");
21614
+ if (Object.hasOwn(body, "isActive") && typeof body.isActive !== "boolean") fail("isActive must be boolean");
21615
+ if (!creating && !Object.keys(body).length) fail("update must contain a writable field");
21616
+ return body;
21617
+ }
21618
+ async function guardArticle(http, parentId, id, maxRetries) {
21619
+ const parent = articleParent(parentId);
21620
+ const target = id === void 0 ? void 0 : parseIdentifier(id, "id");
21621
+ if (target !== void 0 && (target === 0 || !isAuditDecimalId(String(target)))) fail("id must name an article within the signed 64-bit range");
21622
+ unwrapItem(await http.request({ method: "GET", path: `/V1.0/KnowledgeBaseCategories/${parent}`, operation: "knowledge_base_categories.get", maxRetries }), parent, "knowledge_base_categories.get", "article_category");
21623
+ if (target !== void 0) {
21624
+ 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");
21625
+ }
21626
+ return void 0;
21627
+ }
21628
+ function assertArticlePublish(data, fields) {
21629
+ if (!Object.hasOwn(data, "publish")) return;
21630
+ const unavailable = () => fail("publish requires an unambiguous active value in current field metadata");
21631
+ if (!Array.isArray(fields)) unavailable();
21632
+ const rows = fields.filter((field) => isRecord2(field) && field.name === "publish");
21633
+ if (rows.length !== 1 || rows[0].isPickList !== true || rows[0].isReadOnly !== false || !Array.isArray(rows[0].picklistValues)) unavailable();
21634
+ const values = rows[0].picklistValues;
21635
+ const matches = values.filter((value) => isRecord2(value) && typeof value.value === "string" && /^-?\d+$/.test(value.value) && Number.isSafeInteger(Number(value.value)) && Number(value.value) === data.publish);
21636
+ if (matches.length !== 1 || !isRecord2(matches[0]) || matches[0].isActive !== true) unavailable();
21637
+ }
21638
+ function isArticleTimestamp(value) {
21639
+ if (typeof value !== "string") return false;
21640
+ const match = /^(\d{4}-\d{2}-\d{2})T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/.exec(value);
21641
+ if (match === null || !Number.isFinite(Date.parse(value))) return false;
21642
+ const day = match[1];
21643
+ return (/* @__PURE__ */ new Date(`${day}T00:00:00Z`)).toISOString().slice(0, 10) === day;
21644
+ }
21645
+
20893
21646
  // src/resources/base/mutations.ts
20894
21647
  var MutationBase = class extends MetaBase {
20895
21648
  // ------------------------------------------------------------------
@@ -21082,8 +21835,9 @@ var MutationBase = class extends MetaBase {
21082
21835
  */
21083
21836
  async withPersistedCheck(result, data, opts, id, parentId) {
21084
21837
  if (opts.verifyPersisted !== true) return result;
21838
+ const maxRetries = isKnowledgeBaseRootResource(this.config.key) ? opts.maxRetries : void 0;
21085
21839
  try {
21086
- const stored = parentId === void 0 ? await this.getGlobal(id, true) : this.config.attachmentGet === true ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true);
21840
+ 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);
21087
21841
  return { ...result, notPersisted: notPersistedFields(data, stored) };
21088
21842
  } catch (err) {
21089
21843
  return { ...result, persistedCheckFailed: err instanceof AutotaskError ? err.code : `UNKNOWN (${err instanceof Error ? err.name : typeof err})` };
@@ -21105,6 +21859,7 @@ var MutationBase = class extends MetaBase {
21105
21859
  }
21106
21860
  this.staleObjectCheck(current, opts, operation);
21107
21861
  body = mergePartialBody(current, body);
21862
+ if (this.config.key === "knowledge_base_categories") body = categoryReplacement(body);
21108
21863
  } else {
21109
21864
  await this.guardStaleBeforeMutation(numeric2, opts, operation);
21110
21865
  }
@@ -21287,8 +22042,21 @@ var MutationBase = class extends MetaBase {
21287
22042
  if (parentId !== void 0 && this.config.parentField !== void 0) {
21288
22043
  conditions.unshift({ field: this.config.parentField, op: "eq", value: parentId });
21289
22044
  }
21290
- const matches = await this.queryEntity(`${this.resourcePath}/query`, conditions, { maxRecords: 10 });
21291
- const first = matches[0];
22045
+ let first;
22046
+ if (this.config.key === "knowledge_base_categories") {
22047
+ const lookup = await this.queryBounded({ filter: conditions, limit: 1, names: false });
22048
+ first = lookup.items[0];
22049
+ if (first === void 0 && lookup.hasMore) {
22050
+ throw new AutotaskError("The category deduplication lookup did not finish. No category was created.", {
22051
+ code: "INVALID_RESPONSE",
22052
+ category: "server",
22053
+ operation: "knowledge_base_categories.createIfNotExists"
22054
+ });
22055
+ }
22056
+ } else {
22057
+ const matches = await this.queryEntity(`${this.resourcePath}/query`, conditions, { maxRecords: 10 });
22058
+ first = matches[0];
22059
+ }
21292
22060
  if (first !== void 0) {
21293
22061
  const firstId = first.id;
21294
22062
  if (isIdentifierCandidate(firstId)) {
@@ -21340,10 +22108,14 @@ var MutationBase = class extends MetaBase {
21340
22108
  const expected = opts.lastModifiedDate;
21341
22109
  if (field === void 0 || expected === void 0) return false;
21342
22110
  const actual = current[field];
22111
+ const article = this.config.key === "knowledge_base_articles";
22112
+ if (article && (!isArticleTimestamp(actual) || !isArticleTimestamp(expected))) {
22113
+ throw new AutotaskConfigError("knowledge_base_articles: lastModifiedDateTime or the stale token is withheld or malformed; valid timestamps are required");
22114
+ }
21343
22115
  if (typeof actual !== "string") return false;
21344
22116
  if (actual !== expected) {
21345
22117
  throw new StaleObjectError(
21346
- `stale object: ${this.config.key} ${field} changed since the caller read it (expected ${expected}, current ${actual})`,
22118
+ article ? "stale object: knowledge_base_articles lastModifiedDateTime changed since the caller read it" : `stale object: ${this.config.key} ${field} changed since the caller read it (expected ${expected}, current ${actual})`,
21347
22119
  {
21348
22120
  code: "STALE_OBJECT",
21349
22121
  operation,
@@ -21376,7 +22148,7 @@ var MutationBase = class extends MetaBase {
21376
22148
  * verification is a read). Duplicate detection has no reliable lookup for
21377
22149
  * a plain create (that is `createIfNotExists`), so it is not claimed.
21378
22150
  */
21379
- async runCreateDryRun(data, parentId) {
22151
+ async runCreateDryRun(data, parentId, parentVerified = false) {
21380
22152
  const checks = [];
21381
22153
  const warnings = [];
21382
22154
  checks.push({ name: "input-validation", ok: isRecord2(data) && Object.keys(data).length > 0 });
@@ -21394,20 +22166,20 @@ var MutationBase = class extends MetaBase {
21394
22166
  `dry-run: ${this.config.key} is parent-scoped but has no parentPath configured`
21395
22167
  );
21396
22168
  }
21397
- let parent = null;
21398
- if (isIdentifierCandidate(parentId)) {
22169
+ let parentExists = parentVerified;
22170
+ if (!parentExists && isIdentifierCandidate(parentId)) {
21399
22171
  try {
21400
- parent = await this.fetchRecordRaw(
22172
+ parentExists = await this.fetchRecordRaw(
21401
22173
  parentPath,
21402
22174
  parseIdentifier(parentId, "parentId"),
21403
22175
  true
21404
- );
22176
+ ) !== null;
21405
22177
  } catch (err) {
21406
22178
  if (!(err instanceof NotFoundError)) throw err;
21407
22179
  }
21408
22180
  }
21409
- checks.push({ name: "parent-exists", ok: parent !== null });
21410
- if (parent === null) {
22181
+ checks.push({ name: "parent-exists", ok: parentExists });
22182
+ if (!parentExists) {
21411
22183
  warnings.push(`parent ${parentId} not found; the vendor would reject the create`);
21412
22184
  }
21413
22185
  }
@@ -21438,7 +22210,7 @@ var MutationBase = class extends MetaBase {
21438
22210
  * check (mismatch throws STALE_OBJECT) and the best-effort `diff`. NO
21439
22211
  * mutating request is issued.
21440
22212
  */
21441
- async runUpdateDryRun(id, data, opts = {}, parentId) {
22213
+ async runUpdateDryRun(id, data, opts = {}, parentId, currentRecord) {
21442
22214
  const operation = `${this.config.key}.update`;
21443
22215
  const checks = [];
21444
22216
  const warnings = [];
@@ -21449,7 +22221,7 @@ var MutationBase = class extends MetaBase {
21449
22221
  const method = scopedUpdate ? "PATCH" : "PUT";
21450
22222
  let current;
21451
22223
  try {
21452
- current = parentId === void 0 ? await this.getGlobal(id, true) : this.config.attachmentGet ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true);
22224
+ 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));
21453
22225
  } catch (err) {
21454
22226
  if (err instanceof NotFoundError) {
21455
22227
  const updateReason = EMPTY_REASON_STAMPS[this.config.key]?.update;
@@ -21478,11 +22250,11 @@ var MutationBase = class extends MetaBase {
21478
22250
  checks.push({ name: "stale-check", ok: true });
21479
22251
  }
21480
22252
  let envelopeData = data;
21481
- if (parentId === void 0 && this.config.collectionUpdate === true && opts.raw !== true) {
21482
- envelopeData = mergePartialBody(
21483
- current,
21484
- this.normalizeMutationBody(data)
21485
- );
22253
+ if (this.config.key === "knowledge_base_articles") {
22254
+ envelopeData = { ...this.normalizeMutationBody(data), id };
22255
+ } else if (parentId === void 0 && this.config.collectionUpdate === true && opts.raw !== true) {
22256
+ const merged = mergePartialBody(current, this.normalizeMutationBody(data));
22257
+ envelopeData = this.config.key === "knowledge_base_categories" ? categoryReplacement({ ...merged, id }) : merged;
21486
22258
  }
21487
22259
  return buildDryRunResult({
21488
22260
  operation,
@@ -21501,14 +22273,14 @@ var MutationBase = class extends MetaBase {
21501
22273
  * the pinned envelope (no diff — a delete has no before/after fields). NO
21502
22274
  * mutating request is issued.
21503
22275
  */
21504
- async runDeleteDryRun(id, opts = {}, parentId) {
22276
+ async runDeleteDryRun(id, opts = {}, parentId, currentRecord) {
21505
22277
  const operation = `${this.config.key}.delete`;
21506
22278
  const checks = [];
21507
22279
  const warnings = [];
21508
22280
  const path = parentId === void 0 ? `${this.resourcePath}/${id}` : this.scopedItemPath(parentId, id);
21509
22281
  let current;
21510
22282
  try {
21511
- current = parentId === void 0 ? await this.getGlobal(id, true) : this.config.attachmentGet ? await this.getScopedModel(parentId, id, true) : await this.getScopedRaw(parentId, id, true);
22283
+ 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));
21512
22284
  } catch (err) {
21513
22285
  if (err instanceof NotFoundError) {
21514
22286
  checks.push({ name: "current-record-exists", ok: false });
@@ -21529,13 +22301,15 @@ var MutationBase = class extends MetaBase {
21529
22301
  if (this.staleObjectCheck(current, opts, operation)) {
21530
22302
  checks.push({ name: "stale-check", ok: true });
21531
22303
  }
22304
+ const category = this.config.key === "knowledge_base_categories";
22305
+ if (category) warnings.push("Deleting a populated category reassigns its articles to the parent category. The affected article count is unknown.");
21532
22306
  return buildDryRunResult({
21533
22307
  operation,
21534
22308
  method: "DELETE",
21535
22309
  path,
21536
22310
  ids: [id],
21537
22311
  checks,
21538
- impact: { affected: 1, scope: "single-record", reversible: false },
22312
+ impact: { affected: 1, scope: category ? "category and associated articles (article count unknown)" : "single-record", reversible: false },
21539
22313
  warnings
21540
22314
  }, { redactPersonalData: this.http.redactPersonalData });
21541
22315
  }
@@ -21553,34 +22327,34 @@ var BaseResource = class extends MutationBase {
21553
22327
  };
21554
22328
 
21555
22329
  // src/resources/special/taskPredecessors.ts
21556
- function fail(detail) {
22330
+ function fail2(detail) {
21557
22331
  throw new AutotaskConfigError(`task_predecessors: ${detail}`);
21558
22332
  }
21559
22333
  function numeric(value, field) {
21560
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) fail(`${field} must be a positive numeric identifier`);
22334
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) fail2(`${field} must be a positive numeric identifier`);
21561
22335
  return value;
21562
22336
  }
21563
22337
  function predecessorParent(value) {
21564
22338
  const parent = parseIdentifier(value, "parentId");
21565
- if (parent === 0) fail("parentId must name a successor task");
22339
+ if (parent === 0) fail2("parentId must name a successor task");
21566
22340
  return parent;
21567
22341
  }
21568
22342
  function assertPredecessorBinding(value, parentId, id) {
21569
- if (!isRecord2(value)) fail("the returned record must establish id and successorTaskID parent");
21570
- if (String(parseIdentifier(value.id, "record.id")) !== String(parseIdentifier(id, "id")) || String(parseIdentifier(value.successorTaskID, "record.successorTaskID")) !== String(predecessorParent(parentId))) fail("the returned record must match id and successorTaskID parent");
22343
+ if (!isRecord2(value)) fail2("the returned record must establish id and successorTaskID parent");
22344
+ 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");
21571
22345
  }
21572
22346
  function admitTaskPredecessor(data, parentId, creating) {
21573
22347
  const parent = predecessorParent(parentId);
21574
- if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail("data must be a plain record");
22348
+ if (!isRecord2(data) || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail2("data must be a plain record");
21575
22349
  const payload = { ...data };
21576
22350
  const allowed = creating ? ["predecessorTaskID", "successorTaskID", "lagDays"] : ["lagDays"];
21577
- if (Object.keys(payload).some((key) => !allowed.includes(key))) fail(creating ? "only predecessorTaskID, successorTaskID and lagDays are writable on create" : "only lagDays can be updated");
21578
- if ((!creating || payload.lagDays !== void 0) && (typeof payload.lagDays !== "number" || !Number.isInteger(payload.lagDays) || payload.lagDays < -2147483648 || payload.lagDays > 2147483647)) fail("lagDays must be an int32 integer");
22351
+ 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");
22352
+ 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");
21579
22353
  if (creating) {
21580
22354
  const successor = numeric(payload.successorTaskID, "successorTaskID");
21581
22355
  const predecessor = numeric(payload.predecessorTaskID, "predecessorTaskID");
21582
- if (String(successor) !== String(parent)) fail("successorTaskID must match parentId");
21583
- if (predecessor === successor) fail("predecessorTaskID and successorTaskID must be distinct");
22356
+ if (String(successor) !== String(parent)) fail2("successorTaskID must match parentId");
22357
+ if (predecessor === successor) fail2("predecessorTaskID and successorTaskID must be distinct");
21584
22358
  }
21585
22359
  return payload;
21586
22360
  }
@@ -21589,50 +22363,137 @@ async function guardTaskPredecessor(http, parentId, id, data) {
21589
22363
  let row = data;
21590
22364
  if (id !== void 0) {
21591
22365
  const target = parseIdentifier(id, "id");
21592
- if (target === 0) fail("id must name a predecessor relationship");
22366
+ if (target === 0) fail2("id must name a predecessor relationship");
21593
22367
  row = unwrapItem(await http.request({ method: "GET", path: `/V1.0/Tasks/${parent}/Predecessors/${target}`, operation: "task_predecessors.get" }), target, "task_predecessors.get", "task_predecessor");
21594
22368
  assertPredecessorBinding(row, parent, target);
21595
22369
  }
21596
22370
  const predecessor = numeric(row?.predecessorTaskID, "predecessorTaskID");
21597
22371
  const successor = numeric(row?.successorTaskID, "successorTaskID");
21598
- if (predecessor === successor) fail("predecessorTaskID and successorTaskID must be distinct");
22372
+ if (predecessor === successor) fail2("predecessorTaskID and successorTaskID must be distinct");
21599
22373
  const projects = [];
21600
22374
  for (const taskId of [predecessor, successor]) {
21601
22375
  const task = unwrapItem(await http.request({ method: "GET", path: `/V1.0/Tasks/${taskId}`, operation: "tasks.get" }), taskId, "tasks.get", "task");
21602
- if (String(parseIdentifier(task.id, "task.id")) !== String(taskId)) fail("the returned task must match its requested id");
22376
+ if (String(parseIdentifier(task.id, "task.id")) !== String(taskId)) fail2("the returned task must match its requested id");
21603
22377
  projects.push(numeric(task.projectID, "task.projectID"));
21604
22378
  }
21605
- if (projects[0] !== projects[1]) fail("predecessor and successor tasks must belong to the same project");
22379
+ if (projects[0] !== projects[1]) fail2("predecessor and successor tasks must belong to the same project");
21606
22380
  }
21607
22381
 
21608
22382
  // src/resources/special/taskNotes.ts
21609
22383
  var WRITABLE = /* @__PURE__ */ new Set(["id", "itemId", "createdByContactID", "description", "noteType", "publish", "taskID", "title"]);
21610
22384
  function admitTaskNote(data, parentId, creating) {
21611
22385
  const parent = parseIdentifier(parentId, "parentId");
21612
- const fail2 = (message) => {
22386
+ const fail3 = (message) => {
21613
22387
  throw new AutotaskConfigError(`task_notes: ${message}`);
21614
22388
  };
21615
- if (data === null || typeof data !== "object" || Array.isArray(data)) fail2("data must be a record");
22389
+ if (data === null || typeof data !== "object" || Array.isArray(data)) fail3("data must be a record");
21616
22390
  const body = data;
21617
- for (const key of Object.keys(body)) if (!WRITABLE.has(key)) fail2(`${key} is not a writable TaskNotes field`);
22391
+ for (const key of Object.keys(body)) if (!WRITABLE.has(key)) fail3(`${key} is not a writable TaskNotes field`);
21618
22392
  for (const [field, maximum] of [["description", 3200], ["title", 250]]) {
21619
22393
  const value = body[field];
21620
- if (value !== void 0 && (typeof value !== "string" || value.length > maximum)) fail2(`${field} must be a string of at most ${maximum} characters`);
22394
+ if (value !== void 0 && (typeof value !== "string" || value.length > maximum)) fail3(`${field} must be a string of at most ${maximum} characters`);
21621
22395
  }
21622
- if (creating && (typeof body.description !== "string" || body.description.trim() === "")) fail2("description is required");
22396
+ if (creating && (typeof body.description !== "string" || body.description.trim() === "")) fail3("description is required");
21623
22397
  for (const field of ["noteType", "publish"]) {
21624
22398
  const value = body[field];
21625
- if ((creating || value !== void 0) && (typeof value !== "number" || !Number.isSafeInteger(value))) fail2(`${field} must be an integer from the current field metadata`);
22399
+ if ((creating || value !== void 0) && (typeof value !== "number" || !Number.isSafeInteger(value))) fail3(`${field} must be an integer from the current field metadata`);
21626
22400
  }
21627
- if (creating && body.taskID === void 0) fail2("taskID is required in the create body and must match parentId");
22401
+ if (creating && body.taskID === void 0) fail3("taskID is required in the create body and must match parentId");
21628
22402
  for (const field of ["createdByContactID", "taskID"]) {
21629
22403
  if (body[field] !== void 0) {
21630
- if (typeof body[field] !== "number") fail2(`${field} must be a numeric identifier`);
22404
+ if (typeof body[field] !== "number") fail3(`${field} must be a numeric identifier`);
21631
22405
  const id = parseIdentifier(body[field], field);
21632
- if (field === "taskID" && String(id) !== String(parent)) fail2("taskID must match the parentId path argument");
22406
+ if (field === "taskID" && String(id) !== String(parent)) fail3("taskID must match the parentId path argument");
22407
+ }
22408
+ }
22409
+ if (!creating && !Object.keys(body).some((key) => key !== "id" && key !== "itemId")) fail3("update must contain a writable field");
22410
+ }
22411
+
22412
+ // src/operations/invoke/fieldSuggest.ts
22413
+ var MAX_SUGGESTIONS = 3;
22414
+ var MIN_SUBSTRING_CHARS = 4;
22415
+ var GENERIC_TOKENS = /* @__PURE__ */ new Set(["date", "time", "datetime", "day", "is", "number", "type", "name", "last", "on", "at", "id"]);
22416
+ var DATE_TOKENS = /* @__PURE__ */ new Set(["date", "time", "datetime", "day", "on", "at"]);
22417
+ var TOKEN_SYNONYMS = [["install", "purchase", "purchased"]];
22418
+ var SYNONYM_OF = new Map(TOKEN_SYNONYMS.flatMap((group) => group.map((t) => [t, group[0]])));
22419
+ var Tier = { Substring: 0, Tokens: 1, Edit: 2, Generic: 3, SameType: 4, Rest: 5 };
22420
+ function tokens(name) {
22421
+ return (name.match(/[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+/g) ?? []).map((t) => t.toLowerCase());
22422
+ }
22423
+ function normalTokens(name) {
22424
+ return new Set(tokens(name).map((t) => SYNONYM_OF.get(t) ?? t));
22425
+ }
22426
+ function editDistance(a, b, cap = Number.POSITIVE_INFINITY) {
22427
+ if (Math.abs(a.length - b.length) > cap) return cap + 1;
22428
+ const far = Number.isFinite(cap) ? cap + 1 : a.length + b.length + 1;
22429
+ const band = Number.isFinite(cap) ? cap : a.length + b.length;
22430
+ let prev2 = new Int32Array(b.length + 1).fill(far);
22431
+ let prev = Int32Array.from({ length: b.length + 1 }, (_, j) => j <= band ? j : far);
22432
+ let cur = new Int32Array(b.length + 1).fill(far);
22433
+ for (let i = 1; i <= a.length; i += 1) {
22434
+ const lo = Math.max(1, i - band);
22435
+ const hi = Math.min(b.length, i + band);
22436
+ cur.fill(far);
22437
+ cur[0] = i <= band ? i : far;
22438
+ let rowMin = cur[0];
22439
+ for (let j = lo; j <= hi; j += 1) {
22440
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
22441
+ let v = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
22442
+ 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);
22443
+ cur[j] = v;
22444
+ if (v < rowMin) rowMin = v;
22445
+ }
22446
+ if (rowMin > cap) return cap + 1;
22447
+ [prev2, prev, cur] = [prev, cur, prev2];
22448
+ }
22449
+ return Math.min(prev[b.length], cap + 1);
22450
+ }
22451
+ function looksLikeDate(name) {
22452
+ return tokens(name).some((t) => DATE_TOKENS.has(t));
22453
+ }
22454
+ var MAX_EDITS = 6;
22455
+ var DISTANCE_CAP = 8;
22456
+ function score(unknown, candidate2) {
22457
+ const u = unknown.lower;
22458
+ const c = candidate2.lower;
22459
+ const [shorter, longer] = u.length <= c.length ? [u, c] : [c, u];
22460
+ let shared = 0;
22461
+ let meaningful = 0;
22462
+ for (const t of candidate2.tokens) {
22463
+ if (!unknown.tokens.has(t)) continue;
22464
+ shared += 1;
22465
+ if (!GENERIC_TOKENS.has(t)) meaningful += 1;
22466
+ }
22467
+ const threshold = Math.min(MAX_EDITS, Math.max(1, Math.floor(longer.length * 0.3)));
22468
+ const distance = editDistance(u, c, DISTANCE_CAP);
22469
+ const shorterGeneric = shorter === u ? unknown.allGeneric : [...candidate2.tokens].every((t) => GENERIC_TOKENS.has(t));
22470
+ if (shorter.length >= MIN_SUBSTRING_CHARS && longer.includes(shorter) && !shorterGeneric) return { tier: Tier.Substring, shared, distance };
22471
+ if (meaningful > 0) return { tier: Tier.Tokens, shared, distance };
22472
+ if (shorter.length >= 3 && distance <= threshold) return { tier: Tier.Edit, shared, distance };
22473
+ if (shared > 0) return { tier: Tier.Generic, shared, distance };
22474
+ if (candidate2.isDate && unknown.isDate) return { tier: Tier.SameType, shared, distance };
22475
+ return { tier: Tier.Rest, shared, distance };
22476
+ }
22477
+ var better = (a, b) => a.tier - b.tier || b.shared - a.shared || a.distance - b.distance;
22478
+ var isClose = (s) => s.tier <= Tier.Edit;
22479
+ function rankFieldNames(unknown, known, dateFields = []) {
22480
+ const dates = new Set(dateFields);
22481
+ const candidates = known.map((name) => ({ name, lower: name.toLowerCase(), tokens: normalTokens(name), isDate: dates.has(name) }));
22482
+ const best = /* @__PURE__ */ new Map();
22483
+ const suggestions = [];
22484
+ for (const name of new Set(unknown)) {
22485
+ const probeTokens = normalTokens(name);
22486
+ const probe = { lower: name.toLowerCase(), tokens: probeTokens, isDate: looksLikeDate(name), allGeneric: [...probeTokens].every((t) => GENERIC_TOKENS.has(t)) };
22487
+ const scored = candidates.map((c, index) => ({ k: c.name, index, s: score(probe, c) }));
22488
+ for (const { k, s } of scored) {
22489
+ const prev = best.get(k);
22490
+ if (prev === void 0 || better(s, prev) < 0) best.set(k, s);
21633
22491
  }
22492
+ const close = scored.filter((x) => isClose(x.s)).sort((a, b) => better(a.s, b.s) || a.index - b.index);
22493
+ if (close.length > 0) suggestions.push({ name, candidates: close.slice(0, MAX_SUGGESTIONS).map((x) => x.k) });
21634
22494
  }
21635
- if (!creating && !Object.keys(body).some((key) => key !== "id" && key !== "itemId")) fail2("update must contain a writable field");
22495
+ 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);
22496
+ return { ordered, suggestions };
21636
22497
  }
21637
22498
 
21638
22499
  // src/operations/invoke/fieldNames.ts
@@ -21650,6 +22511,14 @@ async function liveFieldNames(holder) {
21650
22511
  var UNKNOWN_NAME_LIST_CAP = 20;
21651
22512
  var UNKNOWN_NAME_DISPLAY_CHARS = 40;
21652
22513
  var ENTITY_NAME_LIST_CAP = 20;
22514
+ var REFUSAL_MAX_CHARS = 3e3;
22515
+ var SUGGESTED_NAME_CAP = 5;
22516
+ function didYouMeanClause(suggestions, take = SUGGESTED_NAME_CAP) {
22517
+ const shown = suggestions.slice(0, take);
22518
+ if (shown.length === 0) return "";
22519
+ const cut = (n) => n.length > UNKNOWN_NAME_DISPLAY_CHARS ? `${n.slice(0, UNKNOWN_NAME_DISPLAY_CHARS)}\u2026` : n;
22520
+ return ` \u2014 did you mean: ${shown.map((s) => `"${cut(s.name)}" -> ${s.candidates.map(cut).join(", ")}`).join("; ")}`;
22521
+ }
21653
22522
  function formatUnknownNameList(names, cap = UNKNOWN_NAME_LIST_CAP) {
21654
22523
  const listed = names.slice(0, cap).map((n) => `"${n.length > UNKNOWN_NAME_DISPLAY_CHARS ? `${n.slice(0, UNKNOWN_NAME_DISPLAY_CHARS)}\u2026` : n}"`).join(", ");
21655
22524
  const more = names.length > cap ? ` (and ${names.length - cap} more)` : "";
@@ -21732,10 +22601,16 @@ function unknownNamesRefusal(record, authority, known, unknownInclude, unknownFi
21732
22601
  if (unknownInclude.length > 0) parts.push(`includeFields has unknown field name(s) ${formatUnknownNameList(unknownInclude)}`);
21733
22602
  if (unknownFilter.length > 0) parts.push(`filter condition(s) carry unknown field name(s) ${formatUnknownNameList(unknownFilter)}`);
21734
22603
  const wireClause = record.operation === "count" ? "the count request was not issued" : "the query POST was not issued";
21735
- const head = `invoke: "${record.id}" ${parts.join("; ")} against ${authority}`;
22604
+ const base = `invoke: "${record.id}" ${parts.join("; ")} against ${authority}`;
22605
+ const ranked = [...unknownInclude.slice(0, UNKNOWN_NAME_LIST_CAP), ...unknownFilter.slice(0, UNKNOWN_NAME_LIST_CAP)];
22606
+ const { ordered, suggestions } = rankFieldNames(ranked, known, MODEL_DATE_FIELDS[record.resource]);
21736
22607
  const count = known.length > ENTITY_NAME_LIST_CAP ? `${known.length}, first ${ENTITY_NAME_LIST_CAP}` : `${known.length}`;
21737
- const withList = `${head} \u2014 fields available on ${record.resource} (${count}): ${formatUnknownNameList(known, ENTITY_NAME_LIST_CAP)} \u2014 ${wireClause}`;
21738
- 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}`;
22608
+ const pointer = `${record.resource} has ${known.length} fields; use operations.fieldCatalog resources: ["${record.resource}"] for the full set`;
22609
+ let take = SUGGESTED_NAME_CAP;
22610
+ while (take > 0 && `${base}${didYouMeanClause(suggestions, take)} \u2014 ${pointer} \u2014 ${wireClause}`.length > REFUSAL_MAX_CHARS) take -= 1;
22611
+ const head = `${base}${didYouMeanClause(suggestions, take)}`;
22612
+ const withList = `${head} \u2014 fields available on ${record.resource} (${count}): ${formatUnknownNameList(ordered, ENTITY_NAME_LIST_CAP)} \u2014 ${wireClause}`;
22613
+ const message = known.length === 0 ? `${head} \u2014 ${wireClause}` : withList.length <= REFUSAL_MAX_CHARS ? withList : `${head} \u2014 ${pointer} \u2014 ${wireClause}`;
21739
22614
  return new AutotaskConfigError(
21740
22615
  message,
21741
22616
  {
@@ -21801,40 +22676,40 @@ function isBase64(value) {
21801
22676
  }
21802
22677
  function admitTaskAttachment(data, parentId) {
21803
22678
  const parent = parseIdentifier(parentId, "parentId");
21804
- const fail2 = (message) => {
22679
+ const fail3 = (message) => {
21805
22680
  throw new AutotaskConfigError(`task_attachments: ${message}`);
21806
22681
  };
21807
- if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail2("data must be a plain record");
22682
+ if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
21808
22683
  const body = data;
21809
- for (const field of Object.keys(body)) if (!WRITABLE2.has(field)) fail2(`${field} is not a supported create field`);
22684
+ for (const field of Object.keys(body)) if (!WRITABLE2.has(field)) fail3(`${field} is not a supported create field`);
21810
22685
  for (const field of ["attachmentType", "fullPath", "title"]) {
21811
- if (typeof body[field] !== "string" || body[field].trim() === "") fail2(`${field} is required and must be a non-empty string`);
22686
+ if (typeof body[field] !== "string" || body[field].trim() === "") fail3(`${field} is required and must be a non-empty string`);
21812
22687
  }
21813
- if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail2("publish must be an integer from current field metadata");
22688
+ if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail3("publish must be an integer from current field metadata");
21814
22689
  for (const field of ["data", "contentType"]) {
21815
- if (body[field] !== void 0 && typeof body[field] !== "string") fail2(`${field} must be a string`);
22690
+ if (body[field] !== void 0 && typeof body[field] !== "string") fail3(`${field} must be a string`);
21816
22691
  }
21817
22692
  if (body.attachmentType === "FILE_ATTACHMENT") {
21818
- if (typeof body.data !== "string" || body.data === "") return fail2("FILE_ATTACHMENT requires non-empty base64 data");
21819
- if (!isBase64(body.data)) fail2("FILE_ATTACHMENT data must be base64 encoded");
22693
+ if (typeof body.data !== "string" || body.data === "") return fail3("FILE_ATTACHMENT requires non-empty base64 data");
22694
+ if (!isBase64(body.data)) fail3("FILE_ATTACHMENT data must be base64 encoded");
21820
22695
  }
21821
22696
  if (body.taskID !== void 0) {
21822
- if (typeof body.taskID !== "number") fail2("taskID must be a numeric identifier");
21823
- if (String(parseIdentifier(body.taskID, "taskID")) !== String(parent)) fail2("taskID must match the parentId path argument");
22697
+ if (typeof body.taskID !== "number") fail3("taskID must be a numeric identifier");
22698
+ if (String(parseIdentifier(body.taskID, "taskID")) !== String(parent)) fail3("taskID must match the parentId path argument");
21824
22699
  }
21825
22700
  if (body.parentAttachmentID !== void 0) {
21826
- if (typeof body.parentAttachmentID !== "number") fail2("parentAttachmentID must be a numeric identifier");
22701
+ if (typeof body.parentAttachmentID !== "number") fail3("parentAttachmentID must be a numeric identifier");
21827
22702
  parseIdentifier(body.parentAttachmentID, "parentAttachmentID");
21828
22703
  }
21829
22704
  }
21830
22705
  function admitFileAttachment(resource, data, parentId) {
21831
22706
  parseIdentifier(parentId, "parentId");
21832
- const fail2 = (message) => {
22707
+ const fail3 = (message) => {
21833
22708
  throw new AutotaskConfigError(`${resource}: ${message}`);
21834
22709
  };
21835
- if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail2("data must be a plain record");
22710
+ if (data === null || typeof data !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(data))) fail3("data must be a plain record");
21836
22711
  const body = data;
21837
- const reference = {
22712
+ const reference2 = {
21838
22713
  project_attachments: void 0,
21839
22714
  contract_note_attachments: void 0,
21840
22715
  sales_order_attachments: void 0,
@@ -21845,20 +22720,20 @@ function admitFileAttachment(resource, data, parentId) {
21845
22720
  configuration_item_attachments: "parentAttachmentID",
21846
22721
  configuration_item_note_attachments: void 0
21847
22722
  }[resource];
21848
- for (const field of Object.keys(body)) if (!FILE_WRITABLE.has(field) && field !== reference) fail2(`${field} is not a supported create field`);
21849
- if (body.attachmentType !== "FILE_ATTACHMENT") fail2("attachmentType must explicitly be FILE_ATTACHMENT; other attachment types are unsupported");
22723
+ for (const field of Object.keys(body)) if (!FILE_WRITABLE.has(field) && field !== reference2) fail3(`${field} is not a supported create field`);
22724
+ if (body.attachmentType !== "FILE_ATTACHMENT") fail3("attachmentType must explicitly be FILE_ATTACHMENT; other attachment types are unsupported");
21850
22725
  const maxLength = resource === "project_attachments" ? void 0 : 255;
21851
22726
  for (const field of ["fullPath", "title"]) {
21852
22727
  const value = body[field];
21853
22728
  const requirement = `${field} is required and must be a nonblank string${maxLength === void 0 ? "" : ` of at most ${maxLength} characters`}`;
21854
- if (typeof value !== "string" || value.trim() === "") return fail2(requirement);
21855
- if (maxLength !== void 0 && value.length > maxLength) fail2(requirement);
22729
+ if (typeof value !== "string" || value.trim() === "") return fail3(requirement);
22730
+ if (maxLength !== void 0 && value.length > maxLength) fail3(requirement);
21856
22731
  }
21857
- if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail2("publish must be an integer from current field metadata");
21858
- if (typeof body.data !== "string" || !isBase64(body.data)) fail2("FILE_ATTACHMENT requires nonempty base64 data");
21859
- if (reference !== void 0 && body[reference] !== void 0) {
21860
- if (typeof body[reference] !== "number") fail2(`${reference} must be a numeric identifier`);
21861
- if (parseIdentifier(body[reference], reference) === 0) fail2(`${reference} must be positive`);
22732
+ if (typeof body.publish !== "number" || !Number.isSafeInteger(body.publish)) fail3("publish must be an integer from current field metadata");
22733
+ if (typeof body.data !== "string" || !isBase64(body.data)) fail3("FILE_ATTACHMENT requires nonempty base64 data");
22734
+ if (reference2 !== void 0 && body[reference2] !== void 0) {
22735
+ if (typeof body[reference2] !== "number") fail3(`${reference2} must be a numeric identifier`);
22736
+ if (parseIdentifier(body[reference2], reference2) === 0) fail3(`${reference2} must be positive`);
21862
22737
  }
21863
22738
  }
21864
22739
  function admitScopedAttachmentQuery(resource, params) {
@@ -22717,6 +23592,31 @@ var SIMPLE_RESOURCES = [
22717
23592
  helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
22718
23593
  opForms: { get: "global" }
22719
23594
  },
23595
+ {
23596
+ key: "knowledge_base_articles",
23597
+ accessor: "knowledgeBaseArticles",
23598
+ resourcePath: "/V1.0/KnowledgeBaseArticles",
23599
+ parentScopedPath: "/V1.0/KnowledgeBaseCategories/{parentId}/KnowledgeBaseArticles",
23600
+ parentPath: "/V1.0/KnowledgeBaseCategories",
23601
+ parentField: "articleCategoryID",
23602
+ deletable: true,
23603
+ udfCapable: false,
23604
+ staleField: "lastModifiedDateTime",
23605
+ ops: { query: true, queryAll: false, count: true, get: true, create: true, update: true, delete: true, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
23606
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
23607
+ opForms: { get: "global", create: "scoped", update: "scoped", delete: "scoped" }
23608
+ },
23609
+ {
23610
+ key: "knowledge_base_categories",
23611
+ accessor: "knowledgeBaseCategories",
23612
+ resourcePath: "/V1.0/KnowledgeBaseCategories",
23613
+ deletable: true,
23614
+ udfCapable: false,
23615
+ collectionUpdate: true,
23616
+ ops: { query: true, queryAll: false, count: true, get: true, create: true, update: true, delete: true, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
23617
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
23618
+ opForms: { get: "global", create: "global", update: "global", delete: "global" }
23619
+ },
22720
23620
  {
22721
23621
  key: "notification_history",
22722
23622
  accessor: "notificationHistory",
@@ -23577,9 +24477,23 @@ var GenericResource = class extends BaseResource {
23577
24477
  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 () => {
23578
24478
  throw new OperationNotSupportedError(config.key, "getUdfInfo");
23579
24479
  };
23580
- if (config.ops?.create === false || isScopedAttachmentResource(config.key) || ["company_attachments", "task_predecessors"].includes(config.key)) this.createIfNotExists = async () => {
24480
+ if (config.ops?.create === false || isScopedAttachmentResource(config.key) || ["company_attachments", "task_predecessors", "knowledge_base_articles"].includes(config.key)) this.createIfNotExists = async () => {
23581
24481
  throw new OperationNotSupportedError(config.key, "createIfNotExists");
23582
24482
  };
24483
+ if (config.key === "knowledge_base_categories") {
24484
+ const compose = this.createIfNotExists.bind(this);
24485
+ this.createIfNotExists = async (a, b) => {
24486
+ const input = admitKnowledgeBaseCategory(a, true);
24487
+ const opts = b;
24488
+ const { dryRun } = snapshotMutationOptions(opts);
24489
+ const supplied = opts?.dedupFields;
24490
+ const fields = Array.isArray(supplied) ? Array.from({ length: supplied.length }, (_, i) => supplied[i]) : supplied;
24491
+ if (fields !== void 0 && (!Array.isArray(fields) || fields.some((field) => typeof field !== "string" || !Object.hasOwn(input, field) || input[field] === void 0))) {
24492
+ throw new AutotaskConfigError("knowledge_base_categories: each dedup field must match a supplied writable field by its API name");
24493
+ }
24494
+ return compose(input, { dryRun, dedupFields: fields });
24495
+ };
24496
+ }
23583
24497
  if (config.key === "task_notes") {
23584
24498
  const compose = this.createIfNotExists.bind(this);
23585
24499
  this.createIfNotExists = async (a, b, c = {}) => {
@@ -23589,7 +24503,7 @@ var GenericResource = class extends BaseResource {
23589
24503
  }
23590
24504
  }
23591
24505
  putFallbackEligible(err) {
23592
- return this.config.key !== "task_predecessors" && super.putFallbackEligible(err);
24506
+ return !["task_predecessors", "knowledge_base_articles"].includes(this.config.key) && super.putFallbackEligible(err);
23593
24507
  }
23594
24508
  /** #293 QA F2: the superset exposes every generic method, but a row whose ops/helpers
23595
24509
  * flags mark an op absent (the plain entities) refuses it client-side, pre-wire — the
@@ -23626,7 +24540,7 @@ var GenericResource = class extends BaseResource {
23626
24540
  /** Query records with the G3 filter surface (server-side JSON filter). */
23627
24541
  query(params) {
23628
24542
  this.requireOp("query");
23629
- return this.queryItems(params);
24543
+ return this.queryItems(this.snapshotKnowledgeBaseQuery(params));
23630
24544
  }
23631
24545
  /** Get every record (the MCP-preferred read; 1000-page guarded). */
23632
24546
  async queryAll(params) {
@@ -23658,22 +24572,29 @@ var GenericResource = class extends BaseResource {
23658
24572
  this.requireOp("create");
23659
24573
  if (isIdentifier(a)) {
23660
24574
  if (this.config.opForms?.create === "global") throw new OperationNotSupportedError(this.config.key, "create");
23661
- const parentId = a;
23662
- const data2 = this.config.key === "task_predecessors" ? admitTaskPredecessor(b, parentId, true) : b;
23663
- const opts2 = this.config.key === "task_predecessors" ? { ...c } : c ?? {};
24575
+ const parentId = this.config.key === "knowledge_base_articles" ? articleParent(a) : a;
24576
+ const data2 = this.config.key === "knowledge_base_articles" ? admitArticle(b, parentId, true) : this.config.key === "task_predecessors" ? admitTaskPredecessor(b, parentId, true) : b;
24577
+ let opts2 = c ?? {};
24578
+ if (this.config.key === "knowledge_base_articles") opts2 = snapshotMutationOptions(c);
24579
+ else if (this.config.key === "task_predecessors") opts2 = { ...c };
23664
24580
  if (this.config.key === "task_notes") admitTaskNote(data2, parentId, true);
23665
24581
  const key = this.config.key;
23666
24582
  if (isScopedAttachmentResource(key)) {
23667
24583
  if (key === "task_attachments") admitTaskAttachment(data2, parentId);
23668
24584
  else admitFileAttachment(key, data2, parentId);
23669
24585
  }
24586
+ if (this.config.key === "knowledge_base_articles") {
24587
+ await guardArticle(this.http, parentId, void 0, opts2.maxRetries);
24588
+ assertArticlePublish(data2, await this.getFreshFieldInfo(opts2.maxRetries));
24589
+ }
23670
24590
  if (this.config.key === "task_predecessors") await guardTaskPredecessor(this.http, parentId, void 0, data2);
23671
- if (opts2.dryRun === true) return this.runCreateDryRun(data2, parentId);
24591
+ if (opts2.dryRun === true) return this.runCreateDryRun(data2, parentId, key === "knowledge_base_articles");
23672
24592
  return this.createScopedRaw(parentId, data2, opts2);
23673
24593
  }
23674
24594
  if (this.config.opForms?.create === "scoped") throw new OperationNotSupportedError(this.config.key, "create");
23675
- const data = a;
23676
- const opts = b ?? {};
24595
+ const data = this.config.key === "knowledge_base_categories" ? admitKnowledgeBaseCategory(a, true) : a;
24596
+ const supplied = b;
24597
+ const opts = this.config.key === "knowledge_base_categories" ? snapshotMutationOptions(supplied) : supplied ?? {};
23677
24598
  if (opts.dryRun === true) return this.runCreateDryRun(data);
23678
24599
  return this.createGlobal(data, opts);
23679
24600
  }
@@ -23681,22 +24602,30 @@ var GenericResource = class extends BaseResource {
23681
24602
  this.requireOp("update");
23682
24603
  if (isIdentifier(a) && isIdentifier(b)) {
23683
24604
  if (this.config.opForms?.update === "global") throw new OperationNotSupportedError(this.config.key, "update");
23684
- const parentId = a;
23685
- const id2 = b;
23686
- const data2 = this.config.key === "task_predecessors" ? admitTaskPredecessor(c, parentId, false) : c;
23687
- const opts2 = this.config.key === "task_predecessors" ? { ...d } : d ?? {};
24605
+ const parentId = this.config.key === "knowledge_base_articles" ? articleParent(a) : a;
24606
+ const id2 = this.config.key === "knowledge_base_articles" ? parseIdentifier(b, "id") : b;
24607
+ const data2 = this.config.key === "knowledge_base_articles" ? admitArticle(c, parentId, false) : this.config.key === "task_predecessors" ? admitTaskPredecessor(c, parentId, false) : c;
24608
+ let opts2 = d ?? {};
24609
+ if (this.config.key === "knowledge_base_articles") opts2 = snapshotMutationOptions(d);
24610
+ else if (this.config.key === "task_predecessors") opts2 = { ...d };
23688
24611
  if (this.config.key === "task_notes") admitTaskNote(data2, parentId, false);
24612
+ const article = this.config.key === "knowledge_base_articles" ? await guardArticle(this.http, parentId, id2, opts2.maxRetries) : void 0;
24613
+ if (this.config.key === "knowledge_base_articles" && Object.hasOwn(data2, "publish")) assertArticlePublish(data2, await this.getFreshFieldInfo(opts2.maxRetries));
23689
24614
  if (this.config.key === "task_predecessors") await guardTaskPredecessor(this.http, parentId, id2);
23690
- if (opts2.dryRun === true) return this.runUpdateDryRun(id2, data2, opts2, parentId);
23691
- if (this.config.collectionUpdate !== true) {
24615
+ if (opts2.dryRun === true) return this.runUpdateDryRun(id2, data2, opts2, parentId, article);
24616
+ if (article !== void 0) this.staleObjectCheck(article, opts2, "knowledge_base_articles.update");
24617
+ else if (this.config.collectionUpdate !== true) {
23692
24618
  await this.guardStaleBeforeMutation(id2, opts2, `${this.config.key}.update`, parentId);
23693
24619
  }
23694
24620
  return this.updateScopedRaw(parentId, id2, data2, opts2);
23695
24621
  }
23696
24622
  if (this.config.opForms?.update === "scoped") throw new OperationNotSupportedError(this.config.key, "update");
23697
- const id = a;
23698
- const data = b;
23699
- const opts = c ?? {};
24623
+ const category = this.config.key === "knowledge_base_categories";
24624
+ const id = category ? parseIdentifier(a, "id") : a;
24625
+ const supplied = c;
24626
+ const opts = category ? snapshotMutationOptions(supplied) : supplied ?? {};
24627
+ if (category && opts.raw === true) throw new AutotaskConfigError("knowledge_base_categories: raw update is unsupported; a fresh merge is required");
24628
+ const data = category ? admitKnowledgeBaseCategory(b, false, opts.lastModifiedDate) : b;
23700
24629
  if (opts.dryRun === true) return this.runUpdateDryRun(id, data, opts);
23701
24630
  if (this.config.collectionUpdate !== true) {
23702
24631
  await this.guardStaleBeforeMutation(id, opts, `${this.config.key}.update`);
@@ -23707,17 +24636,24 @@ var GenericResource = class extends BaseResource {
23707
24636
  this.requireOp("delete");
23708
24637
  if (isIdentifier(a) && isIdentifier(b)) {
23709
24638
  if (this.config.opForms?.delete === "global") throw new OperationNotSupportedError(this.config.key, "delete");
23710
- const parentId = a;
23711
- const id2 = b;
23712
- const opts2 = this.config.key === "task_predecessors" ? { ...c } : c ?? {};
24639
+ const parentId = this.config.key === "knowledge_base_articles" ? articleParent(a) : a;
24640
+ const id2 = this.config.key === "knowledge_base_articles" ? parseIdentifier(b, "id") : b;
24641
+ let opts2 = c ?? {};
24642
+ if (this.config.key === "knowledge_base_articles") opts2 = snapshotMutationOptions(c);
24643
+ else if (this.config.key === "task_predecessors") opts2 = { ...c };
24644
+ const article = this.config.key === "knowledge_base_articles" ? await guardArticle(this.http, parentId, id2, opts2.maxRetries) : void 0;
23713
24645
  if (this.config.key === "task_predecessors") await guardTaskPredecessor(this.http, parentId, id2);
23714
- if (opts2.dryRun === true) return this.runDeleteDryRun(id2, opts2, parentId);
23715
- await this.guardStaleBeforeMutation(id2, opts2, `${this.config.key}.delete`, parentId);
24646
+ if (opts2.dryRun === true) return this.runDeleteDryRun(id2, opts2, parentId, article);
24647
+ if (article !== void 0) this.staleObjectCheck(article, opts2, "knowledge_base_articles.delete");
24648
+ else await this.guardStaleBeforeMutation(id2, opts2, `${this.config.key}.delete`, parentId);
23716
24649
  return this.config.attachmentGet === true ? this.deleteScopedModel(parentId, id2, opts2) : this.deleteScopedRaw(parentId, id2, opts2);
23717
24650
  }
23718
24651
  if (this.config.opForms?.delete === "scoped") throw new OperationNotSupportedError(this.config.key, "delete");
23719
- const id = a;
23720
- const opts = b ?? {};
24652
+ const category = this.config.key === "knowledge_base_categories";
24653
+ const id = category ? parseIdentifier(a, "id") : a;
24654
+ const supplied = b;
24655
+ const opts = category ? snapshotMutationOptions(supplied) : supplied ?? {};
24656
+ if (category && opts.lastModifiedDate !== void 0) throw new AutotaskConfigError("knowledge_base_categories: no documented stale timestamp is available");
23721
24657
  if (opts.dryRun === true) return this.runDeleteDryRun(id, opts);
23722
24658
  await this.guardStaleBeforeMutation(id, opts, `${this.config.key}.delete`);
23723
24659
  return this.deleteGlobal(id, opts);
@@ -23739,7 +24675,7 @@ var GenericResource = class extends BaseResource {
23739
24675
  /** Get the record with its primary context records in one call (each part a
23740
24676
  * single-record fetch; no sub-lists; absent/dangling references come back null).
23741
24677
  * `names: true` (projects) adds the opt-in name siblings + the top-level `names`
23742
- * section; `maxNameReads` may lower the name-read budget (default 20), never raise it. */
24678
+ * section; `maxNameReads` may lower the name-read budget (default 50), never raise it. */
23743
24679
  async getContext(id, opts = {}) {
23744
24680
  this.requireHelper("getContext");
23745
24681
  const cfg = this.config;
@@ -23912,7 +24848,7 @@ function prepare(query, opts) {
23912
24848
  function companyPieces(terms) {
23913
24849
  return textFragments(terms);
23914
24850
  }
23915
- function score(record, terms, source) {
24851
+ function score2(record, terms, source) {
23916
24852
  const match = scoreTerms(terms, companyTerms(record.companyName ?? ""));
23917
24853
  return match === void 0 ? void 0 : { record, source, ...match };
23918
24854
  }
@@ -23942,7 +24878,7 @@ async function searchFuzzy(resource, query, opts = {}) {
23942
24878
  const validIndex = index?.revision() === revision;
23943
24879
  for (const row of validIndex ? indexed : []) if (typeof row.id === "number") merged.set(row.id, { row, source: "index" });
23944
24880
  for (const row of live) if (typeof row.id === "number") merged.set(row.id, { row: slimCompany(row), source: merged.has(row.id) ? "both" : "live" });
23945
- 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));
24881
+ 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));
23946
24882
  const items = ranked.slice(0, limit);
23947
24883
  if (opts.includeFamily) {
23948
24884
  const records = await addCompanyFamilies(resource.http, items.map((row) => row.record), "companies.searchFuzzy");
@@ -24415,11 +25351,6 @@ function monthsBefore(date, months) {
24415
25351
  return new Date(Date.UTC(y, m - 1 - months, Math.min(d, lastDay))).toISOString().slice(0, 10);
24416
25352
  }
24417
25353
 
24418
- // src/resources/special/_shared/numbers.ts
24419
- function num(v) {
24420
- return typeof v === "number" && Number.isFinite(v) ? v : 0;
24421
- }
24422
-
24423
25354
  // src/resources/special/companies/shared.ts
24424
25355
  var DEFAULT_LIMIT = 25;
24425
25356
  var MAX_LIMIT = 500;
@@ -24996,22 +25927,24 @@ function resolveDispatchArgs(record, argsIn) {
24996
25927
  const names = Object.keys(schema);
24997
25928
  const unknown = Object.keys(byName).filter((k) => !names.includes(k));
24998
25929
  if (unknown.length > 0) bad(`has no input named ${unknown.slice(0, 10).map((k) => `"${k}"`).join(", ")}${unknown.length > 10 ? ` (and ${unknown.length - 10} more)` : ""} (declared: ${declaredArgList(record)})`);
24999
- const missing = names.filter((n) => schema[n].required && byName[n] === void 0);
25930
+ const values = names.map((n) => byName[n]);
25931
+ const missing = names.filter((n, i) => schema[n].required && values[i] === void 0);
25000
25932
  if (missing.length > 0) bad(`requires named input ${missing.map((k) => `"${k}"`).join(", ")} (declared: ${declaredArgList(record)})`);
25001
- const last = names.reduce((at, n, i) => byName[n] === void 0 ? at : i, -1);
25002
- return names.slice(0, last + 1).map((n) => byName[n]);
25933
+ const last = values.findLastIndex((value) => value !== void 0);
25934
+ return values.slice(0, last + 1);
25003
25935
  }
25004
- function validateDispatchArgs(record, argsIn) {
25936
+ function captureDispatchArgs(record, argsIn) {
25005
25937
  const args = argsIn ?? [];
25938
+ const length = args.length;
25006
25939
  const operation = record.id;
25007
25940
  const schema = record.inputSchema ?? {};
25008
25941
  const names = Object.keys(schema);
25009
- if (args.length > names.length) {
25942
+ if (length > names.length) {
25010
25943
  const bagName = names.find((n) => schema[n].properties);
25011
25944
  const surplus = args[names.length];
25012
25945
  const bagHint = bagName && surplus !== null && typeof surplus === "object" && !Array.isArray(surplus) ? ` \u2014 options go inside the single ${bagName} object` : "";
25013
25946
  throw new AutotaskConfigError(
25014
- `invoke: "${operation}" declares ${names.length} positional arg(s) (${declaredArgList(record)}) but ${args.length} were passed \u2014 extra args are refused${bagHint}`,
25947
+ `invoke: "${operation}" declares ${names.length} positional arg(s) (${declaredArgList(record)}) but ${length} were passed \u2014 extra args are refused${bagHint}`,
25015
25948
  {
25016
25949
  operation,
25017
25950
  suggestedAction: `Pass exactly the declared args in order (${declaredArgList(record)}); dryRun/confirm/lastModifiedDate travel through the invoke options, never the args.`
@@ -25019,14 +25952,16 @@ function validateDispatchArgs(record, argsIn) {
25019
25952
  );
25020
25953
  }
25021
25954
  const required = names.filter((n) => schema[n].required);
25022
- if (args.length < required.length) {
25955
+ if (length < required.length) {
25023
25956
  throw new AutotaskConfigError(
25024
- `invoke: "${operation}" requires ${required.length} positional arg(s) (${required.map((n) => `${n}: ${schema[n].type}`).join(", ")}) but only ${args.length} were passed \u2014 declared args: ${declaredArgList(record)}`,
25957
+ `invoke: "${operation}" requires ${required.length} positional arg(s) (${required.map((n) => `${n}: ${schema[n].type}`).join(", ")}) but only ${length} were passed \u2014 declared args: ${declaredArgList(record)}`,
25025
25958
  { operation }
25026
25959
  );
25027
25960
  }
25028
- for (let i = 0; i < args.length; i += 1) {
25961
+ const captured = [];
25962
+ for (let i = 0; i < length; i += 1) {
25029
25963
  const value = args[i];
25964
+ captured.push(value);
25030
25965
  if (value === void 0) continue;
25031
25966
  const name = names[i];
25032
25967
  const spec = schema[name];
@@ -25037,6 +25972,10 @@ function validateDispatchArgs(record, argsIn) {
25037
25972
  );
25038
25973
  }
25039
25974
  }
25975
+ return captured;
25976
+ }
25977
+ function validateDispatchArgs(record, argsIn) {
25978
+ captureDispatchArgs(record, argsIn);
25040
25979
  }
25041
25980
  function foldFlattenedOpts(record, toolArgs) {
25042
25981
  if (!isRecord2(toolArgs)) {
@@ -25457,7 +26396,7 @@ function dateBucketLabel(value, bucket) {
25457
26396
  var queryResourceKeysPromise = null;
25458
26397
  function queryResourceKeys() {
25459
26398
  if (queryResourceKeysPromise === null) {
25460
- queryResourceKeysPromise = chunkJCKYM7FD_cjs.loadCapabilityRecords().then((records) => {
26399
+ queryResourceKeysPromise = chunkYVNGUGG6_cjs.loadCapabilityRecords().then((records) => {
25461
26400
  const s = /* @__PURE__ */ new Set();
25462
26401
  for (const rec of records) if (rec.operation === "query") s.add(rec.resource);
25463
26402
  return s;
@@ -25579,7 +26518,7 @@ function parseTopAndLimit(opts, problems) {
25579
26518
  return { top, limit };
25580
26519
  }
25581
26520
  async function checkFieldNames(resourceKey, conditions, opts, problems) {
25582
- const records = resourceKey === void 0 ? [] : await chunkJCKYM7FD_cjs.loadCapabilityRecords();
26521
+ const records = resourceKey === void 0 ? [] : await chunkYVNGUGG6_cjs.loadCapabilityRecords();
25583
26522
  const record = resourceKey === void 0 ? void 0 : records.find((r) => r.resource === resourceKey && r.operation === "query");
25584
26523
  if (record === void 0) return void 0;
25585
26524
  const strings = (v) => Array.isArray(v) ? v.filter((f) => typeof f === "string" && f.trim() !== "") : [];
@@ -25701,167 +26640,6 @@ async function aggregate(client, operation, filter, opts = {}) {
25701
26640
  return result;
25702
26641
  }
25703
26642
 
25704
- // src/resources/special/_shared/finance.ts
25705
- function budgetExceededError(operation, message, details, suggestedAction) {
25706
- return new AutotaskError(message, { code: "BUDGET_EXCEEDED", category: "policy", operation, details, suggestedAction });
25707
- }
25708
- function makeCallBudget(budget, onExceed) {
25709
- let spent = 0;
25710
- return {
25711
- spend() {
25712
- if (spent >= budget) throw onExceed(spent);
25713
- spent += 1;
25714
- },
25715
- spent: () => spent
25716
- };
25717
- }
25718
- function countingHttp(raw, spend) {
25719
- const http = Object.create(raw);
25720
- http.request = (o) => {
25721
- spend();
25722
- return raw.request(o);
25723
- };
25724
- return http;
25725
- }
25726
- function idChunks(ids2, size) {
25727
- const out = [];
25728
- for (let i = 0; i < ids2.length; i += size) out.push(ids2.slice(i, i + size));
25729
- return out;
25730
- }
25731
- async function fetchIdChunks(http, entityPath, ids2, fields, operation, opts) {
25732
- const chunkSize = opts?.chunkSize ?? 250;
25733
- const out = /* @__PURE__ */ new Map();
25734
- for (const chunk of idChunks(ids2, chunkSize)) {
25735
- opts?.budgetSpend?.();
25736
- const chunkKeys = new Set(chunk.map((id) => String(id)));
25737
- try {
25738
- const req = buildQueryRequest(http.baseUrl, entityPath, {
25739
- filter: [{ field: "id", op: "in", value: chunk }],
25740
- maxRecords: opts?.maxRecords ?? chunkSize,
25741
- includeFields: fields
25742
- });
25743
- const res = await http.request({ ...req, operation });
25744
- const { items: rows } = unwrapItems(res, operation);
25745
- for (const row of rows) {
25746
- const k = String(row["id"]);
25747
- if (!chunkKeys.has(k)) continue;
25748
- out.set(k, row);
25749
- }
25750
- } catch (err) {
25751
- if (opts?.onChunkFault?.(chunk, err) !== true) throw err;
25752
- }
25753
- }
25754
- return out;
25755
- }
25756
- function internalAmount(row, internalKey, localKey) {
25757
- const v = row[internalKey];
25758
- return typeof v === "number" && Number.isFinite(v) ? v : num(row[localKey]);
25759
- }
25760
- function toCents(v) {
25761
- return Math.round(num(v) * 100);
25762
- }
25763
- async function readPicklists(http, entityPath, operation) {
25764
- const res = await http.request({ method: "GET", path: `${entityPath}/entityInformation/fields`, operation });
25765
- const body = typeof res === "object" && res !== null ? res : {};
25766
- const fields = Array.isArray(body["fields"]) ? body["fields"] : [];
25767
- const out = /* @__PURE__ */ new Map();
25768
- for (const f of fields) {
25769
- if (f["isPickList"] !== true || typeof f["name"] !== "string" || !Array.isArray(f["picklistValues"])) continue;
25770
- const values = /* @__PURE__ */ new Map();
25771
- for (const p of f["picklistValues"]) {
25772
- const id = typeof p["value"] === "string" ? Number.parseInt(p["value"], 10) : Number.NaN;
25773
- if (Number.isFinite(id)) values.set(id, String(p["label"] ?? ""));
25774
- }
25775
- out.set(f["name"], values);
25776
- }
25777
- return out;
25778
- }
25779
- function resolveSelector(operation, name, sel, values) {
25780
- const out = /* @__PURE__ */ new Map();
25781
- const misses = [];
25782
- for (const s of sel) {
25783
- const hits = typeof s === "number" ? values.has(s) ? [s] : [] : [...values].filter(([, l]) => l.trim().toLowerCase() === s.trim().toLowerCase()).map(([id]) => id);
25784
- if (hits.length === 0) misses.push(JSON.stringify(s));
25785
- for (const h of hits) out.set(h, values.get(h));
25786
- }
25787
- if (misses.length > 0) throw selectorUnmatched(operation, name, `${misses.join(", ")} matched no live value`, values);
25788
- return out;
25789
- }
25790
- function selectorUnmatched(operation, name, what, values) {
25791
- const live = [...values].map(([id, l]) => `${id} ${l}`).join("; ") || "(the picklist serves no values)";
25792
- return new AutotaskConfigError(`${shortName(operation)}: ${name}: ${what}. Live values (id label): ${live}`, {
25793
- operation,
25794
- suggestedAction: `Pass ${name} as ids or exact labels from the live list.`
25795
- });
25796
- }
25797
- var TENANT_HOURLY_LIMIT = 1e4;
25798
- function tenantHourlyShare(calls) {
25799
- return `${(calls / TENANT_HOURLY_LIMIT * 100).toFixed(2)}% of ${TENANT_HOURLY_LIMIT.toLocaleString("en-US")}/h`;
25800
- }
25801
- var isPosInt = (v) => Number.isSafeInteger(v) && v > 0;
25802
- function checkIdList(name, v, max, problems, opts) {
25803
- const ok = opts?.allowZero ? (x) => x === 0 || isPosInt(x) : isPosInt;
25804
- if (!Array.isArray(v) || v.length === 0 || v.length > max || !v.every(ok)) {
25805
- problems.push(`${name} must be a non-empty array of at most ${max} ${opts?.allowZero ? "non-negative" : "positive"} integer ids`);
25806
- return void 0;
25807
- }
25808
- return [...new Set(v)].sort((a, b) => a - b);
25809
- }
25810
- function checkSelector(name, v, problems) {
25811
- if (v === void 0) return void 0;
25812
- if (!Array.isArray(v) || v.length === 0 || !v.every((x) => isPosInt(x) || typeof x === "string" && x.trim() !== "")) {
25813
- problems.push(`${name} must be a non-empty array of picklist ids or labels`);
25814
- return void 0;
25815
- }
25816
- return v;
25817
- }
25818
- function checkInt(name, v, def, max, problems) {
25819
- if (v === void 0) return def;
25820
- if (!Number.isInteger(v) || v < 1 || v > max) {
25821
- problems.push(`${name} must be an integer 1..${max} (got ${String(v)})`);
25822
- return def;
25823
- }
25824
- return v;
25825
- }
25826
- async function collectRows(res, filter, includeFields, page) {
25827
- const out = [];
25828
- for await (const r of res.query({ filter, includeFields, maxRecords: page, names: false })) out.push(r);
25829
- return out;
25830
- }
25831
- function blindCountError(operation, subject, suggestedAction) {
25832
- return new AutotaskError(`${shortName(operation)}: a gate count came back blind (unknown, not zero); ${subject} cannot be sized`, {
25833
- code: "INVALID_RESPONSE",
25834
- category: "server",
25835
- operation,
25836
- details: { reason: "blind_count" },
25837
- suggestedAction
25838
- });
25839
- }
25840
- function countMismatchError(operation, what, streamed, counted, rows) {
25841
- const rowNote = rows !== void 0 && rows !== streamed ? ` (${rows} rows)` : "";
25842
- 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`, {
25843
- code: "INVALID_RESPONSE",
25844
- category: "server",
25845
- operation,
25846
- details: { reason: "count_mismatch", stream: what, streamed, counted },
25847
- suggestedAction: "Retry the call."
25848
- });
25849
- }
25850
- function compareIds(a, b) {
25851
- for (let i = 0; i < a.length; i++) {
25852
- const x = a[i] ?? null;
25853
- const y = b[i] ?? null;
25854
- if (x === y) continue;
25855
- if (x === null) return -1;
25856
- if (y === null) return 1;
25857
- if (typeof x === "number" && typeof y === "number") return x - y;
25858
- return String(x) < String(y) ? -1 : 1;
25859
- }
25860
- return 0;
25861
- }
25862
- var sortedRecord = (m) => Object.fromEntries([...m].sort((a, b) => a[0] - b[0]).map(([id, l]) => [String(id), l]));
25863
- var shortName = (operation) => operation.split(".").pop() ?? operation;
25864
-
25865
26643
  // src/operations/fetchByIds.ts
25866
26644
  var FETCH_BY_IDS_MAX_ITEMS = 500;
25867
26645
  var FETCH_BY_IDS_CHUNK_SIZE = 250;
@@ -25927,7 +26705,8 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
25927
26705
  continue;
25928
26706
  }
25929
26707
  const rel = RELATIONSHIP_MAP[resourceKey];
25930
- if (rel !== void 0 && rel.parentScoped && resourceKey !== "time_off_requests") {
26708
+ const globalRead = resourceKey === "time_off_requests" || resourceKey === "knowledge_base_articles";
26709
+ if (rel !== void 0 && rel.parentScoped && !globalRead) {
25931
26710
  problems.push(
25932
26711
  `${at}.resource: "${resourceKey}" is a parent-scoped child \u2014 its get needs (parentId, id); ${opName} takes single numeric ids of TOP-LEVEL records (scoped reads: client.${camelKey(resourceKey)}.get(parentId, id))`
25933
26712
  );
@@ -25935,8 +26714,9 @@ function validateFetchManyItems(items, cap, opName = "fetchByIds", capRef = `FET
25935
26714
  }
25936
26715
  try {
25937
26716
  const id = parseIdentifier(item.id, `${at}.id`);
25938
- if (isAuditLogResource(resourceKey) && !isAuditDecimalId(String(id))) {
25939
- problems.push(`${at}.id: audit log ID must be a non-negative signed 64-bit integer`);
26717
+ const audit = isAuditLogResource(resourceKey);
26718
+ if ((audit || isKnowledgeBaseRootResource(resourceKey)) && !isAuditDecimalId(String(id))) {
26719
+ problems.push(`${at}.id: ${audit ? "audit log" : "Knowledge Base record"} ID must be a non-negative signed 64-bit integer`);
25940
26720
  }
25941
26721
  } catch {
25942
26722
  if (typeof item.id === "string") {
@@ -26230,7 +27010,7 @@ async function uiLink(client, input) {
26230
27010
  var indexPromise = null;
26231
27011
  function operationIndex() {
26232
27012
  if (indexPromise === null) {
26233
- indexPromise = chunkJCKYM7FD_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
27013
+ indexPromise = chunkYVNGUGG6_cjs.loadCapabilityRecords().then((records) => new Map(records.map((r) => [r.id, r])));
26234
27014
  }
26235
27015
  return indexPromise;
26236
27016
  }
@@ -28566,16 +29346,16 @@ function latchingHttp(raw, spend) {
28566
29346
  }
28567
29347
  };
28568
29348
  observeRecordReadFailures(http, latch);
28569
- const fail2 = (err) => {
29349
+ const fail3 = (err) => {
28570
29350
  latch(err);
28571
29351
  throw err;
28572
29352
  };
28573
29353
  http.request = (o) => {
28574
29354
  if (fatal) throw fatal;
28575
29355
  try {
28576
- return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail2);
29356
+ return counted.request({ ...o, signal: o.signal ?? signal }).catch(fail3);
28577
29357
  } catch (err) {
28578
- return fail2(err);
29358
+ return fail3(err);
28579
29359
  }
28580
29360
  };
28581
29361
  return { http, fatal: () => fatal, signal };
@@ -30310,14 +31090,16 @@ var PROPAGATE_CODES = /* @__PURE__ */ new Set([
30310
31090
  "RATE_LIMITED",
30311
31091
  "RATE_LIMITED_COOLDOWN"
30312
31092
  ]);
30313
- function hasIdScope(filter) {
30314
- if (Array.isArray(filter)) return filter.some(hasIdScope);
31093
+ function hasIdScope(filter, resourceKey) {
31094
+ if (Array.isArray(filter)) return filter.some((condition) => hasIdScope(condition, resourceKey));
30315
31095
  if (filter === null || typeof filter !== "object") return false;
30316
31096
  const n = filter;
30317
31097
  const op = typeof n.op === "string" ? n.op.toLowerCase() : "";
30318
- if (Array.isArray(n.items)) return op === "and" && n.items.some(hasIdScope);
30319
- if (Array.isArray(n.filter)) return hasIdScope(n.filter);
30320
- if (typeof n.field !== "string" || !(n.field === "id" || /ID$/.test(n.field))) return false;
31098
+ if (Array.isArray(n.items)) return op === "and" && hasIdScope(n.items, resourceKey);
31099
+ if (Array.isArray(n.filter)) return hasIdScope(n.filter, resourceKey);
31100
+ if (n.udf === true || typeof n.field !== "string") return false;
31101
+ const field = resourceKey === void 0 ? n.field : normalizeOwnField(resourceKey, n.field);
31102
+ if (!(field === "id" || /ID$/.test(field))) return false;
30321
31103
  const real = (v) => v !== void 0 && v !== null && v !== "";
30322
31104
  const list = Array.isArray(n.value) ? n.value : typeof n.value === "string" ? n.value.split(",").map((t) => t.trim()) : [];
30323
31105
  return op === "eq" && real(n.value) || op === "in" && list.some(real);
@@ -30330,7 +31112,7 @@ async function guardUnscopedQueryWalk(holder, operation, bag) {
30330
31112
  const maxRows = typeof walk?.maxRows === "number" ? walk.maxRows : void 0;
30331
31113
  const effectiveLimit = typeof limit === "number" ? limit : BOUNDED_QUERY_DEFAULT_LIMIT;
30332
31114
  const walked = maxRows ?? (typeof latest === "number" ? Math.max(effectiveLimit, latest) : effectiveLimit);
30333
- if (walked <= UNSCOPED_WALK_THRESHOLD || hasIdScope(filter)) return {};
31115
+ if (walked <= UNSCOPED_WALK_THRESHOLD || hasIdScope(filter, operation.split(".", 1)[0])) return {};
30334
31116
  let conditions;
30335
31117
  try {
30336
31118
  conditions = normalizedConditions(filter);
@@ -30371,6 +31153,11 @@ function bufferResult(buf) {
30371
31153
  note: `Body exceeds the ${INVOKE_MAX_INLINE_BYTES}-byte inline limit and was not returned; call the resource's download method directly.`
30372
31154
  };
30373
31155
  }
31156
+ var PUBLIC_INVOKE_OPTION_KEYS = INVOKE_OPTION_KEYS.filter((key) => key !== "mode");
31157
+ function snapshotInvokeOptions(options, mode) {
31158
+ const captured = isRecord2(options) ? snapshotFields(options, PUBLIC_INVOKE_OPTION_KEYS) : { ...options };
31159
+ return { ...captured, mode };
31160
+ }
30374
31161
  async function resolveRecord(operation) {
30375
31162
  const record = (await operationIndex()).get(operation);
30376
31163
  if (record === void 0) {
@@ -30581,7 +31368,12 @@ var PRE_REQUEST_VALIDATORS = [
30581
31368
  session.guard();
30582
31369
  },
30583
31370
  (c) => requireReadBack(c.record, c.operation, c.opts),
30584
- (c) => validateDispatchArgs(c.record, c.args),
31371
+ (c) => {
31372
+ c.args = captureDispatchArgs(c.record, c.args);
31373
+ const [bag, ...remaining] = c.args;
31374
+ if (!c.boundedQuery && !c.countedQuery || !isRecord2(bag)) return;
31375
+ c.args = [snapshotQueryBag(bag, PARAMS_BAG_KEYS[c.record.operation] ?? []), ...remaining];
31376
+ },
30585
31377
  (c) => validateParamsBag(c.record, c.args),
30586
31378
  (c) => validateFreshSpelling(c.record, c.args),
30587
31379
  (c) => {
@@ -30598,12 +31390,13 @@ async function runPreRequestPass(ctx) {
30598
31390
  }
30599
31391
  async function prepareInvocation(client, operation, argsIn, opts, streaming = false) {
30600
31392
  const record = await resolveRecord(operation);
30601
- const args = resolveDispatchArgs(record, argsIn);
31393
+ const resolvedArgs = resolveDispatchArgs(record, argsIn);
30602
31394
  const boundedQuery = record.kind === "primitive" && record.operation === "query";
30603
31395
  const countedQuery = record.kind === "primitive" && record.operation === "count";
30604
31396
  const holder = resolveHolder(client, record, operation);
30605
- const context = { record, operation, args, opts, client, holder, boundedQuery, countedQuery, streaming };
31397
+ const context = { record, operation, args: resolvedArgs, opts, client, holder, boundedQuery, countedQuery, streaming };
30606
31398
  await runPreRequestPass(context);
31399
+ const { args } = context;
30607
31400
  const labelQuery = boundedQuery && readNamesOpt(client, args[0]?.["names"], `invoke: "${record.id}" params bag`);
30608
31401
  const methodName = boundedQuery ? "queryBounded" : record.operation;
30609
31402
  const method = streaming ? context.pageSession?.consume : holder[methodName];
@@ -30636,14 +31429,14 @@ async function invokeMode(client, operation, argsIn = [], opts = {}) {
30636
31429
  return scopeNote !== void 0 && finished !== null && typeof finished === "object" ? { ...finished, scopeNote } : finished;
30637
31430
  }
30638
31431
  async function invoke(client, operation, args = [], opts = {}) {
30639
- return invokeMode(client, operation, args, { ...opts, mode: void 0 });
31432
+ return invokeMode(client, operation, args, snapshotInvokeOptions(opts));
30640
31433
  }
30641
31434
  async function invokeRead(client, operation, args = [], opts = {}) {
30642
- return invokeMode(client, operation, args, { ...opts, mode: "read" });
31435
+ return invokeMode(client, operation, args, snapshotInvokeOptions(opts, "read"));
30643
31436
  }
30644
31437
  async function invokeReadPages(client, operation, args, onPage, opts = {}) {
30645
31438
  if (typeof onPage !== "function") throw new AutotaskConfigError("invokeReadPages: onPage must be a function", { operation });
30646
- const prepared = await prepareInvocation(client, operation, args, { ...opts, mode: "read" }, true);
31439
+ const prepared = await prepareInvocation(client, operation, args, snapshotInvokeOptions(opts, "read"), true);
30647
31440
  prepared.pageSession.guard();
30648
31441
  const consume = prepared.method;
30649
31442
  const result = await consume.call(prepared.holder, prepared.callArgs[0], onPage);
@@ -30651,10 +31444,10 @@ async function invokeReadPages(client, operation, args, onPage, opts = {}) {
30651
31444
  return prepared.scopeNote === void 0 ? result : { ...result, scopeNote: prepared.scopeNote };
30652
31445
  }
30653
31446
  async function invokeWrite(client, operation, args = [], opts = {}) {
30654
- return invokeMode(client, operation, args, { ...opts, mode: "write" });
31447
+ return invokeMode(client, operation, args, snapshotInvokeOptions(opts, "write"));
30655
31448
  }
30656
31449
  async function invokeDelete(client, operation, args = [], opts = {}) {
30657
- return invokeMode(client, operation, args, { ...opts, mode: "delete" });
31450
+ return invokeMode(client, operation, args, snapshotInvokeOptions(opts, "delete"));
30658
31451
  }
30659
31452
 
30660
31453
  // src/resources/special/_shared/compositeParts.ts