node-autotask 0.69.1 → 0.71.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 (43) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/MCP_TOOL_CATALOG.json +369 -9
  3. package/README.md +7 -1
  4. package/capabilities.json +1697 -392
  5. package/dist/capabilities-data.js +1696 -391
  6. package/dist/capabilities.cjs +4 -4
  7. package/dist/capabilities.js +1 -1
  8. package/dist/{chunk-WFVLF7EW.cjs → chunk-4DSLRDIF.cjs} +33 -30
  9. package/dist/{chunk-FK37JXSJ.js → chunk-4OR3XBIP.js} +699 -168
  10. package/dist/{chunk-MMGO3SFL.js → chunk-5COLIVBE.js} +2 -2
  11. package/dist/{chunk-KAZE4WC7.cjs → chunk-JLCHKCEB.cjs} +3 -3
  12. package/dist/{chunk-SCFB5MF3.js → chunk-LKJA57CH.js} +3 -3
  13. package/dist/{chunk-EWXRFHPP.cjs → chunk-QJ327YI6.cjs} +177 -177
  14. package/dist/{chunk-CLHDTYWO.cjs → chunk-QQFF7X67.cjs} +704 -172
  15. package/dist/{chunk-64BMSXWT.js → chunk-YKQ2KNQO.js} +5 -2
  16. package/dist/{index-BT_0tTPS.d.cts → index-CAXT5ZKT.d.cts} +14 -4
  17. package/dist/{index-COQEG55Q.d.cts → index-CM_SRgtH.d.cts} +209 -1
  18. package/dist/{index-COQEG55Q.d.ts → index-CM_SRgtH.d.ts} +209 -1
  19. package/dist/{index-Coe7LFLY.d.ts → index-lGpxr4gY.d.ts} +14 -4
  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 +54 -50
  25. package/dist/operations/index.d.cts +25 -7
  26. package/dist/operations/index.d.ts +25 -7
  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 +108 -2
  39. package/docs/N8N-ADAPTER.md +1 -1
  40. package/docs/RELEASING.md +11 -3
  41. package/docs/performance-caching.md +92 -0
  42. package/docs/performance-reads.md +9 -1
  43. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { loadCapabilityRecords } from './chunk-SCFB5MF3.js';
1
+ import { loadCapabilityRecords } from './chunk-LKJA57CH.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';
@@ -616,6 +616,27 @@ function isKnownZone(zone) {
616
616
  return typeof zone === "string" && ZONES.includes(zone);
617
617
  }
618
618
 
619
+ // src/metadata-projection.ts
620
+ var METADATA_PROJECTION = /* @__PURE__ */ Symbol.for("node-autotask.metadata-projection.v1");
621
+ function projectMetadata(value, projector) {
622
+ return structuredClone(projector(value));
623
+ }
624
+ async function readMetadataProjection(holder, kind, projector, fallbackReader) {
625
+ const hook = holder !== null && (typeof holder === "object" || typeof holder === "function") ? holder[METADATA_PROJECTION] : void 0;
626
+ const owned = hook?.call(holder, kind, projector);
627
+ owned?.guard();
628
+ if (owned?.projected !== void 0) {
629
+ const value2 = await owned.projected;
630
+ owned.guard();
631
+ return value2;
632
+ }
633
+ const raw = await fallbackReader();
634
+ owned?.guard();
635
+ const value = projector(raw);
636
+ owned?.guard();
637
+ return value;
638
+ }
639
+
619
640
  // src/cache.ts
620
641
  var READ_CACHE_MAX_ENTRIES = 4096;
621
642
  var REFERENCE_TTL_MS = 36e5;
@@ -628,6 +649,7 @@ function readTtlFor(key, ttlMs) {
628
649
  const entity = key.split("\0")[0].split("/").at(-2);
629
650
  return entity !== void 0 && REFERENCE_ENTITIES.includes(entity) ? Math.max(ttlMs, REFERENCE_TTL_MS) : ttlMs;
630
651
  }
