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