652
+ var MAX_ENTRY_PROJECTIONS = 8;
631
653
  var TtlCache = class {
632
654
  ttlMs;
633
655
  maxEntries;
@@ -648,15 +670,38 @@ var TtlCache = class {
648
670
  this.maxEntries = maxEntries;
649
671
  this.ttlFor = options.ttlFor ?? (() => ttlMs);
650
672
  }
651
- /** The live value (a copy), or `undefined` when absent or expired. */
652
- get(key) {
673
+ liveEntry(key) {
653
674
  const entry = this.store.get(key);
654
675
  if (entry === void 0) return void 0;
655
676
  if (entry.expiresAt <= Date.now()) {
656
677
  this.store.delete(key);
657
678
  return void 0;
658
679
  }
659
- return structuredClone(entry.value);
680
+ return entry;
681
+ }
682
+ /** The live value (a copy), or `undefined` when absent or expired. */
683
+ get(key) {
684
+ const entry = this.liveEntry(key);
685
+ return entry === void 0 ? void 0 : structuredClone(entry.value);
686
+ }
687
+ projectEntry(key, entry, projector) {
688
+ if (entry.projections?.has(projector)) return structuredClone(entry.projections.get(projector));
689
+ const value = projectMetadata(structuredClone(entry.value), projector);
690
+ if (this.store.get(key) === entry && entry.expiresAt > Date.now()) {
691
+ const projections = entry.projections ??= /* @__PURE__ */ new Map();
692
+ if (projections.size >= MAX_ENTRY_PROJECTIONS) {
693
+ const oldest = projections.keys().next();
694
+ if (!oldest.done) projections.delete(oldest.value);
695
+ }
696
+ projections.set(projector, value);
697
+ return structuredClone(value);
698
+ }
699
+ return value;
700
+ }
701
+ /** Clone a live derived value without cloning the full metadata on each hit. @internal */
702
+ getProjected(key, projector) {
703
+ const entry = this.liveEntry(key);
704
+ return entry === void 0 ? void 0 : this.projectEntry(key, entry, projector);
660
705
  }
661
706
  /**
662
707
  * Load one record once for concurrent callers. Each subscriber owns its
@@ -667,12 +712,23 @@ var TtlCache = class {
667
712
  * `shouldStore` controls retention, never the result returned to subscribers.
668
713
  * @internal
669
714
  */
670
- async load(key, loader, opts) {
715
+ load(key, loader, opts) {
716
+ return this.loadValue(key, loader, opts);
717
+ }
718
+ /** Projected and raw subscribers share the same raw flight and retention policy. @internal */
719
+ loadProjected(key, loader, projector, opts) {
720
+ return this.loadValue(key, loader, opts, projector);
721
+ }
722
+ async loadValue(key, loader, opts, projector) {
671
723
  const { signal } = opts;
672
724
  if (signal?.aborted) throw opts.abortError();
673
725
  if (!opts.fresh) {
674
- const hit = this.get(key);
675
- if (hit !== void 0) return hit;
726
+ const entry = this.liveEntry(key);
727
+ if (entry !== void 0 && entry.value !== void 0) {
728
+ const hit = projector === void 0 ? structuredClone(entry.value) : this.projectEntry(key, entry, projector);
729
+ if (signal?.aborted) throw opts.abortError();
730
+ return hit;
731
+ }
676
732
  }
677
733
  let flight = opts.fresh ? void 0 : this.loads.get(key);
678
734
  let start;
@@ -690,7 +746,10 @@ var TtlCache = class {
690
746
  }
691
747
  };
692
748
  }).then((value) => {
693
- if (this.loads.get(key) === created && !controller.signal.aborted && (opts.shouldStore?.(value) ?? true)) this.set(key, value, epoch);
749
+ if (this.loads.get(key) === created && !controller.signal.aborted) {
750
+ const retain = opts.shouldStore?.(value) ?? true;
751
+ if (retain && this.loads.get(key) === created && !controller.signal.aborted) created.entry = this.storeValue(key, value, epoch);
752
+ }
694
753
  return value;
695
754
  });
696
755
  const settled = () => {
@@ -724,7 +783,11 @@ var TtlCache = class {
724
783
  (value) => {
725
784
  if (leave()) {
726
785
  try {
727
- resolve(structuredClone(value));
786
+ if (signal?.aborted) throw opts.abortError();
787
+ const entry = shared.entry;
788
+ const selected = projector === void 0 ? structuredClone(value) : entry !== void 0 && this.liveEntry(key) === entry ? this.projectEntry(key, entry, projector) : projectMetadata(structuredClone(value), projector);
789
+ if (signal?.aborted) throw opts.abortError();
790
+ resolve(selected);
728
791
  } catch (error) {
729
792
  reject(error);
730
793
  }
@@ -741,14 +804,19 @@ var TtlCache = class {
741
804
  /** Store `value` under `key`. `epoch` is the value the caller read BEFORE its
742
805
  * wire request: a read that straddled a `clear()` (a write) is dropped. */
743
806
  set(key, value, epoch = this.epochCounter) {
744
- if (epoch !== this.epochCounter) return;
807
+ this.storeValue(key, value, epoch);
808
+ }
809
+ storeValue(key, value, epoch) {
810
+ if (epoch !== this.epochCounter) return void 0;
745
811
  if (!this.store.has(key) && this.store.size >= this.maxEntries && this.purgeExpired() === 0) {
746
812
  const oldest = this.store.keys().next();
747
813
  if (!oldest.done) this.store.delete(oldest.value);
748
814
  }
749
815
  const now = Date.now();
750
816
  this.store.delete(key);
751
- this.store.set(key, { value: structuredClone(value), storedAt: now, expiresAt: now + this.ttlFor(key) });
817
+ const entry = { value: structuredClone(value), storedAt: now, expiresAt: now + this.ttlFor(key) };
818
+ this.store.set(key, entry);
819
+ return entry;
752
820
  }
753
821
  /** `{ hit, age }` without consuming or cloning the entry (age in ms since stored). */
754
822
  peek(key) {
@@ -1732,6 +1800,12 @@ function isAbortLike(err) {
1732
1800
  return typeof err === "object" && err !== null && "name" in err && err.name === "AbortError";
1733
1801
  }
1734
1802
 
1803
+ // src/read-scope.ts
1804
+ var CAPTURE_READ_GUARD = /* @__PURE__ */ Symbol.for("node-autotask.capture-read-guard.v1");
1805
+ function captureReadGuard(http, operation) {
1806
+ return http[CAPTURE_READ_GUARD](operation);
1807
+ }
1808
+
1735
1809
  // src/auth.ts
1736
1810
  var AUTH_HEADERS = {
1737
1811
  integrationCode: "ApiIntegrationCode",
@@ -2321,6 +2395,22 @@ var RELATIONSHIP_MAP = {
2321
2395
  "delete": true
2322
2396
  }
2323
2397
  },
2398
+ {
2399
+ "resource": "company_attachments",
2400
+ "apiEntity": "CompanyAttachment",
2401
+ "parentField": "companyID",
2402
+ "parentSegment": "Attachments",
2403
+ "tier": "extended",
2404
+ "workflowResource": false,
2405
+ "specialOps": [],
2406
+ "searchCovers": null,
2407
+ "scopedOps": {
2408
+ "create": true,
2409
+ "query": true,
2410
+ "update": false,
2411
+ "delete": true
2412
+ }
2413
+ },
2324
2414
  {
2325
2415
  "resource": "company_locations",
2326
2416
  "apiEntity": "CompanyLocation",
@@ -2602,7 +2692,24 @@ var RELATIONSHIP_MAP = {
2602
2692
  "segment": "Notes",
2603
2693
  "field": "companyID"
2604
2694
  },
2605
- "children": [],
2695
+ "children": [
2696
+ {
2697
+ "resource": "company_note_attachments",
2698
+ "apiEntity": "CompanyNoteAttachment",
2699
+ "parentField": "companyNoteID",
2700
+ "parentSegment": "Attachments",
2701
+ "tier": "extended",
2702
+ "workflowResource": false,
2703
+ "specialOps": [],
2704
+ "searchCovers": null,
2705
+ "scopedOps": {
2706
+ "create": true,
2707
+ "query": true,
2708
+ "update": false,
2709
+ "delete": true
2710
+ }
2711
+ }
2712
+ ],
2606
2713
  "naturalKeys": {
2607
2714
  "hasSearch": true,
2608
2715
  "searchCovers": "name only (contains)",
@@ -2889,7 +2996,7 @@ var RELATIONSHIP_MAP = {
2889
2996
  "parent": {
2890
2997
  "resource": "configuration_items",
2891
2998
  "segment": "DnsRecords",
2892
- "field": "configurationItemID"
2999
+ "field": "installedProductID"
2893
3000
  },
2894
3001
  "children": [],
2895
3002
  "naturalKeys": {
@@ -3159,7 +3266,7 @@ var RELATIONSHIP_MAP = {
3159
3266
  {
3160
3267
  "resource": "configuration_item_dns_records",
3161
3268
  "apiEntity": "ConfigurationItemDnsRecord",
3162
- "parentField": "configurationItemID",
3269
+ "parentField": "installedProductID",
3163
3270
  "parentSegment": "DnsRecords",
3164
3271
  "tier": "extended",
3165
3272
  "workflowResource": false,
@@ -9426,6 +9533,137 @@ var RELATIONSHIP_MAP = {
9426
9533
  "zoneFacts": null,
9427
9534
  "deleteBoundary": null,
9428
9535
  "markerField": null
9536
+ },
9537
+ "attachment_info": {
9538
+ "resource": "attachment_info",
9539
+ "apiEntity": "AttachmentInfo",
9540
+ "kind": "entity",
9541
+ "path": "AttachmentInfo",
9542
+ "parentScoped": false,
9543
+ "tier": "extended",
9544
+ "workflowResource": false,
9545
+ "group": "A",
9546
+ "parent": null,
9547
+ "children": [],
9548
+ "naturalKeys": {
9549
+ "hasSearch": false,
9550
+ "searchCovers": null,
9551
+ "findBy": []
9552
+ },
9553
+ "blindSurfaces": null,
9554
+ "zoneFacts": null,
9555
+ "deleteBoundary": null,
9556
+ "markerField": null
9557
+ },
9558
+ "company_attachments": {
9559
+ "resource": "company_attachments",
9560
+ "apiEntity": "CompanyAttachment",
9561
+ "kind": "entity",
9562
+ "path": "CompanyAttachments",
9563
+ "parentScoped": true,
9564
+ "tier": "extended",
9565
+ "workflowResource": false,
9566
+ "group": "A",
9567
+ "parent": {
9568
+ "resource": "companies",
9569
+ "segment": "Attachments",
9570
+ "field": "companyID"
9571
+ },
9572
+ "children": [],
9573
+ "naturalKeys": {
9574
+ "hasSearch": false,
9575
+ "searchCovers": null,
9576
+ "findBy": []
9577
+ },
9578
+ "blindSurfaces": null,
9579
+ "zoneFacts": {
9580
+ "createGuidance": {
9581
+ "createOp": "company_attachments.create",
9582
+ "parentScoped": true,
9583
+ "liveProvenPrefix": [],
9584
+ "unproven": true,
9585
+ "blocker": {
9586
+ "kind": "unknown",
9587
+ "message": "Attachment creation is documented; valid input remains subject to API-user permissions and vendor validation.",
9588
+ "remedy": "Read the current field and picklist metadata, supply the named parent id, and preview the attachment before applying."
9589
+ },
9590
+ "requiresByValue": [
9591
+ {
9592
+ "field": "attachmentType",
9593
+ "value": "FILE_ATTACHMENT",
9594
+ "requires": {
9595
+ "allOf": [
9596
+ "data"
9597
+ ]
9598
+ }
9599
+ }
9600
+ ],
9601
+ "vendorEvidence": [
9602
+ "Specification: POST /V1.0/Companies/{parentId}/Attachments returns OperationResultModel. Official attachment guidance requires base64 data for FILE_ATTACHMENT. No live create was performed."
9603
+ ],
9604
+ "deleteBoundary": {
9605
+ "available": true,
9606
+ "note": null
9607
+ }
9608
+ }
9609
+ },
9610
+ "deleteBoundary": null,
9611
+ "markerField": null
9612
+ },
9613
+ "company_note_attachments": {
9614
+ "resource": "company_note_attachments",
9615
+ "apiEntity": "CompanyNoteAttachment",
9616
+ "kind": "entity",
9617
+ "path": "CompanyNoteAttachments",
9618
+ "parentScoped": true,
9619
+ "tier": "extended",
9620
+ "workflowResource": false,
9621
+ "group": "A",
9622
+ "parent": {
9623
+ "resource": "company_notes",
9624
+ "segment": "Attachments",
9625
+ "field": "companyNoteID"
9626
+ },
9627
+ "children": [],
9628
+ "naturalKeys": {
9629
+ "hasSearch": false,
9630
+ "searchCovers": null,
9631
+ "findBy": []
9632
+ },
9633
+ "blindSurfaces": null,
9634
+ "zoneFacts": {
9635
+ "createGuidance": {
9636
+ "createOp": "company_note_attachments.create",
9637
+ "parentScoped": true,
9638
+ "liveProvenPrefix": [],
9639
+ "unproven": true,
9640
+ "blocker": {
9641
+ "kind": "unknown",
9642
+ "message": "Attachment creation is documented; valid input remains subject to API-user permissions and vendor validation.",
9643
+ "remedy": "Read the current field and picklist metadata, supply the named parent id, and preview the attachment before applying."
9644
+ },
9645
+ "requiresByValue": [
9646
+ {
9647
+ "field": "attachmentType",
9648
+ "value": "FILE_ATTACHMENT",
9649
+ "requires": {
9650
+ "allOf": [
9651
+ "data"
9652
+ ]
9653
+ }
9654
+ }
9655
+ ],
9656
+ "vendorEvidence": [
9657
+ "Specification: POST /V1.0/CompanyNotes/{parentId}/Attachments returns OperationResultModel. Official attachment guidance requires base64 data for FILE_ATTACHMENT. No live create was performed."
9658
+ ],
9659
+ "deleteBoundary": {
9660
+ "available": true,
9661
+ "note": null
9662
+ }
9663
+ }
9664
+ },
9665
+ "deleteBoundary": null,
9666
+ "markerField": null
9429
9667
  }
9430
9668
  };
9431
9669
  var BLIND_SURFACE_STAMPS = {
@@ -11133,6 +11371,36 @@ var CREATE_GUIDANCE = {
11133
11371
  "note": null
11134
11372
  }
11135
11373
  },
11374
+ {
11375
+ "resource": "company_attachments",
11376
+ "createOp": "company_attachments.create",
11377
+ "parentScoped": true,
11378
+ "liveProvenPrefix": [],
11379
+ "unproven": true,
11380
+ "blocker": {
11381
+ "kind": "unknown",
11382
+ "message": "Attachment creation is documented; valid input remains subject to API-user permissions and vendor validation.",
11383
+ "remedy": "Read the current field and picklist metadata, supply the named parent id, and preview the attachment before applying."
11384
+ },
11385
+ "vendorEvidence": [
11386
+ "Specification: POST /V1.0/Companies/{parentId}/Attachments returns OperationResultModel. Official attachment guidance requires base64 data for FILE_ATTACHMENT. No live create was performed."
11387
+ ],
11388
+ "deleteBoundary": {
11389
+ "available": true,
11390
+ "note": null
11391
+ },
11392
+ "requiresByValue": [
11393
+ {
11394
+ "field": "attachmentType",
11395
+ "value": "FILE_ATTACHMENT",
11396
+ "requires": {
11397
+ "allOf": [
11398
+ "data"
11399
+ ]
11400
+ }
11401
+ }
11402
+ ]
11403
+ },
11136
11404
  {
11137
11405
  "resource": "company_locations",
11138
11406
  "createOp": "company_locations.create",
@@ -11150,6 +11418,36 @@ var CREATE_GUIDANCE = {
11150
11418
  "note": null
11151
11419
  }
11152
11420
  },
11421
+ {
11422
+ "resource": "company_note_attachments",
11423
+ "createOp": "company_note_attachments.create",
11424
+ "parentScoped": true,
11425
+ "liveProvenPrefix": [],
11426
+ "unproven": true,
11427
+ "blocker": {
11428
+ "kind": "unknown",
11429
+ "message": "Attachment creation is documented; valid input remains subject to API-user permissions and vendor validation.",
11430
+ "remedy": "Read the current field and picklist metadata, supply the named parent id, and preview the attachment before applying."
11431
+ },
11432
+ "vendorEvidence": [
11433
+ "Specification: POST /V1.0/CompanyNotes/{parentId}/Attachments returns OperationResultModel. Official attachment guidance requires base64 data for FILE_ATTACHMENT. No live create was performed."
11434
+ ],
11435
+ "deleteBoundary": {
11436
+ "available": true,
11437
+ "note": null
11438
+ },
11439
+ "requiresByValue": [
11440
+ {
11441
+ "field": "attachmentType",
11442
+ "value": "FILE_ATTACHMENT",
11443
+ "requires": {
11444
+ "allOf": [
11445
+ "data"
11446
+ ]
11447
+ }
11448
+ }
11449
+ ]
11450
+ },
11153
11451
  {
11154
11452
  "resource": "company_notes",
11155
11453
  "createOp": "company_notes.create",
@@ -13456,7 +13754,7 @@ var CREATE_GUIDANCE = {
13456
13754
  }
13457
13755
  ],
13458
13756
  "counts": {
13459
- "total": 99,
13757
+ "total": 101,
13460
13758
  "byKind": {
13461
13759
  "ok": 41,
13462
13760
  "blind-reference": 16,
@@ -13466,7 +13764,7 @@ var CREATE_GUIDANCE = {
13466
13764
  "resource-role-pair": 2,
13467
13765
  "delete-absent": 0,
13468
13766
  "non-mutable": 0,
13469
- "unknown": 23
13767
+ "unknown": 25
13470
13768
  }
13471
13769
  }
13472
13770
  };
@@ -14183,6 +14481,15 @@ var UNTRUSTED_FIELDS_BY_RESOURCE = {
14183
14481
  "user_defined_field_list_items": [
14184
14482
  "valueForDisplay",
14185
14483
  "valueForExport"
14484
+ ],
14485
+ "attachment_info": [
14486
+ "title"
14487
+ ],
14488
+ "company_attachments": [
14489
+ "title"
14490
+ ],
14491
+ "company_note_attachments": [
14492
+ "title"
14186
14493
  ]
14187
14494
  };
14188
14495
 
@@ -14791,6 +15098,13 @@ async function discoverZoneBase(userName, maxResponseBytes, signal, ctx) {
14791
15098
  var META_TRIO_VERBS = /* @__PURE__ */ new Set(["getEntityInfo", "getFieldInfo", "getUdfInfo"]);
14792
15099
  var RETRY = { done: false };
14793
15100
  var HttpClient = class {
15101
+ /** Retain this build's caller scope without sharing ambient storage. @internal */
15102
+ [CAPTURE_READ_GUARD](operation) {
15103
+ const signal = ambientCallerSignal();
15104
+ return () => {
15105
+ if (signal?.aborted) throw new AutotaskAbortError("Read aborted by the caller", { operation });
15106
+ };
15107
+ }
14794
15108
  /**
14795
15109
  * The LIVE base URL (issue #43): the construction-time value until a zone
14796
15110
  * re-point happens, then the tenant's newly resolved zone base. Reads are
@@ -15842,6 +16156,133 @@ var WORKFLOW_RESOURCES = [
15842
16156
  "projects"
15843
16157
  ];
15844
16158
 
16159
+ // src/metadata-views.ts
16160
+ function liveFieldNamesView(rows) {
16161
+ if (!Array.isArray(rows)) return null;
16162
+ const names = [];
16163
+ for (const row of rows) if (typeof row.name === "string") names.push(row.name);
16164
+ return names.length === 0 ? null : { names, known: new Set(names) };
16165
+ }
16166
+ function projectFieldRow(raw, labels = false, udf = false) {
16167
+ const r = typeof raw === "object" && raw !== null ? raw : {};
16168
+ const name = typeof r.name === "string" ? r.name : "";
16169
+ const type = typeof r.dataType === "string" ? r.dataType : typeof r.type === "string" ? r.type : "";
16170
+ const values = labels && r.isPickList === true && Array.isArray(r.picklistValues) && r.picklistValues.length > 0 ? r.picklistValues : void 0;
16171
+ const referenceEntityType = typeof r.referenceEntityType === "string" ? r.referenceEntityType : "";
16172
+ return {
16173
+ name,
16174
+ ...typeof r.label === "string" && r.label !== "" ? { label: r.label } : {},
16175
+ type,
16176
+ isRequired: r.isRequired === true,
16177
+ isReadOnly: r.isReadOnly === true,
16178
+ // Issue #219 N7: a UDF row never serves the vendor's isQueryable (it is
16179
+ // true for UDFs while a plain filter on a UDF name is refused); it serves
16180
+ // the marker the filter actually needs.
16181
+ ...udf ? { filterable: "udf-marker" } : { isQueryable: r.isQueryable === true },
16182
+ isPickList: r.isPickList === true,
16183
+ ...isObjectOrArrayType(type) ? { writeShape: "replace-all" } : {},
16184
+ maxLength: typeof r.length === "number" ? r.length : null,
16185
+ referenceEntityType,
16186
+ ...values !== void 0 ? { picklistValues: values } : {}
16187
+ };
16188
+ }
16189
+ function isObjectOrArrayType(type) {
16190
+ const t = type.trim().toLowerCase();
16191
+ return t === "object" || t === "array" || t === "collection" || t.endsWith("[]");
16192
+ }
16193
+ function exposesPicklistValues(raw) {
16194
+ const r = typeof raw === "object" && raw !== null ? raw : {};
16195
+ return Array.isArray(r.picklistValues) && r.picklistValues.length > 0;
16196
+ }
16197
+ function catalogList(raw, labels, udf) {
16198
+ return Array.isArray(raw) ? { rows: raw.map((row) => projectFieldRow(row, labels, udf)), exposesValues: raw.some(exposesPicklistValues) } : { rows: null, exposesValues: false };
16199
+ }
16200
+ var catalogFieldsView = (raw) => catalogList(raw, false, false);
16201
+ var catalogLabelledFieldsView = (raw) => catalogList(raw, true, false);
16202
+ var catalogUdfView = (raw) => catalogList(raw, false, true);
16203
+ var catalogLabelledUdfView = (raw) => catalogList(raw, true, true);
16204
+ function compactCatalogList(raw, keepValues, udf) {
16205
+ const view = catalogList(raw, keepValues, udf);
16206
+ if (view.rows === null) return { rows: null, exposesValues: view.exposesValues };
16207
+ const flags = {
16208
+ required: view.rows.filter((row) => row.isRequired).map((row) => row.name),
16209
+ readOnly: view.rows.filter((row) => row.isReadOnly).map((row) => row.name),
16210
+ queryable: view.rows.filter((row) => row.isQueryable).map((row) => row.name),
16211
+ picklistFields: view.rows.filter((row) => row.isPickList).map((row) => row.name)
16212
+ };
16213
+ return {
16214
+ rows: view.rows.map((row) => ({
16215
+ name: row.name,
16216
+ type: row.type,
16217
+ isPickList: row.isPickList,
16218
+ isReference: row.referenceEntityType !== "",
16219
+ udf,
16220
+ ...keepValues && row.picklistValues !== void 0 ? { picklistValues: row.picklistValues } : {}
16221
+ })),
16222
+ flags,
16223
+ exposesValues: view.exposesValues
16224
+ };
16225
+ }
16226
+ var compactCatalogFieldsView = (raw) => compactCatalogList(raw, false, false);
16227
+ var compactCatalogLabelledFieldsView = (raw) => compactCatalogList(raw, true, false);
16228
+ var compactCatalogUdfView = (raw) => compactCatalogList(raw, false, true);
16229
+ var compactCatalogLabelledUdfView = (raw) => compactCatalogList(raw, true, true);
16230
+ function ticketStatusView(fields) {
16231
+ if (!Array.isArray(fields)) return [];
16232
+ const status = fields.find((f) => typeof f?.name === "string" && f.name.toLowerCase() === "status");
16233
+ if (status === void 0 || status.isPickList !== true || !Array.isArray(status.picklistValues)) return [];
16234
+ const out = [];
16235
+ for (const v of status.picklistValues) {
16236
+ const id = Number(v?.value);
16237
+ if (!Number.isSafeInteger(id)) continue;
16238
+ out.push({ id, label: typeof v.label === "string" ? v.label : "" });
16239
+ }
16240
+ return out;
16241
+ }
16242
+ function primitiveData(descriptor2) {
16243
+ return descriptor2 !== void 0 && "value" in descriptor2 && (descriptor2.value === null || typeof descriptor2.value !== "object" && typeof descriptor2.value !== "function");
16244
+ }
16245
+ function picklistsView(raw) {
16246
+ if (!Array.isArray(raw)) return null;
16247
+ const fields = /* @__PURE__ */ new Map();
16248
+ for (const rawField of raw) {
16249
+ const field = projectFieldRow(rawField, true);
16250
+ if (fields.has(field.name)) continue;
16251
+ const values = field.picklistValues;
16252
+ if (values === void 0) {
16253
+ fields.set(field.name, void 0);
16254
+ continue;
16255
+ }
16256
+ const labels = /* @__PURE__ */ new Map();
16257
+ if (values.some((entry) => {
16258
+ if (entry === null || typeof entry !== "object" || Object.getPrototypeOf(entry) !== Object.prototype) return true;
16259
+ return !primitiveData(Object.getOwnPropertyDescriptor(entry, "value")) || !primitiveData(Object.getOwnPropertyDescriptor(entry, "label"));
16260
+ })) {
16261
+ fields.set(field.name, { labels, ordered: values });
16262
+ continue;
16263
+ }
16264
+ for (const value of values) {
16265
+ const key = String(value.value);
16266
+ if (!labels.has(key)) labels.set(key, typeof value.label === "string" ? value.label : null);
16267
+ }
16268
+ fields.set(field.name, { labels });
16269
+ }
16270
+ return fields;
16271
+ }
16272
+ function lookupPicklist(view, value) {
16273
+ if (view.ordered !== void 0) {
16274
+ const hit = view.ordered.find((entry) => String(entry.value) === String(value));
16275
+ return { found: hit !== void 0, label: typeof hit?.label === "string" ? hit.label : null };
16276
+ }
16277
+ const key = String(value);
16278
+ return { found: view.labels.has(key), label: view.labels.get(key) ?? null };
16279
+ }
16280
+ function ticketStatusFieldsView(fields) {
16281
+ if (!Array.isArray(fields)) return [];
16282
+ const status = fields.find((field) => typeof field?.name === "string" && field.name.toLowerCase() === "status");
16283
+ return status === void 0 ? [] : [status];
16284
+ }
16285
+
15845
16286
  // src/utils/bounded.ts
15846
16287
  async function runBounded(fn, items, opts) {
15847
16288
  const { concurrency, signal, settle } = opts;
@@ -15897,48 +16338,7 @@ var MAX_FIELD_CATALOG_WIRE = 60;
15897
16338
  var FIELD_CATALOG_HONESTY_NOTE = "Live field metadata reports the SHAPE of a field (existence, requiredness, type, maxLength, read-only, queryable, picklist-ness) as FLAGS and NAMES: picklist-ness as a flag (isPickList) and picklist field names (picklistFields). With the opt-in `labels: true`, picklist rows carry the vendor's exposed picklist VALUES (labels next to each value); without it the op serves no VALUES. It cannot resolve a picklist VALUE the vendor does not expose to this API user (a vendor-withheld picklist value): retrying the catalog will not surface a withheld value; that gap is vendor-side, not a client defect.";
15898
16339
  var MIN_FIELD_CATALOG_MAX_BYTES = 4096;
15899
16340
  var FIELD_CATALOG_OPT_KEYS = ["resources", "include", "fresh", "fields", "labels", "compact", "maxBytes"];
15900
- function projectFieldRow(raw, labels = false, udf = false) {
15901
- const r = typeof raw === "object" && raw !== null ? raw : {};
15902
- const name = typeof r.name === "string" ? r.name : "";
15903
- const type = typeof r.dataType === "string" ? r.dataType : typeof r.type === "string" ? r.type : "";
15904
- const values = labels && r.isPickList === true && Array.isArray(r.picklistValues) && r.picklistValues.length > 0 ? r.picklistValues : void 0;
15905
- const referenceEntityType = typeof r.referenceEntityType === "string" ? r.referenceEntityType : "";
15906
- return {
15907
- name,
15908
- ...typeof r.label === "string" && r.label !== "" ? { label: r.label } : {},
15909
- type,
15910
- isRequired: r.isRequired === true,
15911
- isReadOnly: r.isReadOnly === true,
15912
- // Issue #219 N7: a UDF row never serves the vendor's isQueryable (it is
15913
- // true for UDFs while a plain filter on a UDF name is refused); it serves
15914
- // the marker the filter actually needs.
15915
- ...udf ? { filterable: "udf-marker" } : { isQueryable: r.isQueryable === true },
15916
- isPickList: r.isPickList === true,
15917
- ...isObjectOrArrayType(type) ? { writeShape: "replace-all" } : {},
15918
- maxLength: typeof r.length === "number" ? r.length : null,
15919
- referenceEntityType,
15920
- ...values !== void 0 ? { picklistValues: values } : {}
15921
- };
15922
- }
15923
- function compactFieldRow(f, udf, keepValues) {
15924
- return {
15925
- name: f.name,
15926
- type: f.type,
15927
- isPickList: f.isPickList,
15928
- isReference: f.referenceEntityType !== "",
15929
- udf,
15930
- ...keepValues && f.picklistValues !== void 0 ? { picklistValues: f.picklistValues } : {}
15931
- };
15932
- }
15933
- function isObjectOrArrayType(type) {
15934
- const t = type.trim().toLowerCase();
15935
- return t === "object" || t === "array" || t === "collection" || t.endsWith("[]");
15936
- }
15937
- function exposesPicklistValues(raw) {
15938
- const r = typeof raw === "object" && raw !== null ? raw : {};
15939
- return Array.isArray(r.picklistValues) && r.picklistValues.length > 0;
15940
- }
15941
- function applyFieldsFilter(projected, filter, row) {
16341
+ function applyFieldsFilter(projected, filter, row, flags) {
15942
16342
  const kept = filter === void 0 ? projected : projected.filter((f) => filter.includes(f.name));
15943
16343
  if (filter !== void 0) {
15944
16344
  const present = new Set(projected.map((f) => f.name));
@@ -15946,10 +16346,19 @@ function applyFieldsFilter(projected, filter, row) {
15946
16346
  row.projected = true;
15947
16347
  }
15948
16348
  row.fields = kept;
15949
- row.required = kept.filter((f) => f.isRequired).map((f) => f.name);
15950
- row.readOnly = kept.filter((f) => f.isReadOnly).map((f) => f.name);
15951
- row.queryable = kept.filter((f) => f.isQueryable).map((f) => f.name);
15952
- row.picklistFields = kept.filter((f) => f.isPickList).map((f) => f.name);
16349
+ if (flags !== void 0) {
16350
+ const present = new Set(kept.map((field) => field.name));
16351
+ row.required = flags.required.filter((name) => present.has(name));
16352
+ row.readOnly = flags.readOnly.filter((name) => present.has(name));
16353
+ row.queryable = flags.queryable.filter((name) => present.has(name));
16354
+ row.picklistFields = flags.picklistFields.filter((name) => present.has(name));
16355
+ } else {
16356
+ const full = kept;
16357
+ row.required = full.filter((field) => field.isRequired).map((field) => field.name);
16358
+ row.readOnly = full.filter((field) => field.isReadOnly).map((field) => field.name);
16359
+ row.queryable = full.filter((field) => field.isQueryable).map((field) => field.name);
16360
+ row.picklistFields = full.filter((field) => field.isPickList).map((field) => field.name);
16361
+ }
15953
16362
  }
15954
16363
  async function capabilitySets() {
15955
16364
  const fieldOps = /* @__PURE__ */ new Map();
@@ -16164,14 +16573,25 @@ function kindFetches(holder, resource) {
16164
16573
  udf: () => holder?.getUdfInfo?.() ?? Promise.reject(new AutotaskError(`fieldCatalog: the client exposes no getUdfInfo read for "${resource}"`, { code: "INVALID_RESPONSE", category: "server" }))
16165
16574
  };
16166
16575
  }
16167
- async function readKind(ctx, resource, kind, fetch2) {
16576
+ function catalogProjector(kind, ctx) {
16577
+ if (ctx.compact) {
16578
+ const keepValues = ctx.labels && ctx.fieldsFilter !== void 0;
16579
+ if (kind === "fields") return keepValues ? compactCatalogLabelledFieldsView : compactCatalogFieldsView;
16580
+ if (kind === "udf") return keepValues ? compactCatalogLabelledUdfView : compactCatalogUdfView;
16581
+ }
16582
+ if (kind === "fields") return ctx.labels ? catalogLabelledFieldsView : catalogFieldsView;
16583
+ if (kind === "udf") return ctx.labels ? catalogLabelledUdfView : catalogUdfView;
16584
+ return void 0;
16585
+ }
16586
+ async function readKind(ctx, resource, kind, fetch2, holder, projector = catalogProjector(kind, ctx)) {
16168
16587
  const cache = ctx.client.http.fieldCache;
16169
16588
  const peek = cache !== void 0 && !ctx.fresh ? cache.peek(fieldKey(resource, kind)) : { hit: false, age: null };
16170
16589
  if (peek.hit && cache !== void 0) {
16171
- return { kind, peek, outcome: { status: "fulfilled", value: cache.get(fieldKey(resource, kind)) } };
16590
+ const value = projector !== void 0 && typeof cache.getProjected === "function" ? cache.getProjected(fieldKey(resource, kind), projector) ?? projector(void 0) : projector === void 0 ? cache.get(fieldKey(resource, kind)) : projector(cache.get(fieldKey(resource, kind)));
16591
+ return { kind, peek, outcome: { status: "fulfilled", value } };
16172
16592
  }
16173
16593
  try {
16174
- const value = await fetch2();
16594
+ const value = projector === void 0 ? await fetch2() : await readMetadataProjection(holder, kind, projector, fetch2);
16175
16595
  return { kind, peek, outcome: { status: "fulfilled", value } };
16176
16596
  } catch (error) {
16177
16597
  if (!isAutotaskError(error) || error.code === "ABORTED") throw error;
@@ -16179,7 +16599,7 @@ async function readKind(ctx, resource, kind, fetch2) {
16179
16599
  }
16180
16600
  }
16181
16601
  async function sweepResource(ctx, resource, tally, reads) {
16182
- const { fieldsFilter, labels } = ctx;
16602
+ const { fieldsFilter } = ctx;
16183
16603
  const fieldOp = ctx.fieldOps.get(resource);
16184
16604
  if (fieldOp === void 0) return void 0;
16185
16605
  const apiEntity = apiEntityFor(fieldOp);
@@ -16198,12 +16618,6 @@ async function sweepResource(ctx, resource, tally, reads) {
16198
16618
  wire: 0,
16199
16619
  error: null
16200
16620
  };
16201
- const projectList = (kind, list) => {
16202
- const projected = list.map((f) => projectFieldRow(f, labels, kind === "udf"));
16203
- if (kind === "fields") applyFieldsFilter(projected, fieldsFilter, row);
16204
- else row.udf = projected;
16205
- for (const f of list) if (exposesPicklistValues(f)) tally.anyPicklistValues = true;
16206
- };
16207
16621
  let allCached = true;
16208
16622
  const ages = [];
16209
16623
  for (const { kind, peek, outcome } of reads) {
@@ -16221,19 +16635,17 @@ async function sweepResource(ctx, resource, tally, reads) {
16221
16635
  if (kind === "info") {
16222
16636
  row.info = value ?? null;
16223
16637
  } else {
16224
- if (!Array.isArray(value)) {
16638
+ const view = value;
16639
+ if (view.rows === null) {
16225
16640
  if (row.error === null) row.error = { code: "INVALID_RESPONSE", message: `fieldCatalog: the ${kind} response for ${resource} was not a list` };
16226
16641
  continue;
16227
16642
  }
16228
- projectList(kind, value);
16643
+ if (kind === "fields") applyFieldsFilter(view.rows, fieldsFilter, row, view.flags);
16644
+ else row.udf = view.rows;
16645
+ if (view.exposesValues) tally.anyPicklistValues = true;
16229
16646
  }
16230
16647
  }
16231
16648
  row.cache = allCached ? { hit: true, age: ages.length > 0 ? Math.max(...ages) : 0 } : { hit: false, age: null };
16232
- if (ctx.compact) {
16233
- const keepValues = labels && fieldsFilter !== void 0;
16234
- if (row.fields !== void 0) row.fields = row.fields.map((f) => compactFieldRow(f, false, keepValues));
16235
- if (Array.isArray(row.udf)) row.udf = row.udf.map((f) => compactFieldRow(f, true, keepValues));
16236
- }
16237
16649
  const declared = await derivedFieldsFor(resource);
16238
16650
  if (declared.length > 0) {
16239
16651
  const byField = new Map(declared.map((d) => [d.field, d]));
@@ -16249,7 +16661,7 @@ async function sweepResource(ctx, resource, tally, reads) {
16249
16661
  }
16250
16662
  return row;
16251
16663
  }
16252
- async function fieldCatalog(client, opts) {
16664
+ async function prepareCatalog(client, opts) {
16253
16665
  validateCatalogOptsShape(opts);
16254
16666
  const { fieldOps, udfCapable, resources: allResources } = await capabilitySets();
16255
16667
  const include = resolveInclude(opts);
@@ -16258,11 +16670,22 @@ async function fieldCatalog(client, opts) {
16258
16670
  const labels = resolveLabels(opts);
16259
16671
  const { compact, maxBytes } = resolveSizeOpts(opts);
16260
16672
  assertWithinWireCap(targets.length, include.length);
16673
+ const ctx = { client, include, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
16674
+ return { ctx, targets, compact, maxBytes };
16675
+ }
16676
+ async function fieldCatalogPicklists(client, resource, fields) {
16677
+ const { ctx } = await prepareCatalog(client, { resources: [resource], labels: true, fields: [...fields] });
16678
+ const holder = client[camelKey(resource)];
16679
+ const [read] = await mapReadTasks(client.http, [resource], () => readKind(ctx, resource, "fields", kindFetches(holder, resource).fields, holder, picklistsView));
16680
+ return read.outcome.status === "fulfilled" ? read.outcome.value : null;
16681
+ }
16682
+ async function fieldCatalog(client, opts) {
16683
+ const { ctx, targets, compact, maxBytes } = await prepareCatalog(client, opts);
16684
+ const { include, labels, fieldOps, udfCapable } = ctx;
16261
16685
  const cache = client.http.fieldCache;
16262
16686
  const zone = client.config.zone ?? "unknown";
16263
16687
  const rows = [];
16264
16688
  const tally = { wireUsed: 0, anyPicklistValues: false };
16265
- const ctx = { client, fieldsFilter, labels, compact, fresh: opts?.fresh === true, fieldOps, udfCapable };
16266
16689
  for (const resource of targets) {
16267
16690
  apiEntityFor(fieldOps.get(resource));
16268
16691
  if (ctx.fresh) cache?.invalidate(`${resource}:`);
@@ -16270,9 +16693,9 @@ async function fieldCatalog(client, opts) {
16270
16693
  const tasks = targets.flatMap((resource) => {
16271
16694
  const holder = client[camelKey(resource)];
16272
16695
  const fetches = kindFetches(holder, resource);
16273
- return include.map((kind) => ({ resource, kind, fetch: fetches[kind] }));
16696
+ return include.map((kind) => ({ resource, kind, fetch: fetches[kind], holder }));
16274
16697
  });
16275
- const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2 }) => readKind(ctx, resource, kind, fetch2));
16698
+ const reads = await mapReadTasks(client.http, tasks, ({ resource, kind, fetch: fetch2, holder }) => readKind(ctx, resource, kind, fetch2, holder));
16276
16699
  for (let index = 0; index < targets.length; index += 1) {
16277
16700
  const start = index * include.length;
16278
16701
  const row = await sweepResource(ctx, targets[index], tally, reads.slice(start, start + include.length));
@@ -16874,19 +17297,12 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16874
17297
  };
16875
17298
  });
16876
17299
  }
16877
- const picklists = {};
17300
+ let picklists = null;
16878
17301
  if (plan.labelFields.length > 0) {
16879
17302
  tasks.push(async () => {
16880
17303
  try {
16881
17304
  const labelResource = plan.labelResource ?? "tickets";
16882
- const catalog = await fieldCatalog(client, { resources: [labelResource], labels: true, fields: [...plan.labelFields] });
16883
- const row = catalog.rows.find((r) => r.resource === labelResource);
16884
- if (row !== void 0 && row.error === null && row.fields !== void 0) {
16885
- for (const f of plan.labelFields) {
16886
- const frow = row.fields.find((x) => x.name === f);
16887
- picklists[f] = frow?.picklistValues;
16888
- }
16889
- }
17305
+ picklists = await fieldCatalogPicklists(client, labelResource, plan.labelFields);
16890
17306
  } catch (err) {
16891
17307
  if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
16892
17308
  }
@@ -16922,17 +17338,17 @@ async function resolveCompositeNames(http, plan, opts = {}) {
16922
17338
  recordName: (table, id) => section.rows[`${table}:${id}`]?.name ?? null,
16923
17339
  labelFor: (field, value) => {
16924
17340
  if (value === null || value === void 0) return null;
16925
- const values = picklists[field];
17341
+ const values = picklists?.get(field);
16926
17342
  if (values === void 0) {
16927
17343
  section.reasons[field] = FIELD_CATALOG_HONESTY_NOTE;
16928
17344
  return null;
16929
17345
  }
16930
- const hit = values.find((v) => String(v.value) === String(value));
16931
- if (hit === void 0) {
17346
+ const hit = lookupPicklist(values, value);
17347
+ if (!hit.found) {
16932
17348
  if (String(value) !== "0") section.reasons[field] = PICKLIST_VALUE_NOT_SERVED_NOTE;
16933
17349
  return null;
16934
17350
  }
16935
- return typeof hit.label === "string" ? hit.label : null;
17351
+ return hit.label;
16936
17352
  }
16937
17353
  };
16938
17354
  }
@@ -16994,8 +17410,7 @@ function subscriberError(error, operation) {
16994
17410
  };
16995
17411
  return copyValue(error);
16996
17412
  }
16997
- function cachedRead(http, cache, key, path, operation, request, fresh, shouldStore) {
16998
- if (cache === void 0) return request();
17413
+ function cachedRead(http, cache, key, path, operation, request, fresh, shouldStore, projector) {
16999
17414
  let ownsLoader = false;
17000
17415
  const loader = (signal) => {
17001
17416
  ownsLoader = true;
@@ -17010,11 +17425,21 @@ function cachedRead(http, cache, key, path, operation, request, fresh, shouldSto
17010
17425
  suggestedAction: "The caller aborted; re-issue the call if still needed."
17011
17426
  })
17012
17427
  };
17013
- return cache.load(key, loader, options).catch((error) => {
17428
+ const select = (value) => {
17429
+ if (options.signal?.aborted) throw options.abortError();
17430
+ const selected = projector === void 0 ? value : projectMetadata(value, projector);
17431
+ if (options.signal?.aborted) throw options.abortError();
17432
+ return selected;
17433
+ };
17434
+ if (cache === void 0) return request().then(select);
17435
+ const load = (fresh2) => projector !== void 0 && typeof cache.loadProjected === "function" ? cache.loadProjected(key, loader, projector, { ...options, fresh: fresh2 }) : cache.load(key, loader, { ...options, fresh: fresh2 }).then(select);
17436
+ return load(fresh).catch((error) => {
17014
17437
  if (ownsLoader || !(error instanceof AutotaskError) || error.details?.budgetScope !== "client" || error.notSent !== true) throw error;
17015
17438
  if (options.signal?.aborted) throw options.abortError();
17016
- const warm = cache.get(key);
17017
- return warm !== void 0 ? warm : cache.load(key, loader, { ...options, fresh: true });
17439
+ const projected = projector !== void 0 && typeof cache.getProjected === "function";
17440
+ const warm = projected ? cache.getProjected(key, projector) : cache.get(key);
17441
+ if (options.signal?.aborted) throw options.abortError();
17442
+ return warm !== void 0 ? projected ? warm : select(warm) : load(true);
17018
17443
  }).catch((error) => {
17019
17444
  if (!(error instanceof AutotaskError)) throw error;
17020
17445
  const failure = subscriberError(error, operation);
@@ -17033,7 +17458,7 @@ function cachedRecordGet(http, path, operation, fresh = false) {
17033
17458
  fresh
17034
17459
  );
17035
17460
  }
17036
- function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh = false, maxRetries) {
17461
+ function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh = false, maxRetries, projector) {
17037
17462
  const cache = http.fieldCache;
17038
17463
  const request = (signal) => {
17039
17464
  return http.request({ method: "GET", path, operation, signal, maxRetries }).then(unwrap).catch((error) => {
@@ -17047,12 +17472,13 @@ function cachedMetadataGet(http, resource, kind, path, operation, unwrap, fresh
17047
17472
  if (value === null || value === void 0) return false;
17048
17473
  if (Array.isArray(value)) return value.length > 0;
17049
17474
  return typeof value !== "object" || Object.keys(value).length > 0;
17050
- });
17475
+ }, projector);
17051
17476
  }
17052
17477
 
17053
17478
  // src/field-sets.ts
17054
17479
  var MODEL_FIELD_SETS = {
17055
17480
  "appointments": ["id", "createDateTime", "creatorResourceID", "description", "endDateTime", "resourceID", "startDateTime", "title", "updateDateTime"],
17481
+ "attachment_info": ["id", "articleID", "attachDate", "attachedByContactID", "attachedByResourceID", "attachmentType", "companyID", "companyNoteID", "configurationItemID", "configurationItemNoteID", "contentType", "contractID", "contractNoteID", "creatorType", "documentID", "expenseItemID", "expenseReportID", "fileSize", "fullPath", "impersonatorCreatorResourceID", "opportunityID", "parentAttachmentID", "parentID", "parentType", "projectID", "projectNoteID", "publish", "resourceID", "salesOrderID", "taskID", "taskNoteID", "ticketID", "ticketNoteID", "timeEntryID", "title", "soapParentPropertyId"],
17056
17482
  "billing_codes": ["id", "afterHoursWorkType", "billingCodeType", "department", "description", "externalNumber", "generalLedgerAccount", "isActive", "isExcludedFromNewContracts", "markupRate", "name", "taxCategoryID", "unitCost", "unitPrice", "useType"],
17057
17483
  "billing_item_approval_levels": ["id", "approvalDateTime", "approvalLevel", "approvalResourceID", "timeEntryID"],
17058
17484
  "billing_items": ["id", "accountManagerWhenApprovedID", "billingCodeID", "billingItemType", "companyID", "configurationItemID", "contractBlockID", "contractChargeID", "contractID", "contractServiceAdjustmentID", "contractServiceBundleAdjustmentID", "contractServiceBundleID", "contractServiceBundlePeriodID", "contractServiceID", "contractServicePeriodID", "description", "expenseItemID", "extendedPrice", "internalCurrencyExtendedPrice", "internalCurrencyRate", "internalCurrencyTaxDollars", "internalCurrencyTotalAmount", "invoiceID", "itemApproverID", "itemDate", "itemName", "lineItemFullDescription", "lineItemGroupDescription", "milestoneID", "nonBillable", "organizationalLevelAssociationID", "ourCost", "postedDate", "postedOnTime", "projectChargeID", "projectID", "purchaseOrderNumber", "quantity", "rate", "roleID", "serviceBundleID", "serviceID", "sortOrderID", "subType", "taskID", "taxDollars", "ticketChargeID", "ticketID", "timeEntryID", "totalAmount", "vendorID", "webServiceDate"],
@@ -17062,7 +17488,9 @@ var MODEL_FIELD_SETS = {
17062
17488
  "classification_icons": ["id", "description", "isActive", "isSystem", "name", "relativeUrl"],
17063
17489
  "companies": ["id", "additionalAddressInformation", "address1", "address2", "alternatePhone1", "alternatePhone2", "apiVendorID", "assetValue", "billToCompanyLocationID", "billToAdditionalAddressInformation", "billingAddress1", "billingAddress2", "billToAddressToUse", "billToAttention", "billToCity", "billToCountryID", "billToState", "billToZipCode", "city", "classification", "companyCategoryID", "companyName", "companyNumber", "companyType", "competitorID", "countryID", "createDate", "createdByResourceID", "currencyID", "fax", "impersonatorCreatorResourceID", "invoiceEmailMessageID", "invoiceMethod", "invoiceNonContractItemsToParentCompany", "invoiceTemplateID", "isActive", "isClientPortalActive", "isEnabledForComanaged", "isSample", "isTaskFireActive", "isTaxExempt", "lastActivityDate", "lastTrackedModifiedDateTime", "marketSegmentID", "ownerResourceID", "parentCompanyID", "phone", "postalCode", "purchaseOrderTemplateID", "quoteEmailMessageID", "quoteTemplateID", "sicCode", "state", "stockMarket", "stockSymbol", "surveyCompanyRating", "taxID", "taxRegionID", "territoryID", "webAddress", "userDefinedFields"],
17064
17490
  "company_alerts": ["id", "alertText", "alertTypeID", "companyID", "soapParentPropertyId"],
17491
+ "company_attachments": ["id", "attachDate", "attachedByContactID", "attachedByResourceID", "attachmentType", "companyID", "companyNoteID", "contentType", "creatorType", "fileSize", "fullPath", "impersonatorCreatorResourceID", "opportunityID", "parentAttachmentID", "parentID", "publish", "salesOrderID", "title", "data", "parentType", "soapParentPropertyId", "isTaskAttachment"],
17065
17492
  "company_locations": ["id", "address1", "address2", "alternatePhone1", "alternatePhone2", "city", "companyID", "countryID", "description", "fax", "isActive", "isPrimary", "isTaxExempt", "overrideCompanyTaxSettings", "name", "phone", "postalCode", "roundtripDistance", "state", "taxRegionID", "soapParentPropertyId"],
17493
+ "company_note_attachments": ["id", "attachDate", "attachedByContactID", "attachedByResourceID", "attachmentType", "companyID", "companyNoteID", "contentType", "creatorType", "fileSize", "fullPath", "impersonatorCreatorResourceID", "opportunityID", "parentID", "publish", "salesOrderID", "title", "data", "parentType", "soapParentPropertyId", "isTaskAttachment"],
17066
17494
  "company_notes": ["id", "actionType", "assignedResourceID", "companyID", "completedDateTime", "contactID", "createDateTime", "endDateTime", "impersonatorCreatorResourceID", "impersonatorUpdaterResourceID", "lastModifiedDate", "name", "note", "opportunityID", "startDateTime", "soapParentPropertyId"],
17067
17495
  "company_site_configurations": ["id", "companyID", "locationName", "soapParentPropertyId", "userDefinedFields"],
17068
17496
  "company_webhooks": ["id", "deactivationUrl", "isActive", "isReady", "isSubscribedToCreateEvents", "isSubscribedToDeleteEvents", "isSubscribedToUpdateEvents", "name", "notificationEmailAddress", "ownerResourceID", "secretKey", "sendThresholdExceededNotification", "webhookGUID", "webhookUrl"],
@@ -17182,9 +17610,12 @@ var MODEL_FIELD_SETS = {
17182
17610
  };
17183
17611
  var MODEL_DATE_FIELDS = {
17184
17612
  "appointments": ["createDateTime", "endDateTime", "startDateTime", "updateDateTime"],
17613
+ "attachment_info": ["attachDate"],
17185
17614
  "billing_item_approval_levels": ["approvalDateTime"],
17186
17615
  "billing_items": ["itemDate", "postedDate", "postedOnTime", "webServiceDate"],
17187
17616
  "companies": ["createDate", "lastActivityDate", "lastTrackedModifiedDateTime"],
17617
+ "company_attachments": ["attachDate"],
17618
+ "company_note_attachments": ["attachDate"],
17188
17619
  "company_notes": ["completedDateTime", "createDateTime", "endDateTime", "lastModifiedDate", "startDateTime"],
17189
17620
  "configuration_item_billing_product_associations": ["effectiveDate", "expirationDate"],
17190
17621
  "configuration_item_dns_records": ["createDateTime"],
@@ -17545,6 +17976,12 @@ function validateWalkBag(walk, prefix, details) {
17545
17976
  return wr;
17546
17977
  }
17547
17978
 
17979
+ // src/operations/query-pages.ts
17980
+ var PREPARE_BOUNDED_QUERY = /* @__PURE__ */ Symbol.for("node-autotask.prepare-bounded-query.v1");
17981
+ function assertPageReadActive(operation) {
17982
+ if (ambientCallerSignal()?.aborted) throw new AutotaskAbortError("Bounded query page consumption aborted by the caller", { operation });
17983
+ }
17984
+
17548
17985
  // src/resources/base/query.ts
17549
17986
  var QueryBase = class {
17550
17987
  httpClient;
@@ -17719,6 +18156,22 @@ var QueryBase = class {
17719
18156
  * Pure read; no mutation paths involved.
17720
18157
  */
17721
18158
  async queryBounded(params) {
18159
+ return this.boundedQueryResult(params);
18160
+ }
18161
+ /** Internal governed consumer hook; all validation and paging stay shared. @internal */
18162
+ [PREPARE_BOUNDED_QUERY]() {
18163
+ const guard = captureReadGuard(this.http, `${this.config.key}.query`);
18164
+ return {
18165
+ guard,
18166
+ consume: async (params, consume) => {
18167
+ guard();
18168
+ const { items, ...summary } = await this.boundedQueryResult(params, consume);
18169
+ guard();
18170
+ return summary;
18171
+ }
18172
+ };
18173
+ }
18174
+ async boundedQueryResult(params, consume) {
17722
18175
  if (Array.isArray(params)) {
17723
18176
  throw new AutotaskConfigError(
17724
18177
  "queryBounded: params must be an object { filter?, limit?, latest?, includeFields? } \u2014 a bare conditions array is not accepted (wrap it: { filter: [...] })"
@@ -17765,13 +18218,28 @@ var QueryBase = class {
17765
18218
  if (latest !== void 0) {
17766
18219
  return this.applyNoteChars(await this.latestWalk(walkParams, Math.max(limit, latest), latest), noteChars);
17767
18220
  }
17768
- const { items, pages: pages2, guard, sliced, cursor, names } = await this.walkBounded(walkParams, cap, limit, labelPages);
17769
- const hasMore = maxRows === void 0 ? (items.length >= cap || guard) && (sliced > 0 || cursor !== null) : guard || sliced > 0 || cursor !== null;
17770
- const result = { items, fetched: items.length, hasMore, pagesWalked: pages2 };
18221
+ let truncatedFields = 0;
18222
+ const sink = consume === void 0 ? void 0 : async (rows, page) => {
18223
+ const projected = this.applyNoteChars({ items: rows, fetched: rows.length, hasMore: false, pagesWalked: 1 }, noteChars);
18224
+ truncatedFields += projected.noteCharsTruncated ?? 0;
18225
+ assertPageReadActive(`${this.config.key}.query`);
18226
+ try {
18227
+ await consume({ items: projected.items, page });
18228
+ } catch (error) {
18229
+ assertPageReadActive(`${this.config.key}.query`);
18230
+ throw error;
18231
+ }
18232
+ assertPageReadActive(`${this.config.key}.query`);
18233
+ };
18234
+ const { items, fetched, pages: pages2, guard, sliced, cursor, names } = await this.walkBounded(walkParams, cap, limit, labelPages, sink);
18235
+ const hasMore = maxRows === void 0 ? (fetched >= cap || guard) && (sliced > 0 || cursor !== null) : guard || sliced > 0 || cursor !== null;
18236
+ const result = { items, fetched, hasMore, pagesWalked: pages2 };
17771
18237
  if (maxRows !== void 0) result.truncated = hasMore;
17772
18238
  if (names !== void 0) result.names = names;
17773
18239
  this.stampEmptyQueryResult(result, params);
17774
- return this.applyNoteChars(result, noteChars);
18240
+ if (consume === void 0) return this.applyNoteChars(result, noteChars);
18241
+ if (truncatedFields > 0) result.noteCharsTruncated = truncatedFields;
18242
+ return result;
17775
18243
  }
17776
18244
  /** Issue #61 (slice A): the noteChars truncation at the SINGLE chokepoint
17777
18245
  * of `queryBounded` — the normal walk and the `latest` paths both
@@ -17800,9 +18268,10 @@ var QueryBase = class {
17800
18268
  * SOFT stop (never a throw). ONE per-walk closure (walks never share
17801
18269
  * state).
17802
18270
  * @internal */
17803
- async walkBounded(p, limit, pageSizeBase, labelPages = false) {
18271
+ async walkBounded(p, limit, pageSizeBase, labelPages = false, consume) {
17804
18272
  const state2 = { cursor: null };
17805
18273
  const items = [];
18274
+ let fetched = 0;
17806
18275
  let pages2 = 0;
17807
18276
  let sliced = 0;
17808
18277
  let guard = false;
@@ -17814,6 +18283,7 @@ var QueryBase = class {
17814
18283
  guard = true;
17815
18284
  break;
17816
18285
  }
18286
+ if (consume !== void 0) assertPageReadActive(`${this.config.key}.query`);
17817
18287
  const page = await this.fetchPage(p, pages2 + 1, pageSize, state2);
17818
18288
  pages2 += 1;
17819
18289
  if (labelPages && this.http.client !== void 0) {
@@ -17824,18 +18294,20 @@ var QueryBase = class {
17824
18294
  Object.assign(nameReasons, labelled.names.reasons);
17825
18295
  }
17826
18296
  }
17827
- const remaining = limit - items.length;
18297
+ const remaining = limit - fetched;
17828
18298
  const take = page.items.slice(0, remaining);
17829
18299
  sliced += Math.max(0, page.items.length - remaining);
17830
- items.push(...take);
17831
- if (items.length >= limit) break;
18300
+ fetched += take.length;
18301
+ if (consume === void 0) items.push(...take);
18302
+ else await consume(take, pages2);
18303
+ if (fetched >= limit) break;
17832
18304
  if (!page.hasMore || page.items.length === 0) break;
17833
18305
  }
17834
18306
  const names = nameNotes.size === 0 ? void 0 : {
17835
18307
  note: [...nameNotes].join("; "),
17836
18308
  ...Object.keys(nameReasons).length === 0 ? {} : { reasons: nameReasons }
17837
18309
  };
17838
- return { items, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
18310
+ return { items, fetched, pages: pages2, guard, sliced, cursor: state2.cursor, ...names === void 0 ? {} : { names } };
17839
18311
  }
17840
18312
  /** A walk stop is TRUNCATED when the 1000-page guard fired, or the limit
17841
18313
  * was met with a live next cursor (or a sliced final page): rows exist
@@ -17859,7 +18331,7 @@ var QueryBase = class {
17859
18331
  * speculation).
17860
18332
  * @internal */
17861
18333
  stampEmptyQueryResult(result, params) {
17862
- if (result.items.length !== 0) return;
18334
+ if (result.fetched !== 0) return;
17863
18335
  result.blindSurface = blindStampFor(BLIND_SURFACE_STAMPS[this.config.key]?.query, params?.filter);
17864
18336
  const pinnedReason = normalizedConditions(params?.filter) === void 0 ? EMPTY_REASON_STAMPS[this.config.key]?.query : void 0;
17865
18337
  if (result.blindSurface !== void 0 || pinnedReason !== void 0) {
@@ -18095,7 +18567,7 @@ var QueryBase = class {
18095
18567
  };
18096
18568
 
18097
18569
  // src/resources/base/meta.ts
18098
- var MetaBase = class extends QueryBase {
18570
+ var MetaBase = class _MetaBase extends QueryBase {
18099
18571
  // ------------------------------------------------------------------
18100
18572
  // Single-record reads
18101
18573
  // ------------------------------------------------------------------
@@ -18242,21 +18714,7 @@ var MetaBase = class extends QueryBase {
18242
18714
  * entity's entries via the fieldCache's `invalidate` first — the trio
18243
18715
  * keeps its no-arg surface (the registry/MCP arity pin). */
18244
18716
  async getEntityInfo() {
18245
- return await this.cachedMeta(
18246
- "info",
18247
- `${this.resourcePath}/entityInformation`,
18248
- `${this.config.key}.getEntityInfo`,
18249
- (res) => {
18250
- const body = isRecord2(res) ? res : void 0;
18251
- if (body === void 0 || !isRecord2(body.info)) {
18252
- throw new AutotaskError("Expected the entityInformation envelope { info }; got a different shape", {
18253
- code: "INVALID_RESPONSE",
18254
- category: "server"
18255
- });
18256
- }
18257
- return body.info;
18258
- }
18259
- );
18717
+ return await this.metadataRead("info");
18260
18718
  }
18261
18719
  /** `GET /V1.0/<E>/entityInformation/fields` → `{ fields }` unwrapped.
18262
18720
  * Goes through the field cache when it is present (issue #80:
@@ -18266,12 +18724,7 @@ var MetaBase = class extends QueryBase {
18266
18724
  * entity's entries via the fieldCache's `invalidate` first — the trio
18267
18725
  * keeps its no-arg surface (the registry/MCP arity pin). */
18268
18726
  async getFieldInfo() {
18269
- return await this.cachedMeta(
18270
- "fields",
18271
- `${this.resourcePath}/entityInformation/fields`,
18272
- `${this.config.key}.getFieldInfo`,
18273
- (res) => this.unwrapFields(res, "FieldInformationResultModel")
18274
- );
18727
+ return await this.metadataRead("fields");
18275
18728
  }
18276
18729
  /** `GET /V1.0/<E>/entityInformation/userDefinedFields` → `{ fields }` unwrapped.
18277
18730
  * Goes through the field cache when it is present (issue #80:
@@ -18281,12 +18734,29 @@ var MetaBase = class extends QueryBase {
18281
18734
  * entity's entries via the fieldCache's `invalidate` first — the trio
18282
18735
  * keeps its no-arg surface (the registry/MCP arity pin). */
18283
18736
  async getUdfInfo() {
18284
- return await this.cachedMeta(
18285
- "udf",
18286
- `${this.resourcePath}/entityInformation/userDefinedFields`,
18287
- `${this.config.key}.getUdfInfo`,
18288
- (res) => this.unwrapFields(res, "UserDefinedFieldInformationResultModel")
18289
- );
18737
+ return await this.metadataRead("udf");
18738
+ }
18739
+ /** Capture the owning transport's context; overridden readers keep their original path. @internal */
18740
+ [METADATA_PROJECTION](kind, projector) {
18741
+ const reader = kind === "info" ? "getEntityInfo" : kind === "fields" ? "getFieldInfo" : "getUdfInfo";
18742
+ const guard = captureReadGuard(this.http, `${this.config.key}.${reader}`);
18743
+ guard();
18744
+ if (this[reader] !== _MetaBase.prototype[reader] || this.cachedMeta !== _MetaBase.prototype.cachedMeta) return { guard };
18745
+ return { guard, projected: this.metadataRead(kind, projector) };
18746
+ }
18747
+ metadataRead(kind, projector) {
18748
+ const suffix = kind === "info" ? "" : kind === "fields" ? "/fields" : "/userDefinedFields";
18749
+ const operation = kind === "info" ? "getEntityInfo" : kind === "fields" ? "getFieldInfo" : "getUdfInfo";
18750
+ const path = `${this.resourcePath}/entityInformation${suffix}`;
18751
+ const unwrap = (res) => {
18752
+ if (kind !== "info") return this.unwrapFields(res, kind === "fields" ? "FieldInformationResultModel" : "UserDefinedFieldInformationResultModel");
18753
+ const body = isRecord2(res) ? res : void 0;
18754
+ if (body === void 0 || !isRecord2(body.info)) {
18755
+ throw new AutotaskError("Expected the entityInformation envelope { info }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
18756
+ }
18757
+ return body.info;
18758
+ };
18759
+ 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);
18290
18760
  }
18291
18761
  /** @internal */
18292
18762
  unwrapFields(body, envelopeName) {
@@ -19328,6 +19798,16 @@ var SIMPLE_RESOURCES = [
19328
19798
  helpers: { search: false, resolve: true, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
19329
19799
  opForms: { get: "global", create: "global", update: "global", delete: "global" }
19330
19800
  },
19801
+ {
19802
+ key: "attachment_info",
19803
+ accessor: "attachmentInfo",
19804
+ resourcePath: "/V1.0/AttachmentInfo",
19805
+ deletable: false,
19806
+ udfCapable: false,
19807
+ ops: { query: true, queryAll: false, count: true, get: true, create: false, update: false, delete: false, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
19808
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
19809
+ opForms: { get: "global" }
19810
+ },
19331
19811
  {
19332
19812
  key: "billing_codes",
19333
19813
  accessor: "billingCodes",
@@ -19419,6 +19899,20 @@ var SIMPLE_RESOURCES = [
19419
19899
  helpers: { search: false, resolve: true, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
19420
19900
  opForms: { get: "scoped", create: "scoped", update: "scoped", delete: "scoped" }
19421
19901
  },
19902
+ {
19903
+ key: "company_attachments",
19904
+ accessor: "companyAttachments",
19905
+ resourcePath: "/V1.0/CompanyAttachments",
19906
+ parentScopedPath: "/V1.0/Companies/{parentId}/Attachments",
19907
+ parentPath: "/V1.0/Companies",
19908
+ parentField: "companyID",
19909
+ deletable: true,
19910
+ udfCapable: false,
19911
+ attachmentGet: true,
19912
+ ops: { query: true, queryAll: false, count: true, get: true, create: true, update: false, delete: true, getEntityInfo: true, getFieldInfo: true, getUdfInfo: false, download: false },
19913
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
19914
+ opForms: { get: "scoped", create: "scoped", delete: "scoped" }
19915
+ },
19422
19916
  {
19423
19917
  key: "company_locations",
19424
19918
  accessor: "companyLocations",
@@ -19433,6 +19927,20 @@ var SIMPLE_RESOURCES = [
19433
19927
  helpers: { search: true, resolve: true, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
19434
19928
  opForms: { get: "scoped", create: "scoped", update: "scoped", delete: "scoped" }
19435
19929
  },
19930
+ {
19931
+ key: "company_note_attachments",
19932
+ accessor: "companyNoteAttachments",
19933
+ resourcePath: "/V1.0/CompanyNoteAttachments",
19934
+ parentScopedPath: "/V1.0/CompanyNotes/{parentId}/Attachments",
19935
+ parentPath: "/V1.0/CompanyNotes",
19936
+ parentField: "companyNoteID",
19937
+ deletable: true,
19938
+ udfCapable: false,
19939
+ attachmentGet: true,
19940
+ ops: { query: true, queryAll: false, count: true, get: true, create: true, update: false, delete: true, getEntityInfo: true, getFieldInfo: true, getUdfInfo: false, download: false },
19941
+ helpers: { search: false, resolve: false, getContext: false, createIfNotExists: false, attachToDocument: false, findBy: [] },
19942
+ opForms: { get: "scoped", create: "scoped", delete: "scoped" }
19943
+ },
19436
19944
  {
19437
19945
  key: "company_notes",
19438
19946
  accessor: "companyNotes",
@@ -19519,7 +20027,7 @@ var SIMPLE_RESOURCES = [
19519
20027
  resourcePath: "/V1.0/ConfigurationItemDnsRecords",
19520
20028
  parentScopedPath: "/V1.0/ConfigurationItems/{parentId}/DnsRecords",
19521
20029
  parentPath: "/V1.0/ConfigurationItems",
19522
- parentField: "configurationItemID",
20030
+ parentField: "installedProductID",
19523
20031
  deletable: true,
19524
20032
  udfCapable: false,
19525
20033
  ops: { query: true, queryAll: false, count: true, get: true, create: false, update: false, delete: true, getEntityInfo: true, getFieldInfo: true, getUdfInfo: true },
@@ -20769,6 +21277,12 @@ var SIMPLE_RESOURCES = [
20769
21277
  var GenericResource = class extends BaseResource {
20770
21278
  constructor(http, config, pageSize) {
20771
21279
  super(http, config, pageSize);
21280
+ if (["company_attachments", "company_note_attachments"].includes(config.key)) this.getUdfInfo = async () => {
21281
+ throw new OperationNotSupportedError(config.key, "getUdfInfo");
21282
+ };
21283
+ if (config.ops?.create === false || config.key === "company_attachments") this.createIfNotExists = async () => {
21284
+ throw new OperationNotSupportedError(config.key, "createIfNotExists");
21285
+ };
20772
21286
  }
20773
21287
  /** #293 QA F2: the superset exposes every generic method, but a row whose ops/helpers
20774
21288
  * flags mark an op absent (the plain entities) refuses it client-side, pre-wire — the
@@ -20957,6 +21471,7 @@ var GenericResource = class extends BaseResource {
20957
21471
  }
20958
21472
  /** Download the attachment bytes (GET .../{id}/data; node-proven path, quirk #9) → Buffer. */
20959
21473
  async download(parentId, id) {
21474
+ this.requireOp("download");
20960
21475
  if (this.config.attachmentGet !== true) throw new OperationNotSupportedError(this.config.key, "download");
20961
21476
  return this.downloadScoped(parentId, id);
20962
21477
  }
@@ -21103,13 +21618,7 @@ async function liveFieldNames(holder) {
21103
21618
  const reader = holder.getFieldInfo;
21104
21619
  if (typeof reader !== "function") return null;
21105
21620
  try {
21106
- const rows = await reader.call(holder);
21107
- if (!Array.isArray(rows)) return null;
21108
- const names = [];
21109
- for (const row of rows) {
21110
- if (typeof row.name === "string") names.push(row.name);
21111
- }
21112
- return names.length > 0 ? names : null;
21621
+ return await readMetadataProjection(holder, "fields", liveFieldNamesView, () => reader.call(holder));
21113
21622
  } catch (err) {
21114
21623
  if (!isAutotaskError(err) || err.code === "ABORTED") throw err;
21115
21624
  return null;
@@ -21184,7 +21693,7 @@ function readIncludeNames(record, includeFields) {
21184
21693
  return names;
21185
21694
  }
21186
21695
  function resolveAuthority(record, live) {
21187
- if (live !== null) return { known: live, authority: "the tenant's live entity field metadata", hasField: (name) => live.includes(name) };
21696
+ if (live !== null) return { known: live.names, authority: "the tenant's live entity field metadata", hasField: (name) => live.known.has(name) };
21188
21697
  const vendored = MODEL_FIELD_SETS[record.resource];
21189
21698
  const modelHas = modelFieldLookup(record.resource);
21190
21699
  const liveOnlyExempt = Array.isArray(record.metadata?.liveOnlyFields) ? record.metadata.liveOnlyFields : [];
@@ -21249,18 +21758,6 @@ async function findUnknownFieldNames(record, holder, lists) {
21249
21758
  var ASSUMED_CLOSED_STATUS_ID = 5;
21250
21759
  var CLOSED_STATUS_LABELS = ["complete", "completed", "closed", "cancelled", "canceled", "resolved"];
21251
21760
  var OP = "tickets.statusSemantics";
21252
- function picklistOf(fields) {
21253
- if (!Array.isArray(fields)) return [];
21254
- const status = fields.find((f) => typeof f?.name === "string" && f.name.toLowerCase() === "status");
21255
- if (status === void 0 || status.isPickList !== true || !Array.isArray(status.picklistValues)) return [];
21256
- const out = [];
21257
- for (const v of status.picklistValues) {
21258
- const id = Number(v?.value);
21259
- if (!Number.isSafeInteger(id)) continue;
21260
- out.push({ id, label: typeof v.label === "string" ? v.label : "" });
21261
- }
21262
- return out;
21263
- }
21264
21761
  async function readFields(http, fresh) {
21265
21762
  return cachedMetadataGet(http, "tickets", "fields", "/V1.0/Tickets/entityInformation/fields", OP, (res) => {
21266
21763
  const fields = res?.fields;
@@ -21268,7 +21765,7 @@ async function readFields(http, fresh) {
21268
21765
  throw new AutotaskError("Expected the FieldInformationResultModel envelope { fields: [] }; got a different shape", { code: "INVALID_RESPONSE", category: "server" });
21269
21766
  }
21270
21767
  return fields;
21271
- }, fresh, 0);
21768
+ }, fresh, 0, ticketStatusFieldsView);
21272
21769
  }
21273
21770
  function assumed(allowAssumed, operation) {
21274
21771
  if (!allowAssumed) {
@@ -21305,7 +21802,7 @@ async function resolveTicketStatusSemantics(http, opts = {}, operation = OP) {
21305
21802
  if (e instanceof AutotaskError && e.code === "ABORTED") throw e;
21306
21803
  return assumed(allowAssumed, operation);
21307
21804
  }
21308
- const picklist = picklistOf(fields);
21805
+ const picklist = ticketStatusView(fields);
21309
21806
  const closedIds = picklist.filter((v) => CLOSED_STATUS_LABELS.includes(v.label.trim().toLowerCase())).map((v) => v.id);
21310
21807
  if (closedIds.length === 0) return assumed(allowAssumed, operation);
21311
21808
  const labels = picklist.filter((v) => closedIds.includes(v.id)).map((v) => `${v.id} ${v.label}`).join(", ");
@@ -27867,25 +28364,46 @@ async function requireReadBack(record, operation, opts) {
27867
28364
  }
27868
28365
  var PRE_REQUEST_VALIDATORS = [
27869
28366
  (c) => governPreRequest(c.record, c.operation, c.opts),
28367
+ (c) => {
28368
+ if (!c.streaming) return;
28369
+ if (!c.boundedQuery) throw new AutotaskConfigError("invokeReadPages: only primitive query reads support bounded page consumption", { operation: c.operation });
28370
+ const holder = c.holder;
28371
+ const prepare2 = holder[PREPARE_BOUNDED_QUERY];
28372
+ if (typeof prepare2 !== "function") {
28373
+ throw new AutotaskConfigError("invokeReadPages: the resource does not support governed bounded page consumption", { operation: c.operation });
28374
+ }
28375
+ const session = prepare2.call(holder);
28376
+ if (typeof session?.guard !== "function" || typeof session.consume !== "function") throw new AutotaskConfigError("invokeReadPages: the resource has no scoped page consumer", { operation: c.operation });
28377
+ c.pageSession = session;
28378
+ session.guard();
28379
+ },
27870
28380
  (c) => requireReadBack(c.record, c.operation, c.opts),
27871
28381
  (c) => validateDispatchArgs(c.record, c.args),
27872
28382
  (c) => validateParamsBag(c.record, c.args),
27873
28383
  (c) => validateFreshSpelling(c.record, c.args),
28384
+ (c) => {
28385
+ if (!c.streaming) return;
28386
+ const bag = c.args[0];
28387
+ if (bag?.["walk"] === void 0 || bag?.["latest"] !== void 0) {
28388
+ throw new AutotaskConfigError("invokeReadPages: an explicit walk.maxRows query without latest is required", { operation: c.operation });
28389
+ }
28390
+ },
27874
28391
  (c) => c.boundedQuery || c.countedQuery ? validateQueryFieldNames(c.record, c.holder, c.args) : Promise.resolve(void 0)
27875
28392
  ];
27876
28393
  async function runPreRequestPass(ctx) {
27877
28394
  for (const step of PRE_REQUEST_VALIDATORS) await step(ctx);
27878
28395
  }
27879
- async function invokeMode(client, operation, argsIn = [], opts = {}) {
28396
+ async function prepareInvocation(client, operation, argsIn, opts, streaming = false) {
27880
28397
  const record = await resolveRecord(operation);
27881
28398
  const args = resolveDispatchArgs(record, argsIn);
27882
28399
  const boundedQuery = record.kind === "primitive" && record.operation === "query";
27883
28400
  const countedQuery = record.kind === "primitive" && record.operation === "count";
27884
28401
  const holder = resolveHolder(client, record, operation);
27885
- await runPreRequestPass({ record, operation, args, opts, client, holder, boundedQuery, countedQuery });
28402
+ const context = { record, operation, args, opts, client, holder, boundedQuery, countedQuery, streaming };
28403
+ await runPreRequestPass(context);
27886
28404
  const labelQuery = boundedQuery && readNamesOpt(client, args[0]?.["names"], `invoke: "${record.id}" params bag`);
27887
28405
  const methodName = boundedQuery ? "queryBounded" : record.operation;
27888
- const method = holder[methodName];
28406
+ const method = streaming ? context.pageSession?.consume : holder[methodName];
27889
28407
  if (typeof method !== "function") {
27890
28408
  throw new AutotaskConfigError(
27891
28409
  `invoke: "${record.resource}.${methodName}" is not a callable method on the client`,
@@ -27901,6 +28419,10 @@ async function invokeMode(client, operation, argsIn = [], opts = {}) {
27901
28419
  if (boundedQuery && args[0]?.["acknowledgeUnscoped"] !== true) {
27902
28420
  scopeNote = (await guardUnscopedQueryWalk(holder, record.id, args[0])).note;
27903
28421
  }
28422
+ return { record, args, holder, method, callArgs, labelQuery, scopeNote, pageSession: context.pageSession };
28423
+ }
28424
+ async function invokeMode(client, operation, argsIn = [], opts = {}) {
28425
+ const { record, args, holder, method, callArgs, labelQuery, scopeNote } = await prepareInvocation(client, operation, argsIn, opts);
27904
28426
  const result = await method.apply(holder, callArgs);
27905
28427
  if (labelQuery && args[0]?.["walk"] === void 0 && Array.isArray(result?.items)) {
27906
28428
  const bounded = result;
@@ -27916,6 +28438,15 @@ async function invoke(client, operation, args = [], opts = {}) {
27916
28438
  async function invokeRead(client, operation, args = [], opts = {}) {
27917
28439
  return invokeMode(client, operation, args, { ...opts, mode: "read" });
27918
28440
  }
28441
+ async function invokeReadPages(client, operation, args, onPage, opts = {}) {
28442
+ if (typeof onPage !== "function") throw new AutotaskConfigError("invokeReadPages: onPage must be a function", { operation });
28443
+ const prepared = await prepareInvocation(client, operation, args, { ...opts, mode: "read" }, true);
28444
+ prepared.pageSession.guard();
28445
+ const consume = prepared.method;
28446
+ const result = await consume.call(prepared.holder, prepared.callArgs[0], onPage);
28447
+ prepared.pageSession.guard();
28448
+ return prepared.scopeNote === void 0 ? result : { ...result, scopeNote: prepared.scopeNote };
28449
+ }
27919
28450
  async function invokeWrite(client, operation, args = [], opts = {}) {
27920
28451
  return invokeMode(client, operation, args, { ...opts, mode: "write" });
27921
28452
  }
@@ -28079,4 +28610,4 @@ var ContractsResource = class extends GenericResource {
28079
28610
  }
28080
28611
  };
28081
28612
 
28082
- export { AGGREGATE_DATE_BUCKETS, AGGREGATE_DEFAULT_LIMIT, AGGREGATE_DEFAULT_TOP, AGGREGATE_TOP_MAX, AutotaskAbortError, AutotaskConfigError, AutotaskError, AutotaskNetworkError, AutotaskTimeoutError, CREATE_BLOCKER_KINDS, CREDENTIAL_ENV_LOAD_ACTION, CREDENTIAL_SHAPE_POINTER, CompaniesResource, ConfirmationRequiredError, ConflictError, ContractsResource, DEFAULT_ZONE, DeleteBoundaryError, EXPAND_RESOURCE_NAMES_MAX_IDS, EmptyResponseError, FETCH_BY_IDS_CHUNK_SIZE, FETCH_BY_IDS_MAX_ITEMS, FIELD_CACHE_KINDS, FIELD_CATALOG_HONESTY_NOTE, GenericResource, HostPolicyDeniedError, HttpClient, INVOKE_OPTION_KEYS, InvoicesResource, MAX_FIELD_CATALOG_WIRE, MIN_FIELD_CATALOG_MAX_BYTES, MIN_PREFIX_SUMMARY_LENGTH, MaintenanceError, MarkerUnsafeIdError, MoveRefusedError, NotFoundError, OperationNotSupportedError, PARAMS_BAG_KEYS, PICKLIST_VALUE_NOT_SERVED_NOTE, PaginationLimitError, QueryTooLongError, RELATIONSHIP_MAP, RateLimitError, RecoveryTruncatedError, ResolutionError, ResponseRejectedError, SIMPLE_RESOURCES, ScopeRequiredError, StaleObjectError, TICKET_LABEL_FIELDS, TimeEntriesResource, TtlCache, UI_LINK_ENTITIES, UNSCOPED_WALK_THRESHOLD, UnexpectedContentTypeError, WORKFLOW_RESOURCES, ZONES, addLabelSibling, addNameSibling, aggregate, arAging, buildDryRunResult, buildQueryRequest, buildReadCache, buildUiLink, cachedRecordGet, clientOf, compositePart, compositePartLimit, createGuidance, createNamePlan, credentialShapeProblem, credentialValueSummary, cursorToPath, dateBucketLabel, effectiveRequiredFields, errorFromStatus, expandResourceNames, fetchByIds, fieldCatalog, foldFlattenedOpts, formatVendorDetail, invoke, invokeDelete, invokeRead, invokeWrite, isAutotaskError, isClosedStatus, isDeterministicVendor500, joinedCompositePart, mergeDetails, mergePartialBody, needsConfirmation, nextActionFor, nonChargeableWork, notPersistedFields, openStatusFilter, openTicketsOfPart, parseIdentifier, parseVendorErrors, portfolioMargin, queryRows, readTasks, recurringRevenue, refuse2 as refuse, relationshipMap, resolveAny, resolveCompositeNames, resolveConfig, resolveCredentials, resolveLineOfBusinessChain, resolveStaff, resolveTicketStatusSemantics, revenueRollup, runBounded, runMove, runWithSignal, sanitiseResult, searchAcrossResources, suspendCompanyIndex, uiLink, uiLinkFor, unknownKeysRefusal, unwrapItem, unwrapItems, unwrapOperation, validateDispatchArgs, validateInvokeOptions, validateParamsBag, vendorId, wipHours, zoneUrl };
28613
+ export { AGGREGATE_DATE_BUCKETS, AGGREGATE_DEFAULT_LIMIT, AGGREGATE_DEFAULT_TOP, AGGREGATE_TOP_MAX, AutotaskAbortError, AutotaskConfigError, AutotaskError, AutotaskNetworkError, AutotaskTimeoutError, CREATE_BLOCKER_KINDS, CREDENTIAL_ENV_LOAD_ACTION, CREDENTIAL_SHAPE_POINTER, CompaniesResource, ConfirmationRequiredError, ConflictError, ContractsResource, DEFAULT_ZONE, DeleteBoundaryError, EXPAND_RESOURCE_NAMES_MAX_IDS, EmptyResponseError, FETCH_BY_IDS_CHUNK_SIZE, FETCH_BY_IDS_MAX_ITEMS, FIELD_CACHE_KINDS, FIELD_CATALOG_HONESTY_NOTE, GenericResource, HostPolicyDeniedError, HttpClient, INVOKE_OPTION_KEYS, InvoicesResource, MAX_FIELD_CATALOG_WIRE, MIN_FIELD_CATALOG_MAX_BYTES, MIN_PREFIX_SUMMARY_LENGTH, MaintenanceError, MarkerUnsafeIdError, MoveRefusedError, NotFoundError, OperationNotSupportedError, PARAMS_BAG_KEYS, PICKLIST_VALUE_NOT_SERVED_NOTE, PaginationLimitError, QueryTooLongError, RELATIONSHIP_MAP, RateLimitError, RecoveryTruncatedError, ResolutionError, ResponseRejectedError, SIMPLE_RESOURCES, ScopeRequiredError, StaleObjectError, TICKET_LABEL_FIELDS, TimeEntriesResource, TtlCache, UI_LINK_ENTITIES, UNSCOPED_WALK_THRESHOLD, UnexpectedContentTypeError, WORKFLOW_RESOURCES, ZONES, addLabelSibling, addNameSibling, aggregate, arAging, buildDryRunResult, buildQueryRequest, buildReadCache, buildUiLink, cachedRecordGet, clientOf, compositePart, compositePartLimit, createGuidance, createNamePlan, credentialShapeProblem, credentialValueSummary, cursorToPath, dateBucketLabel, effectiveRequiredFields, errorFromStatus, expandResourceNames, fetchByIds, fieldCatalog, foldFlattenedOpts, formatVendorDetail, invoke, invokeDelete, invokeRead, invokeReadPages, invokeWrite, isAutotaskError, isClosedStatus, isDeterministicVendor500, joinedCompositePart, mergeDetails, mergePartialBody, needsConfirmation, nextActionFor, nonChargeableWork, notPersistedFields, openStatusFilter, openTicketsOfPart, parseIdentifier, parseVendorErrors, portfolioMargin, queryRows, readTasks, recurringRevenue, refuse2 as refuse, relationshipMap, resolveAny, resolveCompositeNames, resolveConfig, resolveCredentials, resolveLineOfBusinessChain, resolveStaff, resolveTicketStatusSemantics, revenueRollup, runBounded, runMove, runWithSignal, sanitiseResult, searchAcrossResources, suspendCompanyIndex, uiLink, uiLinkFor, unknownKeysRefusal, unwrapItem, unwrapItems, unwrapOperation, validateDispatchArgs, validateInvokeOptions, validateParamsBag, vendorId, wipHours, zoneUrl };