@uipath/uipath-typescript 1.3.10 → 1.4.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 (56) hide show
  1. package/dist/agent-memory/index.cjs +1765 -0
  2. package/dist/agent-memory/index.d.ts +588 -0
  3. package/dist/agent-memory/index.mjs +1763 -0
  4. package/dist/agents/index.cjs +1726 -0
  5. package/dist/agents/index.d.ts +502 -0
  6. package/dist/agents/index.mjs +1724 -0
  7. package/dist/assets/index.cjs +155 -30
  8. package/dist/assets/index.d.ts +84 -5
  9. package/dist/assets/index.mjs +155 -30
  10. package/dist/attachments/index.cjs +37 -6
  11. package/dist/attachments/index.d.ts +1 -0
  12. package/dist/attachments/index.mjs +37 -6
  13. package/dist/buckets/index.cjs +37 -6
  14. package/dist/buckets/index.d.ts +1 -0
  15. package/dist/buckets/index.mjs +37 -6
  16. package/dist/cases/index.cjs +192 -10
  17. package/dist/cases/index.d.ts +208 -7
  18. package/dist/cases/index.mjs +192 -11
  19. package/dist/conversational-agent/index.cjs +124 -57
  20. package/dist/conversational-agent/index.d.ts +190 -122
  21. package/dist/conversational-agent/index.mjs +124 -57
  22. package/dist/core/index.cjs +413 -105
  23. package/dist/core/index.d.ts +15 -0
  24. package/dist/core/index.mjs +413 -105
  25. package/dist/entities/index.cjs +135 -70
  26. package/dist/entities/index.d.ts +146 -45
  27. package/dist/entities/index.mjs +135 -70
  28. package/dist/feedback/index.cjs +37 -6
  29. package/dist/feedback/index.d.ts +1 -0
  30. package/dist/feedback/index.mjs +37 -6
  31. package/dist/governance/index.cjs +1782 -0
  32. package/dist/governance/index.d.ts +598 -0
  33. package/dist/governance/index.mjs +1780 -0
  34. package/dist/index.cjs +1050 -291
  35. package/dist/index.d.ts +1313 -134
  36. package/dist/index.mjs +1050 -292
  37. package/dist/index.umd.js +4546 -3770
  38. package/dist/jobs/index.cjs +37 -6
  39. package/dist/jobs/index.d.ts +1 -0
  40. package/dist/jobs/index.mjs +37 -6
  41. package/dist/maestro-processes/index.cjs +224 -18
  42. package/dist/maestro-processes/index.d.ts +221 -9
  43. package/dist/maestro-processes/index.mjs +224 -18
  44. package/dist/processes/index.cjs +37 -6
  45. package/dist/processes/index.d.ts +1 -0
  46. package/dist/processes/index.mjs +37 -6
  47. package/dist/queues/index.cjs +37 -6
  48. package/dist/queues/index.d.ts +1 -0
  49. package/dist/queues/index.mjs +37 -6
  50. package/dist/tasks/index.cjs +37 -6
  51. package/dist/tasks/index.d.ts +1 -0
  52. package/dist/tasks/index.mjs +37 -6
  53. package/dist/traces/index.cjs +1933 -0
  54. package/dist/traces/index.d.ts +566 -0
  55. package/dist/traces/index.mjs +1931 -0
  56. package/package.json +42 -2
package/dist/index.cjs CHANGED
@@ -4020,7 +4020,7 @@ object({
4020
4020
  secret: string().optional(),
4021
4021
  clientId: string().optional(),
4022
4022
  redirectUri: string().url().optional(),
4023
- scope: string().optional()
4023
+ scope: string().optional(),
4024
4024
  });
4025
4025
  class UiPathConfig {
4026
4026
  constructor(options) {
@@ -4071,6 +4071,32 @@ class ExecutionContext {
4071
4071
  */
4072
4072
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
4073
4073
  const isInActionCenter = isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
4074
+ const _params = isBrowser ? new URLSearchParams(window.location.search) : null;
4075
+ /**
4076
+ * True when the coded app has been loaded inside a host frame that explicitly
4077
+ * opted into token delegation by adding `?host=embed` to the iframe src URL.
4078
+ */
4079
+ const isHostEmbedded = isBrowser && window.self !== window.top && _params?.get('host') === 'embed';
4080
+ /**
4081
+ * The validated parent origin, read from the `?basedomain=` query param set
4082
+ * by the embedding host in the iframe src URL.
4083
+ * Mirrors the same mechanism used by ActionCenterTokenManager.
4084
+ * Non-null only when `?host=embed` is present and `?basedomain=` is a valid URL.
4085
+ */
4086
+ const embeddingOrigin = (() => {
4087
+ if (!isHostEmbedded)
4088
+ return null;
4089
+ const basedomain = _params?.get('basedomain');
4090
+ if (!basedomain)
4091
+ return null;
4092
+ try {
4093
+ return new URL(basedomain).origin;
4094
+ }
4095
+ catch {
4096
+ console.warn('embeddingOrigin: basedomain query param is not a valid URL', basedomain);
4097
+ return null;
4098
+ }
4099
+ })();
4074
4100
 
4075
4101
  /**
4076
4102
  * Session storage keys used by the auth module
@@ -4480,6 +4506,7 @@ const ORCHESTRATOR_BASE = 'orchestrator_';
4480
4506
  const PIMS_BASE = 'pims_';
4481
4507
  const DATAFABRIC_BASE = 'datafabric_';
4482
4508
  const IDENTITY_BASE = 'identity_';
4509
+ const LLMOPS_BASE = 'llmopstenant_';
4483
4510
  const INSIGHTS_RTM_BASE = 'insightsrtm_';
4484
4511
 
4485
4512
  /**
@@ -4572,7 +4599,7 @@ const MAESTRO_ENDPOINTS = {
4572
4599
  INSTANCES: {
4573
4600
  GET_ALL: `${PIMS_BASE}/api/v1/instances`,
4574
4601
  GET_BY_ID: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}`,
4575
- GET_EXECUTION_HISTORY: (instanceId) => `${PIMS_BASE}/api/v1/spans/${instanceId}`,
4602
+ GET_ELEMENT_EXECUTIONS: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/element-executions`,
4576
4603
  GET_BPMN: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/bpmn`,
4577
4604
  GET_VARIABLES: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/variables`,
4578
4605
  CANCEL: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/cancel`,
@@ -4584,6 +4611,9 @@ const MAESTRO_ENDPOINTS = {
4584
4611
  GET_BY_PROCESS: (processKey) => `${PIMS_BASE}/api/v1/incidents/process/${processKey}`,
4585
4612
  GET_BY_INSTANCE: (instanceId) => `${PIMS_BASE}/api/v1/instances/${instanceId}/incidents`,
4586
4613
  },
4614
+ TRACES: {
4615
+ GET_SPANS: (traceId) => `${LLMOPS_BASE}/api/Traces/spans?traceId=${traceId}`,
4616
+ },
4587
4617
  CASES: {
4588
4618
  GET_CASE_JSON: (instanceId) => `${PIMS_BASE}/api/v1/cases/${instanceId}/case-json`,
4589
4619
  GET_ELEMENT_EXECUTIONS: (instanceId) => `${PIMS_BASE}/api/v1/element-executions/case-instances/${instanceId}`,
@@ -4598,10 +4628,14 @@ const MAESTRO_ENDPOINTS = {
4598
4628
  TOP_PROCESSES_BY_RUN_COUNT: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcessesByRunCount`,
4599
4629
  /** Top processes ranked by failure count */
4600
4630
  TOP_PROCESSES_WITH_FAILURE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcesseswithFailure`,
4631
+ /** Top elements ranked by failure count */
4632
+ TOP_ELEMENTS_WITH_FAILURE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopElementswithFailure`,
4601
4633
  /** Instance status aggregated by date for time-series charts */
4602
4634
  INSTANCE_STATUS_BY_DATE: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/InstanceStatusByDate`,
4603
4635
  /** Top processes ranked by total duration */
4604
4636
  TOP_PROCESSES_BY_DURATION: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/TopProcessesByDuration`,
4637
+ /** Element count by status for agentic instances (process and case) */
4638
+ ELEMENT_COUNT_BY_STATUS: `${INSIGHTS_RTM_BASE}/agenticInstanceStatus/ElementCountByStatus`,
4605
4639
  },
4606
4640
  };
4607
4641
 
@@ -4676,6 +4710,96 @@ var ActionCenterEventNames;
4676
4710
  })(ActionCenterEventNames || (ActionCenterEventNames = {}));
4677
4711
 
4678
4712
  const AUTHENTICATION_TIMEOUT = 8000;
4713
+ const ALLOWED_HOST_ORIGINS = new Set([
4714
+ 'https://alpha.uipath.com',
4715
+ 'https://staging.uipath.com',
4716
+ 'https://cloud.uipath.com',
4717
+ ]);
4718
+ /**
4719
+ * Returns true if the origin is a trusted UiPath host that may initiate
4720
+ * token delegation. Mirrors the same allowlist used by ActionCenterTokenManager.
4721
+ */
4722
+ function isValidHostOrigin(origin) {
4723
+ if (!origin)
4724
+ return false;
4725
+ if (ALLOWED_HOST_ORIGINS.has(origin))
4726
+ return true;
4727
+ try {
4728
+ return new URL(origin).hostname === 'localhost';
4729
+ }
4730
+ catch {
4731
+ console.warn('isValidHostOrigin: received a malformed origin URL', origin);
4732
+ return false;
4733
+ }
4734
+ }
4735
+ function isTokenExpired(tokenInfo) {
4736
+ if (!tokenInfo?.expiresAt)
4737
+ return true;
4738
+ return new Date() >= tokenInfo.expiresAt;
4739
+ }
4740
+ /**
4741
+ * Waits for the next window message that satisfies `filter`.
4742
+ * Rejects if the AbortSignal fires before a matching message arrives.
4743
+ */
4744
+ function waitForMessage(filter, signal) {
4745
+ return new Promise((resolve, reject) => {
4746
+ const handler = (event) => {
4747
+ if (!filter(event))
4748
+ return;
4749
+ window.removeEventListener('message', handler);
4750
+ resolve(event);
4751
+ };
4752
+ signal.addEventListener('abort', () => {
4753
+ window.removeEventListener('message', handler);
4754
+ reject(signal.reason);
4755
+ }, { once: true });
4756
+ window.addEventListener('message', handler);
4757
+ });
4758
+ }
4759
+ /**
4760
+ * Sends a token-refresh request to a parent host frame and waits for the
4761
+ * response. Handles timeout, origin filtering, and listener cleanup.
4762
+ *
4763
+ * Both ActionCenterTokenManager and EmbeddedTokenManager delegate to this
4764
+ * function; they differ only in the event names and message shape they use.
4765
+ */
4766
+ function requestHostToken(options) {
4767
+ const { pinnedOrigin, sendRequest, responseEventType, extractToken, onTokenRefreshed } = options;
4768
+ const controller = new AbortController();
4769
+ const cancel = () => controller.abort(new AuthenticationError({
4770
+ message: 'Token refresh cancelled',
4771
+ statusCode: HttpStatus.UNAUTHORIZED,
4772
+ }));
4773
+ const promise = (async () => {
4774
+ const timer = setTimeout(() => controller.abort(new AuthenticationError({
4775
+ message: `Token refresh timed out after ${AUTHENTICATION_TIMEOUT}ms waiting for host response`,
4776
+ statusCode: HttpStatus.UNAUTHORIZED,
4777
+ })), AUTHENTICATION_TIMEOUT);
4778
+ try {
4779
+ // Register listener before sending — avoids any race between send and response
4780
+ const responsePromise = waitForMessage(event => event.origin === pinnedOrigin && event.data?.eventType === responseEventType, controller.signal);
4781
+ sendRequest();
4782
+ const event = await responsePromise;
4783
+ const token = extractToken(event.data);
4784
+ if (!token) {
4785
+ throw new AuthenticationError({
4786
+ message: 'Host responded but did not include a valid access token',
4787
+ statusCode: HttpStatus.UNAUTHORIZED,
4788
+ });
4789
+ }
4790
+ // type: 'secret' intentionally prevents the SDK's internal OAuth refresh path
4791
+ // from running — the host manager owns the refresh cycle via requestHostToken.
4792
+ // This mirrors the same pattern used by ActionCenterTokenManager.
4793
+ onTokenRefreshed({ token: token.accessToken, type: 'secret', expiresAt: token.expiresAt });
4794
+ return token.accessToken;
4795
+ }
4796
+ finally {
4797
+ clearTimeout(timer);
4798
+ }
4799
+ })();
4800
+ return { promise, cancel };
4801
+ }
4802
+
4679
4803
  class ActionCenterTokenManager {
4680
4804
  constructor(config, onTokenRefreshed) {
4681
4805
  this.config = config;
@@ -4684,84 +4808,334 @@ class ActionCenterTokenManager {
4684
4808
  this.refreshPromise = null;
4685
4809
  }
4686
4810
  async refreshAccessToken(tokenInfo) {
4687
- if (!this.isTokenExpired(tokenInfo)) {
4811
+ if (!isTokenExpired(tokenInfo)) {
4688
4812
  return tokenInfo.token;
4689
4813
  }
4690
4814
  if (this.refreshPromise) {
4691
4815
  return this.refreshPromise;
4692
4816
  }
4693
- this.refreshPromise = new Promise((resolve, reject) => {
4694
- const content = {
4817
+ const parentOrigin = this.parentOrigin;
4818
+ if (!parentOrigin) {
4819
+ return Promise.reject(new AuthenticationError({
4820
+ message: 'Cannot refresh token: basedomain query parameter is missing',
4821
+ statusCode: HttpStatus.UNAUTHORIZED,
4822
+ }));
4823
+ }
4824
+ // Guard before requestHostToken registers the inbound listener — an untrusted
4825
+ // basedomain would otherwise leave the listener live for the full timeout window,
4826
+ // accepting a forged TOKENREFRESHED from that origin.
4827
+ if (!isValidHostOrigin(parentOrigin)) {
4828
+ return Promise.reject(new AuthenticationError({
4829
+ message: 'Cannot refresh token: basedomain is not a trusted UiPath host origin',
4830
+ statusCode: HttpStatus.UNAUTHORIZED,
4831
+ }));
4832
+ }
4833
+ const { promise } = requestHostToken({
4834
+ pinnedOrigin: parentOrigin,
4835
+ sendRequest: () => this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, {
4695
4836
  clientId: this.config.clientId,
4696
4837
  scope: this.config.scope,
4697
- };
4698
- this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, content);
4699
- const messageListener = (event) => {
4700
- if (event.origin !== this.parentOrigin)
4701
- return;
4702
- if (event.data?.eventType !== ActionCenterEventNames.TOKENREFRESHED)
4703
- return;
4704
- clearTimeout(timer);
4705
- if (event.data?.content?.token) {
4706
- const { accessToken, expiresAt } = event.data.content.token;
4707
- this.onTokenRefreshed({ token: accessToken, type: 'secret', expiresAt });
4708
- resolve(accessToken);
4709
- }
4710
- else {
4711
- reject(new AuthenticationError({
4712
- message: 'Failed to fetch access token',
4713
- statusCode: HttpStatus.UNAUTHORIZED,
4714
- }));
4715
- }
4716
- this.refreshPromise = null;
4717
- this.cleanup(messageListener);
4718
- };
4719
- const timer = setTimeout(() => {
4720
- reject(new AuthenticationError({
4721
- message: 'Failed to fetch access token',
4722
- statusCode: HttpStatus.UNAUTHORIZED,
4723
- }));
4724
- this.refreshPromise = null;
4725
- this.cleanup(messageListener);
4726
- }, AUTHENTICATION_TIMEOUT);
4727
- window.addEventListener('message', messageListener);
4838
+ }),
4839
+ responseEventType: ActionCenterEventNames.TOKENREFRESHED,
4840
+ extractToken: (data) => {
4841
+ const token = data?.content?.token;
4842
+ if (!token?.accessToken)
4843
+ return undefined;
4844
+ return { accessToken: token.accessToken, expiresAt: token.expiresAt };
4845
+ },
4846
+ onTokenRefreshed: this.onTokenRefreshed,
4728
4847
  });
4729
- return this.refreshPromise;
4730
- }
4731
- isTokenExpired(tokenInfo) {
4732
- if (!tokenInfo?.expiresAt) {
4733
- return true;
4848
+ this.refreshPromise = promise;
4849
+ try {
4850
+ return await this.refreshPromise;
4851
+ }
4852
+ finally {
4853
+ this.refreshPromise = null;
4734
4854
  }
4735
- return new Date() >= tokenInfo.expiresAt;
4736
4855
  }
4737
4856
  sendMessageToParent(eventType, content) {
4738
- if (window.parent && this.isValidOrigin(this.parentOrigin)) {
4857
+ if (window.parent && isValidHostOrigin(this.parentOrigin)) {
4739
4858
  try {
4740
4859
  window.parent.postMessage({ eventType, content }, this.parentOrigin);
4741
4860
  }
4742
4861
  catch (error) {
4743
- console.warn('Failed to send message to Action Center', JSON.stringify(error));
4862
+ console.warn('ActionCenterTokenManager: postMessage to host failed', JSON.stringify(error));
4744
4863
  }
4745
4864
  }
4746
4865
  }
4747
- cleanup(messageListener) {
4748
- window.removeEventListener('message', messageListener);
4866
+ }
4867
+
4868
+ /**
4869
+ * Event names and payload types for the UIP.* postMessage protocol used
4870
+ * when a coded app is embedded inside a UiPath host (e.g. Governance Portal, Insights UI).
4871
+ *
4872
+ * Flow — app-initiated, mirrors the Action Center protocol:
4873
+ * App → Host: UIP.refreshToken (requests a token; carries clientId + scope
4874
+ * so the host knows which OAuth client to use)
4875
+ * Host → App: UIP.tokenRefreshed (delivers the access token)
4876
+ *
4877
+ * Detection: the host signals embedding via `?host=embed&basedomain=<origin>` in
4878
+ * the iframe src URL. No explicit init message from the host is required.
4879
+ */
4880
+ var UipEmbeddedEventNames;
4881
+ (function (UipEmbeddedEventNames) {
4882
+ UipEmbeddedEventNames["REFRESH_TOKEN"] = "UIP.refreshToken";
4883
+ UipEmbeddedEventNames["TOKEN_REFRESHED"] = "UIP.tokenRefreshed";
4884
+ })(UipEmbeddedEventNames || (UipEmbeddedEventNames = {}));
4885
+
4886
+ function parseExpiresAt(raw) {
4887
+ const d = new Date(raw);
4888
+ if (isNaN(d.getTime())) {
4889
+ console.warn('EmbeddedTokenManager: host sent a malformed expiresAt value — treating token as already expired', raw);
4890
+ return new Date(0);
4891
+ }
4892
+ return d;
4893
+ }
4894
+ function extractToken(data) {
4895
+ const token = data?.content?.token;
4896
+ if (!token?.accessToken)
4897
+ return undefined;
4898
+ return { accessToken: token.accessToken, expiresAt: parseExpiresAt(token.expiresAt) };
4899
+ }
4900
+ /**
4901
+ * Handles token delegation for coded apps embedded inside a UiPath host
4902
+ * (e.g. Governance Portal, Insights UI).
4903
+ *
4904
+ * Detection: the host signals embedding via `?host=embed&basedomain=<origin>`
4905
+ * in the iframe src URL. `parentOrigin` is read from `?basedomain=` and validated
4906
+ * against the trusted UiPath host allowlist before this manager is constructed.
4907
+ * This mirrors the mechanism used by ActionCenterTokenManager.
4908
+ *
4909
+ * On every token expiry the SDK sends `UIP.refreshToken` with `clientId` and
4910
+ * `scope`; the host performs silent SSO and responds with `UIP.tokenRefreshed`.
4911
+ */
4912
+ class EmbeddedTokenManager {
4913
+ /**
4914
+ * @param parentOrigin Validated UiPath host origin from the `?basedomain=` query parameter.
4915
+ * @param config SDK configuration — `clientId` and `scope` are required and forwarded
4916
+ * in every `UIP.refreshToken` request so the host knows which OAuth client to use.
4917
+ * @param onTokenRefreshed Called with the refreshed TokenInfo so the caller
4918
+ * can persist it in the execution context.
4919
+ * @throws {AuthenticationError} if `config.clientId` or `config.scope` are not set.
4920
+ */
4921
+ constructor(parentOrigin, config, onTokenRefreshed) {
4922
+ this.parentOrigin = parentOrigin;
4923
+ this.onTokenRefreshed = onTokenRefreshed;
4924
+ this.refreshPromise = null;
4925
+ this.cancelRefresh = null;
4926
+ if (!config.clientId || !config.scope) {
4927
+ throw new ValidationError({
4928
+ message: 'EmbeddedTokenManager requires clientId and scope to be configured for host-delegated authentication',
4929
+ });
4930
+ }
4931
+ this.clientId = config.clientId;
4932
+ this.scope = config.scope;
4749
4933
  }
4750
- isValidOrigin(origin) {
4751
- const ALLOWED_ORIGINS = ['https://alpha.uipath.com', 'https://staging.uipath.com', 'https://cloud.uipath.com'];
4752
- if (!origin) {
4753
- return false;
4934
+ async refreshAccessToken(tokenInfo) {
4935
+ if (!isTokenExpired(tokenInfo)) {
4936
+ return tokenInfo.token;
4754
4937
  }
4755
- if (ALLOWED_ORIGINS.includes(origin)) {
4756
- return true;
4938
+ if (this.refreshPromise) {
4939
+ return this.refreshPromise;
4757
4940
  }
4941
+ const { promise, cancel } = requestHostToken({
4942
+ pinnedOrigin: this.parentOrigin,
4943
+ sendRequest: () => {
4944
+ try {
4945
+ const message = {
4946
+ eventType: UipEmbeddedEventNames.REFRESH_TOKEN,
4947
+ content: { clientId: this.clientId, scope: this.scope },
4948
+ };
4949
+ window.parent.postMessage(message, this.parentOrigin);
4950
+ }
4951
+ catch (error) {
4952
+ console.warn('EmbeddedTokenManager: postMessage to host failed', error);
4953
+ }
4954
+ },
4955
+ responseEventType: UipEmbeddedEventNames.TOKEN_REFRESHED,
4956
+ extractToken,
4957
+ onTokenRefreshed: this.onTokenRefreshed,
4958
+ });
4959
+ this.cancelRefresh = cancel;
4960
+ this.refreshPromise = promise;
4758
4961
  try {
4759
- const url = new URL(origin);
4760
- return url.hostname === 'localhost';
4962
+ return await this.refreshPromise;
4761
4963
  }
4762
- catch {
4763
- return false;
4964
+ finally {
4965
+ this.refreshPromise = null;
4966
+ this.cancelRefresh = null;
4967
+ }
4968
+ }
4969
+ /** Cancels any in-flight token-refresh request. */
4970
+ destroy() {
4971
+ this.cancelRefresh?.();
4972
+ }
4973
+ }
4974
+
4975
+ /**
4976
+ * SDK Telemetry constants.
4977
+ *
4978
+ * Only the SDK's identity (version, service name, role name, …) lives
4979
+ * here. The Application Insights connection string is injected into
4980
+ * `@uipath/core-telemetry` itself at publish time, and the generic attribute
4981
+ * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
4982
+ * `@uipath/core-telemetry` and consumed there — they are not part of the
4983
+ * SDK's public API.
4984
+ */
4985
+ /** SDK version placeholder — patched by the SDK publish workflow. */
4986
+ const SDK_VERSION = '1.4.0';
4987
+ const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
4988
+ const SDK_SERVICE_NAME = 'UiPath.TypeScript.Sdk';
4989
+ const SDK_LOGGER_NAME = 'uipath-ts-sdk-telemetry';
4990
+ const SDK_RUN_EVENT = 'Sdk.Run';
4991
+
4992
+ /**
4993
+ * UiPath TypeScript SDK Telemetry
4994
+ *
4995
+ * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
4996
+ * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
4997
+ * does this independently, so events carry their own consumer's identity
4998
+ * and tenant context.
4999
+ */
5000
+ // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
5001
+ // same `TelemetryClient` instance at runtime. A single `initialize(...)`
5002
+ // from the `UiPath` constructor therefore wires up `@track` decorators
5003
+ // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
5004
+ const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
5005
+ const track = coreTelemetry.createTrack(sdkClient);
5006
+ const trackEvent = coreTelemetry.createTrackEvent(sdkClient);
5007
+ const telemetryClient = {
5008
+ initialize(context) {
5009
+ sdkClient.initialize({
5010
+ sdkVersion: SDK_VERSION,
5011
+ serviceName: SDK_SERVICE_NAME,
5012
+ cloudRoleName: CLOUD_ROLE_NAME,
5013
+ loggerName: SDK_LOGGER_NAME,
5014
+ defaultEventName: SDK_RUN_EVENT,
5015
+ context,
5016
+ });
5017
+ },
5018
+ /**
5019
+ * Sets the authenticated user's id so every subsequently emitted event
5020
+ * carries it as `CloudUserId`.
5021
+ */
5022
+ setUserId(userId) {
5023
+ sdkClient.setUserId(userId);
5024
+ },
5025
+ };
5026
+
5027
+ /**
5028
+ * Base64 encoding/decoding
5029
+ */
5030
+ /**
5031
+ * Encodes a string to base64
5032
+ * @param str - The string to encode
5033
+ * @returns Base64 encoded string
5034
+ */
5035
+ function encodeBase64(str) {
5036
+ // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
5037
+ const encoder = new TextEncoder();
5038
+ const data = encoder.encode(str);
5039
+ // Convert Uint8Array to base64
5040
+ if (isBrowser) {
5041
+ // Browser environment
5042
+ // Convert Uint8Array to binary string then to base64
5043
+ const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
5044
+ return btoa(binaryString);
5045
+ }
5046
+ else {
5047
+ // Node.js environment
5048
+ return Buffer.from(data).toString('base64');
5049
+ }
5050
+ }
5051
+ /**
5052
+ * Decodes a base64 string
5053
+ * @param base64 - The base64 string to decode
5054
+ * @returns Decoded string
5055
+ */
5056
+ function decodeBase64(base64) {
5057
+ let bytes;
5058
+ if (isBrowser) {
5059
+ // Browser environment
5060
+ const binaryString = atob(base64);
5061
+ bytes = new Uint8Array(binaryString.length);
5062
+ for (let i = 0; i < binaryString.length; i++) {
5063
+ bytes[i] = binaryString.charCodeAt(i);
5064
+ }
5065
+ }
5066
+ else {
5067
+ // Node.js environment
5068
+ bytes = new Uint8Array(Buffer.from(base64, 'base64'));
5069
+ }
5070
+ // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
5071
+ const decoder = new TextDecoder();
5072
+ return decoder.decode(bytes);
5073
+ }
5074
+
5075
+ /**
5076
+ * Encodes a folder path for the `X-UIPATH-FolderPath-Encoded` header.
5077
+ *
5078
+ * Orchestrator decodes this header as **base64-encoded UTF-16 LE bytes**
5079
+ * (see `HttpHeadersProviderExtensions.GetDecoded` + `OrganizationUnitProvider`
5080
+ * in the Orchestrator repo, which call `Encoding.Unicode.GetString(...)`).
5081
+ * URL-encoding is NOT what the server expects — it must be base64-of-UTF-16-LE
5082
+ * bytes.
5083
+ *
5084
+ * @param folderPath - The folder path (e.g. 'Shared/Finance')
5085
+ * @returns Base64 string suitable for the `X-UIPATH-FolderPath-Encoded` header
5086
+ */
5087
+ function encodeFolderPathHeader(folderPath) {
5088
+ // Force little-endian regardless of host byte order. `Uint16Array` viewed
5089
+ // as `Uint8Array` would use the host's native order — correct on LE hosts
5090
+ // (x86/ARM-LE) but wrong on BE hosts. `DataView.setUint16(..., true)`
5091
+ // pins LE.
5092
+ const buf = new ArrayBuffer(folderPath.length * 2);
5093
+ const view = new DataView(buf);
5094
+ for (let i = 0; i < folderPath.length; i++) {
5095
+ view.setUint16(i * 2, folderPath.charCodeAt(i), true);
5096
+ }
5097
+ const bytes = new Uint8Array(buf);
5098
+ let binary = '';
5099
+ for (let i = 0; i < bytes.byteLength; i++) {
5100
+ binary += String.fromCharCode(bytes[i]);
5101
+ }
5102
+ // btoa is browser-native; Node 16+ also has it as a global
5103
+ return btoa(binary);
5104
+ }
5105
+
5106
+ /**
5107
+ * JWT decoding helpers — payload inspection only, no signature verification.
5108
+ */
5109
+ const BASE64URL_DASH_RE = /-/g;
5110
+ const BASE64URL_UNDERSCORE_RE = /_/g;
5111
+ /**
5112
+ * Converts a base64url-encoded JWT segment to standard base64 with padding.
5113
+ */
5114
+ function base64UrlToBase64(value) {
5115
+ const base64 = value
5116
+ .replace(BASE64URL_DASH_RE, '+')
5117
+ .replace(BASE64URL_UNDERSCORE_RE, '/');
5118
+ return base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
5119
+ }
5120
+ /**
5121
+ * Extracts the user id (`sub` claim) from a JWT access token payload.
5122
+ * Returns an empty string for opaque (non-JWT) tokens or malformed payloads.
5123
+ *
5124
+ * @param token - The access token to inspect
5125
+ * @returns The user id, or an empty string if it cannot be extracted
5126
+ */
5127
+ function extractUserIdFromToken(token) {
5128
+ try {
5129
+ const payload = token.split('.')[1];
5130
+ if (!payload) {
5131
+ return '';
4764
5132
  }
5133
+ const claims = JSON.parse(decodeBase64(base64UrlToBase64(payload)));
5134
+ const sub = claims['sub'];
5135
+ return typeof sub === 'string' && sub ? sub : '';
5136
+ }
5137
+ catch {
5138
+ return '';
4765
5139
  }
4766
5140
  }
4767
5141
 
@@ -4784,10 +5158,15 @@ class TokenManager {
4784
5158
  this.isOAuth = isOAuth;
4785
5159
  this.refreshPromise = null;
4786
5160
  this.actionCenterTokenManager = null;
5161
+ this.embeddedTokenManager = null;
4787
5162
  if (isInActionCenter) {
4788
5163
  this.actionCenterTokenManager = new ActionCenterTokenManager(config, (tokenInfo) => this.setToken(tokenInfo));
4789
5164
  this.isOAuth = false;
4790
5165
  }
5166
+ else if (isHostEmbedded && embeddingOrigin && isValidHostOrigin(embeddingOrigin)) {
5167
+ this.embeddedTokenManager = new EmbeddedTokenManager(embeddingOrigin, config, tokenInfo => this.setToken(tokenInfo));
5168
+ this.isOAuth = false;
5169
+ }
4791
5170
  }
4792
5171
  /**
4793
5172
  * Checks if a token is expired
@@ -4818,6 +5197,10 @@ class TokenManager {
4818
5197
  if (this.actionCenterTokenManager) {
4819
5198
  return await this.actionCenterTokenManager.refreshAccessToken(tokenInfo);
4820
5199
  }
5200
+ // Generic embedded path — active whenever the app is embedded in a UiPath host page
5201
+ if (this.embeddedTokenManager) {
5202
+ return await this.embeddedTokenManager.refreshAccessToken(tokenInfo);
5203
+ }
4821
5204
  // For secret-based tokens, they never expire
4822
5205
  if (tokenInfo.type === 'secret') {
4823
5206
  return tokenInfo.token;
@@ -4956,6 +5339,13 @@ class TokenManager {
4956
5339
  }
4957
5340
  return true;
4958
5341
  }
5342
+ /**
5343
+ * Releases resources held by this instance.
5344
+ * Must be called when the TokenManager is no longer needed to prevent listener leaks.
5345
+ */
5346
+ destroy() {
5347
+ this.embeddedTokenManager?.destroy();
5348
+ }
4959
5349
  /**
4960
5350
  * Clears the current token
4961
5351
  */
@@ -4977,6 +5367,7 @@ class TokenManager {
4977
5367
  */
4978
5368
  _updateExecutionContext(tokenInfo) {
4979
5369
  this.executionContext.set('tokenInfo', tokenInfo);
5370
+ telemetryClient.setUserId(extractUserIdFromToken(tokenInfo.token));
4980
5371
  }
4981
5372
  /**
4982
5373
  * Refreshes the access token using the stored refresh token.
@@ -5006,6 +5397,9 @@ class TokenManager {
5006
5397
  * Internal method to perform the actual token refresh
5007
5398
  */
5008
5399
  async _doRefreshToken() {
5400
+ // Destructure before the type guard — hasOAuthConfig narrows this.config to
5401
+ // { clientId, redirectUri, scope } which does not include BaseConfig fields.
5402
+ const { orgName, baseUrl } = this.config;
5009
5403
  // Check if we're in OAuth flow
5010
5404
  if (!hasOAuthConfig(this.config)) {
5011
5405
  throw new Error('refreshAccessToken is only available in OAuth flow');
@@ -5015,13 +5409,12 @@ class TokenManager {
5015
5409
  if (!tokenInfo?.refreshToken) {
5016
5410
  throw new Error('No refresh token available. User may need to re-authenticate.');
5017
5411
  }
5018
- const orgName = this.config.orgName;
5019
5412
  const body = new URLSearchParams({
5020
5413
  grant_type: 'refresh_token',
5021
5414
  client_id: this.config.clientId,
5022
5415
  refresh_token: tokenInfo.refreshToken
5023
5416
  });
5024
- const response = await fetch(`${this.config.baseUrl}/${orgName}/identity_/connect/token`, {
5417
+ const response = await fetch(`${baseUrl}/${orgName}/identity_/connect/token`, {
5025
5418
  method: 'POST',
5026
5419
  headers: {
5027
5420
  'Content-Type': 'application/x-www-form-urlencoded'
@@ -5481,51 +5874,6 @@ function normalizeBaseUrl(url) {
5481
5874
  return url.endsWith('/') ? url.slice(0, -1) : url;
5482
5875
  }
5483
5876
 
5484
- /**
5485
- * SDK Telemetry constants.
5486
- *
5487
- * Only the SDK's identity (version, service name, role name, …) lives
5488
- * here. The Application Insights connection string is injected into
5489
- * `@uipath/core-telemetry` itself at publish time, and the generic attribute
5490
- * keys (`Version`, `Service`, `CloudOrganizationName`, …) are owned by
5491
- * `@uipath/core-telemetry` and consumed there — they are not part of the
5492
- * SDK's public API.
5493
- */
5494
- /** SDK version placeholder — patched by the SDK publish workflow. */
5495
- const SDK_VERSION = '1.3.10';
5496
- const CLOUD_ROLE_NAME = 'uipath-ts-sdk';
5497
- const SDK_SERVICE_NAME = 'UiPath.TypeScript.Sdk';
5498
- const SDK_LOGGER_NAME = 'uipath-ts-sdk-telemetry';
5499
- const SDK_RUN_EVENT = 'Sdk.Run';
5500
-
5501
- /**
5502
- * UiPath TypeScript SDK Telemetry
5503
- *
5504
- * Constructs the SDK's own `TelemetryClient` and binds the SDK-local
5505
- * `track` / `trackEvent` to it. Each consumer of `@uipath/core-telemetry`
5506
- * does this independently, so events carry their own consumer's identity
5507
- * and tenant context.
5508
- */
5509
- // Keyed by `CLOUD_ROLE_NAME` so every SDK subpath bundle resolves to the
5510
- // same `TelemetryClient` instance at runtime. A single `initialize(...)`
5511
- // from the `UiPath` constructor therefore wires up `@track` decorators
5512
- // across every subpath bundle (`assets`, `feedback`, `tasks`, …).
5513
- const sdkClient = coreTelemetry.getOrCreateClient(CLOUD_ROLE_NAME);
5514
- const track = coreTelemetry.createTrack(sdkClient);
5515
- const trackEvent = coreTelemetry.createTrackEvent(sdkClient);
5516
- const telemetryClient = {
5517
- initialize(context) {
5518
- sdkClient.initialize({
5519
- sdkVersion: SDK_VERSION,
5520
- serviceName: SDK_SERVICE_NAME,
5521
- cloudRoleName: CLOUD_ROLE_NAME,
5522
- loggerName: SDK_LOGGER_NAME,
5523
- defaultEventName: SDK_RUN_EVENT,
5524
- context,
5525
- });
5526
- },
5527
- };
5528
-
5529
5877
  /**
5530
5878
  * SDK Internals Registry - Internal registry for SDK instances
5531
5879
  *
@@ -5635,7 +5983,7 @@ function loadFromMetaTags() {
5635
5983
  return hasAnyValue ? config : null;
5636
5984
  }
5637
5985
 
5638
- var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_multiLogin, _UiPath_metaFolderKey, _UiPath_initializeWithConfig, _UiPath_loadConfig;
5986
+ var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_multiLogin, _UiPath_metaFolderKey, _UiPath_metaOrgId, _UiPath_metaTenantId, _UiPath_initializeWithConfig, _UiPath_loadConfig;
5639
5987
  /**
5640
5988
  * UiPath - Core SDK class for authentication and configuration management.
5641
5989
  *
@@ -5680,9 +6028,18 @@ let UiPath$1 = class UiPath {
5680
6028
  // deployments). Not accepted via the public constructor; lives here so the
5681
6029
  // SDK can flow it through to BaseService.config without polluting BaseConfig.
5682
6030
  _UiPath_metaFolderKey.set(this, void 0);
6031
+ // Org/tenant ids captured from the meta tags before the constructor config
6032
+ // is merged in. The `uipath:org-name`/`uipath:tenant-name` meta tags always
6033
+ // carry org/tenant *ids* in coded-app deployments, whereas a
6034
+ // constructor-supplied `orgName`/`tenantName` may be actual names — so the
6035
+ // telemetry ids must be read from the meta tags.
6036
+ _UiPath_metaOrgId.set(this, void 0);
6037
+ _UiPath_metaTenantId.set(this, void 0);
5683
6038
  // Load configuration from meta tags
5684
6039
  const configFromMetaTags = loadFromMetaTags();
5685
6040
  __classPrivateFieldSet(this, _UiPath_metaFolderKey, configFromMetaTags?.folderKey, "f");
6041
+ __classPrivateFieldSet(this, _UiPath_metaOrgId, configFromMetaTags?.orgName, "f");
6042
+ __classPrivateFieldSet(this, _UiPath_metaTenantId, configFromMetaTags?.tenantName, "f");
5686
6043
  // Merge configuration: constructor config overrides meta tags
5687
6044
  const mergedConfig = config ? { ...configFromMetaTags, ...config } : configFromMetaTags;
5688
6045
  if (mergedConfig && isCompleteConfig(mergedConfig)) {
@@ -5789,6 +6146,13 @@ let UiPath$1 = class UiPath {
5789
6146
  getToken() {
5790
6147
  return __classPrivateFieldGet(this, _UiPath_authService, "f")?.getToken();
5791
6148
  }
6149
+ /**
6150
+ * Releases resources held by this SDK instance.
6151
+ * Cancels any in-flight token-refresh request. Call this when the coded app is unmounted.
6152
+ */
6153
+ destroy() {
6154
+ __classPrivateFieldGet(this, _UiPath_authService, "f")?.getTokenManager()?.destroy();
6155
+ }
5792
6156
  /**
5793
6157
  * Logout from the SDK, clearing all authentication state.
5794
6158
  * After calling this method, the user will need to re-initialize to authenticate again.
@@ -5811,7 +6175,7 @@ let UiPath$1 = class UiPath {
5811
6175
  __classPrivateFieldGet(this, _UiPath_authService, "f")?.updateToken(tokenInfo);
5812
6176
  }
5813
6177
  };
5814
- _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap(), _UiPath_partialConfig = new WeakMap(), _UiPath_multiLogin = new WeakMap(), _UiPath_metaFolderKey = new WeakMap(), _UiPath_instances = new WeakSet(), _UiPath_initializeWithConfig = function _UiPath_initializeWithConfig(config) {
6178
+ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap(), _UiPath_partialConfig = new WeakMap(), _UiPath_multiLogin = new WeakMap(), _UiPath_metaFolderKey = new WeakMap(), _UiPath_metaOrgId = new WeakMap(), _UiPath_metaTenantId = new WeakMap(), _UiPath_instances = new WeakSet(), _UiPath_initializeWithConfig = function _UiPath_initializeWithConfig(config) {
5815
6179
  // Validate and normalize the configuration
5816
6180
  validateConfig(config);
5817
6181
  const hasSecretAuth = hasSecretConfig(config);
@@ -5847,9 +6211,11 @@ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_ini
5847
6211
  orgName: internalConfig.orgName,
5848
6212
  tenantName: internalConfig.tenantName
5849
6213
  };
5850
- // Initialize telemetry with SDK configuration
6214
+ // Initialize telemetry with SDK configuration.
5851
6215
  telemetryClient.initialize({
5852
6216
  baseUrl: config.baseUrl,
6217
+ orgId: __classPrivateFieldGet(this, _UiPath_metaOrgId, "f"),
6218
+ tenantId: __classPrivateFieldGet(this, _UiPath_metaTenantId, "f"),
5853
6219
  orgName: config.orgName,
5854
6220
  tenantName: config.tenantName,
5855
6221
  clientId: hasOAuthAuth ? config.clientId : undefined,
@@ -5868,6 +6234,8 @@ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_ini
5868
6234
  // Load from meta tags
5869
6235
  const metaConfig = loadFromMetaTags();
5870
6236
  __classPrivateFieldSet(this, _UiPath_metaFolderKey, metaConfig?.folderKey, "f");
6237
+ __classPrivateFieldSet(this, _UiPath_metaOrgId, metaConfig?.orgName, "f");
6238
+ __classPrivateFieldSet(this, _UiPath_metaTenantId, metaConfig?.tenantName, "f");
5871
6239
  // Merge with any partial config from constructor (constructor overrides meta tags)
5872
6240
  const merged = { ...metaConfig, ...__classPrivateFieldGet(this, _UiPath_partialConfig, "f") };
5873
6241
  if (!isCompleteConfig(merged)) {
@@ -6337,54 +6705,6 @@ function processODataArrayResponse(oDataResponse, successData) {
6337
6705
  };
6338
6706
  }
6339
6707
 
6340
- /**
6341
- * Base64 encoding/decoding
6342
- */
6343
- /**
6344
- * Encodes a string to base64
6345
- * @param str - The string to encode
6346
- * @returns Base64 encoded string
6347
- */
6348
- function encodeBase64(str) {
6349
- // TextEncoder for UTF-8 encoding (works in both browser and Node.js)
6350
- const encoder = new TextEncoder();
6351
- const data = encoder.encode(str);
6352
- // Convert Uint8Array to base64
6353
- if (isBrowser) {
6354
- // Browser environment
6355
- // Convert Uint8Array to binary string then to base64
6356
- const binaryString = Array.from(data, byte => String.fromCharCode(byte)).join('');
6357
- return btoa(binaryString);
6358
- }
6359
- else {
6360
- // Node.js environment
6361
- return Buffer.from(data).toString('base64');
6362
- }
6363
- }
6364
- /**
6365
- * Decodes a base64 string
6366
- * @param base64 - The base64 string to decode
6367
- * @returns Decoded string
6368
- */
6369
- function decodeBase64(base64) {
6370
- let bytes;
6371
- if (isBrowser) {
6372
- // Browser environment
6373
- const binaryString = atob(base64);
6374
- bytes = new Uint8Array(binaryString.length);
6375
- for (let i = 0; i < binaryString.length; i++) {
6376
- bytes[i] = binaryString.charCodeAt(i);
6377
- }
6378
- }
6379
- else {
6380
- // Node.js environment
6381
- bytes = new Uint8Array(Buffer.from(base64, 'base64'));
6382
- }
6383
- // TextDecoder for UTF-8 decoding (works in both browser and Node.js)
6384
- const decoder = new TextDecoder();
6385
- return decoder.decode(bytes);
6386
- }
6387
-
6388
6708
  /**
6389
6709
  * PaginationManager handles the conversion between uniform cursor-based pagination
6390
6710
  * and the specific pagination type for each service
@@ -7181,8 +7501,9 @@ class PaginationHelpers {
7181
7501
  });
7182
7502
  }
7183
7503
  // Extract and transform items from response
7184
- // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
7185
- const rawItems = Array.isArray(response.data) ? response.data : response.data?.[itemsField];
7504
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
7505
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
7506
+ const rawItems = Array.isArray(response.data) ? response.data : resolveNestedField(response.data, itemsField);
7186
7507
  const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
7187
7508
  const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
7188
7509
  // Parse items - automatically handle JSON string responses
@@ -7228,7 +7549,7 @@ class PaginationHelpers {
7228
7549
  getEndpoint: config.getEndpoint,
7229
7550
  folderId,
7230
7551
  headers: config.headers,
7231
- paginationParams: cursor ? { cursor, pageSize } : jumpToPage ? { jumpToPage, pageSize } : { pageSize },
7552
+ paginationParams: cursor ? { cursor, pageSize } : jumpToPage !== undefined ? { jumpToPage, pageSize } : { pageSize },
7232
7553
  additionalParams: prefixedOptions,
7233
7554
  transformFn: config.transformFn,
7234
7555
  method: config.method,
@@ -7431,6 +7752,8 @@ class BaseService {
7431
7752
  // When true (default), converts pageNumber to a skip/offset value (e.g., page 3 with pageSize 10 → skip 20).
7432
7753
  // When false, passes pageNumber directly as the offset param — used by APIs that accept a page number instead of a record offset.
7433
7754
  const convertToSkip = paginationParams?.convertToSkip ?? true;
7755
+ // When true, sends pageNumber - 1 (for 0-based APIs). Default false (1-based).
7756
+ const zeroBased = paginationParams?.zeroBased ?? false;
7434
7757
  requestParams[pageSizeParam] = limitedPageSize;
7435
7758
  if (convertToSkip) {
7436
7759
  if (params.pageNumber && params.pageNumber > 1) {
@@ -7438,7 +7761,8 @@ class BaseService {
7438
7761
  }
7439
7762
  }
7440
7763
  else {
7441
- requestParams[offsetParam] = params.pageNumber || 1;
7764
+ const sdkPageNumber = params.pageNumber || 1;
7765
+ requestParams[offsetParam] = zeroBased ? sdkPageNumber - 1 : sdkPageNumber;
7442
7766
  }
7443
7767
  {
7444
7768
  requestParams[countParam] = true;
@@ -7467,8 +7791,9 @@ class BaseService {
7467
7791
  const totalCountField = fields.totalCountField || 'totalRecordCount';
7468
7792
  const continuationTokenField = fields.continuationTokenField || 'continuationToken';
7469
7793
  // Extract items and metadata
7470
- // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N })
7471
- const items = Array.isArray(response.data) ? response.data : (response.data[itemsField] || []);
7794
+ // Handle both plain array responses and envelope responses ({ value: [...], totalRecordCount: N }).
7795
+ // itemsField may be a dotted path (e.g. 'data.agents') for nested envelopes.
7796
+ const items = Array.isArray(response.data) ? response.data : (resolveNestedField(response.data, itemsField) || []);
7472
7797
  const rawTotalCount = Array.isArray(response.data) ? undefined : resolveNestedField(response.data, totalCountField);
7473
7798
  const totalCount = typeof rawTotalCount === 'number' ? rawTotalCount : undefined;
7474
7799
  const continuationToken = response.data[continuationTokenField];
@@ -7551,12 +7876,12 @@ function createEntityMethods(entityData, service) {
7551
7876
  throw new Error('Entity ID is undefined');
7552
7877
  return service.deleteRecordsById(entityData.id, recordIds, options);
7553
7878
  },
7554
- async deleteRecord(recordId) {
7879
+ async deleteRecord(recordId, options) {
7555
7880
  if (!entityData.id)
7556
7881
  throw new Error('Entity ID is undefined');
7557
7882
  if (!recordId)
7558
7883
  throw new Error('Record ID is undefined');
7559
- return service.deleteRecordById(entityData.id, recordId);
7884
+ return service.deleteRecordById(entityData.id, recordId, options);
7560
7885
  },
7561
7886
  async getAllRecords(options) {
7562
7887
  if (!entityData.id)
@@ -7570,30 +7895,30 @@ function createEntityMethods(entityData, service) {
7570
7895
  throw new Error('Record ID is undefined');
7571
7896
  return service.getRecordById(entityData.id, recordId, options);
7572
7897
  },
7573
- async downloadAttachment(recordId, fieldName) {
7898
+ async downloadAttachment(recordId, fieldName, options) {
7574
7899
  if (!entityData.id)
7575
7900
  throw new Error('Entity ID is undefined');
7576
- return service.downloadAttachment(entityData.id, recordId, fieldName);
7901
+ return service.downloadAttachment(entityData.id, recordId, fieldName, options);
7577
7902
  },
7578
7903
  async uploadAttachment(recordId, fieldName, file, options) {
7579
7904
  if (!entityData.id)
7580
7905
  throw new Error('Entity ID is undefined');
7581
7906
  return service.uploadAttachment(entityData.id, recordId, fieldName, file, options);
7582
7907
  },
7583
- async deleteAttachment(recordId, fieldName) {
7908
+ async deleteAttachment(recordId, fieldName, options) {
7584
7909
  if (!entityData.id)
7585
7910
  throw new Error('Entity ID is undefined');
7586
- return service.deleteAttachment(entityData.id, recordId, fieldName);
7911
+ return service.deleteAttachment(entityData.id, recordId, fieldName, options);
7587
7912
  },
7588
7913
  async queryRecords(options) {
7589
7914
  if (!entityData.id)
7590
7915
  throw new Error('Entity ID is undefined');
7591
7916
  return service.queryRecordsById(entityData.id, options);
7592
7917
  },
7593
- async importRecords(file) {
7918
+ async importRecords(file, options) {
7594
7919
  if (!entityData.id)
7595
7920
  throw new Error('Entity ID is undefined');
7596
- return service.importRecordsById(entityData.id, file);
7921
+ return service.importRecordsById(entityData.id, file, options);
7597
7922
  },
7598
7923
  async insert(data, options) {
7599
7924
  return this.insertRecord(data, options);
@@ -7604,10 +7929,10 @@ function createEntityMethods(entityData, service) {
7604
7929
  async getRecords(options) {
7605
7930
  return this.getAllRecords(options);
7606
7931
  },
7607
- async delete() {
7932
+ async delete(options) {
7608
7933
  if (!entityData.id)
7609
7934
  throw new Error('Entity ID is undefined');
7610
- return service.deleteById(entityData.id);
7935
+ return service.deleteById(entityData.id, options);
7611
7936
  },
7612
7937
  async update(options) {
7613
7938
  if (!entityData.id)
@@ -7937,6 +8262,7 @@ class EntityService extends BaseService {
7937
8262
  * Gets entity metadata by entity ID with attached operation methods
7938
8263
  *
7939
8264
  * @param id - UUID of the entity
8265
+ * @param options - Optional {@link EntityGetByIdOptions} (e.g. `folderKey` for folder-scoped entities)
7940
8266
  * @returns Promise resolving to entity metadata with schema information and operation methods
7941
8267
  *
7942
8268
  * @example
@@ -7946,6 +8272,9 @@ class EntityService extends BaseService {
7946
8272
  * const entities = new Entities(sdk);
7947
8273
  * const entity = await entities.getById("<entityId>");
7948
8274
  *
8275
+ * // Folder-scoped: pass the entity's folder key
8276
+ * const folderEntity = await entities.getById("<entityId>", { folderKey: "<folderKey>" });
8277
+ *
7949
8278
  * // Call operations directly on the entity
7950
8279
  * const records = await entity.getAllRecords();
7951
8280
  *
@@ -7959,9 +8288,9 @@ class EntityService extends BaseService {
7959
8288
  * ]);
7960
8289
  * ```
7961
8290
  */
7962
- async getById(id) {
8291
+ async getById(id, options) {
7963
8292
  // Get entity metadata
7964
- const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_BY_ID(id));
8293
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_BY_ID(id), { headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }) });
7965
8294
  // Apply EntityMap transformations
7966
8295
  const metadata = transformData(response.data, EntityMap);
7967
8296
  // Transform metadata with field mappers
@@ -8004,9 +8333,14 @@ class EntityService extends BaseService {
8004
8333
  * ```
8005
8334
  */
8006
8335
  async getAllRecords(entityId, options) {
8336
+ // folderKey is header-only — destructure it out so PaginationHelpers doesn't serialise it
8337
+ // into the query string as $folderKey.
8338
+ const { folderKey, ...rest } = options ?? {};
8339
+ const downstreamOptions = options === undefined ? undefined : rest;
8007
8340
  return PaginationHelpers.getAll({
8008
8341
  serviceAccess: this.createPaginationServiceAccess(),
8009
8342
  getEndpoint: () => DATA_FABRIC_ENDPOINTS.ENTITY.GET_ENTITY_RECORDS(entityId),
8343
+ headers: createHeaders({ [FOLDER_KEY]: folderKey }),
8010
8344
  pagination: {
8011
8345
  paginationType: PaginationType.OFFSET,
8012
8346
  itemsField: ENTITY_PAGINATION.ITEMS_FIELD,
@@ -8018,7 +8352,7 @@ class EntityService extends BaseService {
8018
8352
  }
8019
8353
  },
8020
8354
  excludeFromPrefix: ['expansionLevel'] // Don't add ODATA prefix to expansionLevel
8021
- }, options);
8355
+ }, downstreamOptions);
8022
8356
  }
8023
8357
  /**
8024
8358
  * Gets a single entity record by entity ID and record ID
@@ -8043,7 +8377,7 @@ class EntityService extends BaseService {
8043
8377
  const params = createParams({
8044
8378
  expansionLevel: options.expansionLevel
8045
8379
  });
8046
- const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_RECORD_BY_ID(entityId, recordId), { params });
8380
+ const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_RECORD_BY_ID(entityId, recordId), { params, headers: createHeaders({ [FOLDER_KEY]: options.folderKey }) });
8047
8381
  return response.data;
8048
8382
  }
8049
8383
  /**
@@ -8075,7 +8409,7 @@ class EntityService extends BaseService {
8075
8409
  });
8076
8410
  const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.INSERT_BY_ID(id), data, {
8077
8411
  params,
8078
- ...options
8412
+ headers: createHeaders({ [FOLDER_KEY]: options.folderKey }),
8079
8413
  });
8080
8414
  return response.data;
8081
8415
  }
@@ -8116,7 +8450,7 @@ class EntityService extends BaseService {
8116
8450
  });
8117
8451
  const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.BATCH_INSERT_BY_ID(id), data, {
8118
8452
  params,
8119
- ...options
8453
+ headers: createHeaders({ [FOLDER_KEY]: options.folderKey }),
8120
8454
  });
8121
8455
  return response.data;
8122
8456
  }
@@ -8150,7 +8484,7 @@ class EntityService extends BaseService {
8150
8484
  });
8151
8485
  const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPDATE_RECORD_BY_ID(entityId, recordId), data, {
8152
8486
  params,
8153
- ...options
8487
+ headers: createHeaders({ [FOLDER_KEY]: options.folderKey }),
8154
8488
  });
8155
8489
  return response.data;
8156
8490
  }
@@ -8192,7 +8526,7 @@ class EntityService extends BaseService {
8192
8526
  });
8193
8527
  const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPDATE_BY_ID(id), data, {
8194
8528
  params,
8195
- ...options
8529
+ headers: createHeaders({ [FOLDER_KEY]: options.folderKey }),
8196
8530
  });
8197
8531
  return response.data;
8198
8532
  }
@@ -8224,7 +8558,7 @@ class EntityService extends BaseService {
8224
8558
  });
8225
8559
  const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_BY_ID(id), recordIds, {
8226
8560
  params,
8227
- ...options
8561
+ headers: createHeaders({ [FOLDER_KEY]: options.folderKey }),
8228
8562
  });
8229
8563
  return response.data;
8230
8564
  }
@@ -8236,6 +8570,7 @@ class EntityService extends BaseService {
8236
8570
  *
8237
8571
  * @param entityId - UUID of the entity
8238
8572
  * @param recordId - UUID of the record to delete
8573
+ * @param options - Optional {@link EntityDeleteRecordByIdOptions} (e.g. `folderKey` for folder-scoped entities)
8239
8574
  * @returns Promise resolving to void on success
8240
8575
  * @example
8241
8576
  * ```typescript
@@ -8244,10 +8579,13 @@ class EntityService extends BaseService {
8244
8579
  * const entities = new Entities(sdk);
8245
8580
  *
8246
8581
  * await entities.deleteRecordById("<entityId>", "<recordId>");
8582
+ *
8583
+ * // Folder-scoped: pass the entity's folder key
8584
+ * await entities.deleteRecordById("<entityId>", "<recordId>", { folderKey: "<folderKey>" });
8247
8585
  * ```
8248
8586
  */
8249
- async deleteRecordById(entityId, recordId) {
8250
- await this.delete(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_RECORD_BY_ID(entityId, recordId));
8587
+ async deleteRecordById(entityId, recordId, options) {
8588
+ await this.delete(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_RECORD_BY_ID(entityId, recordId), { headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }) });
8251
8589
  }
8252
8590
  /**
8253
8591
  * Gets all entities in the system
@@ -8333,10 +8671,15 @@ class EntityService extends BaseService {
8333
8671
  * ```
8334
8672
  */
8335
8673
  async queryRecordsById(id, options) {
8674
+ // folderKey is header-only — destructure it out so PaginationHelpers doesn't include
8675
+ // it in the POST body alongside the query filters.
8676
+ const { folderKey, ...rest } = options ?? {};
8677
+ const downstreamOptions = options === undefined ? undefined : rest;
8336
8678
  return PaginationHelpers.getAll({
8337
8679
  serviceAccess: this.createPaginationServiceAccess(),
8338
8680
  getEndpoint: () => DATA_FABRIC_ENDPOINTS.ENTITY.QUERY_BY_ID(id),
8339
8681
  method: HTTP_METHODS.POST,
8682
+ headers: createHeaders({ [FOLDER_KEY]: folderKey }),
8340
8683
  pagination: {
8341
8684
  paginationType: PaginationType.OFFSET,
8342
8685
  itemsField: ENTITY_PAGINATION.ITEMS_FIELD,
@@ -8348,13 +8691,14 @@ class EntityService extends BaseService {
8348
8691
  }
8349
8692
  },
8350
8693
  excludeFromPrefix: ['expansionLevel', 'filterGroup', 'selectedFields', 'sortOptions', 'aggregates', 'groupBy']
8351
- }, options);
8694
+ }, downstreamOptions);
8352
8695
  }
8353
8696
  /**
8354
8697
  * Imports records from a CSV file into an entity
8355
8698
  *
8356
8699
  * @param id - UUID of the entity
8357
8700
  * @param file - CSV file to import (Blob, File, or Uint8Array)
8701
+ * @param options - Optional {@link EntityImportRecordsByIdOptions} (e.g. `folderKey` for folder-scoped entities)
8358
8702
  * @returns Promise resolving to import result with record counts
8359
8703
  *
8360
8704
  * @example
@@ -8375,10 +8719,12 @@ class EntityService extends BaseService {
8375
8719
  * if (result.errorFileLink) {
8376
8720
  * console.log(`Error file link: ${result.errorFileLink}`);
8377
8721
  * }
8722
+ *
8723
+ * // Folder-scoped entity: pass the entity's folder key
8724
+ * await entities.importRecordsById("<entityId>", fileInput.files[0], { folderKey: "<folderKey>" });
8378
8725
  * ```
8379
- * @internal
8380
8726
  */
8381
- async importRecordsById(id, file) {
8727
+ async importRecordsById(id, file, options) {
8382
8728
  const formData = new FormData();
8383
8729
  if (file instanceof Uint8Array) {
8384
8730
  formData.append('file', new Blob([file.buffer]));
@@ -8386,7 +8732,7 @@ class EntityService extends BaseService {
8386
8732
  else {
8387
8733
  formData.append('file', file);
8388
8734
  }
8389
- const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.BULK_UPLOAD_BY_ID(id), formData);
8735
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.BULK_UPLOAD_BY_ID(id), formData, { headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }) });
8390
8736
  return response.data;
8391
8737
  }
8392
8738
  /**
@@ -8395,6 +8741,7 @@ class EntityService extends BaseService {
8395
8741
  * @param entityId - UUID of the entity
8396
8742
  * @param recordId - UUID of the record containing the attachment
8397
8743
  * @param fieldName - Name of the File-type field containing the attachment
8744
+ * @param options - Optional {@link EntityDownloadAttachmentOptions} (e.g. `folderKey` for folder-scoped entities)
8398
8745
  * @returns Promise resolving to Blob containing the file content
8399
8746
  *
8400
8747
  * @example
@@ -8413,11 +8760,15 @@ class EntityService extends BaseService {
8413
8760
  *
8414
8761
  * // Download attachment for a specific record and field
8415
8762
  * const blob = await entities.downloadAttachment(entityId, recordId, 'Documents');
8763
+ *
8764
+ * // Folder-scoped: pass the entity's folder key
8765
+ * const blob = await entities.downloadAttachment(entityId, recordId, 'Documents', { folderKey: "<folderKey>" });
8416
8766
  * ```
8417
8767
  */
8418
- async downloadAttachment(entityId, recordId, fieldName) {
8768
+ async downloadAttachment(entityId, recordId, fieldName, options) {
8419
8769
  const response = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.DOWNLOAD_ATTACHMENT(entityId, recordId, fieldName), {
8420
- responseType: RESPONSE_TYPES.BLOB
8770
+ responseType: RESPONSE_TYPES.BLOB,
8771
+ headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }),
8421
8772
  });
8422
8773
  return response.data;
8423
8774
  }
@@ -8428,7 +8779,7 @@ class EntityService extends BaseService {
8428
8779
  * @param recordId - UUID of the record to upload the attachment to
8429
8780
  * @param fieldName - Name of the File-type field
8430
8781
  * @param file - File to upload (Blob, File, or Uint8Array)
8431
- * @param options - Optional {@link EntityUploadAttachmentOptions} (e.g. expansionLevel)
8782
+ * @param options - Optional {@link EntityUploadAttachmentOptions} (e.g. `expansionLevel`, `folderKey` for folder-scoped entities)
8432
8783
  * @returns Promise resolving to {@link EntityUploadAttachmentResponse}
8433
8784
  *
8434
8785
  * @example
@@ -8447,6 +8798,9 @@ class EntityService extends BaseService {
8447
8798
  *
8448
8799
  * // Upload a file attachment
8449
8800
  * const response = await entities.uploadAttachment(entityId, recordId, 'Documents', file);
8801
+ *
8802
+ * // Folder-scoped entity: pass the entity's folder key
8803
+ * await entities.uploadAttachment(entityId, recordId, 'Documents', file, { folderKey: "<folderKey>" });
8450
8804
  * ```
8451
8805
  */
8452
8806
  async uploadAttachment(entityId, recordId, fieldName, file, options) {
@@ -8458,7 +8812,10 @@ class EntityService extends BaseService {
8458
8812
  formData.append('file', file);
8459
8813
  }
8460
8814
  const params = createParams({ expansionLevel: options?.expansionLevel });
8461
- const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPLOAD_ATTACHMENT(entityId, recordId, fieldName), formData, { params });
8815
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPLOAD_ATTACHMENT(entityId, recordId, fieldName), formData, {
8816
+ params,
8817
+ headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }),
8818
+ });
8462
8819
  return response.data;
8463
8820
  }
8464
8821
  /**
@@ -8467,6 +8824,7 @@ class EntityService extends BaseService {
8467
8824
  * @param entityId - UUID of the entity
8468
8825
  * @param recordId - UUID of the record containing the attachment
8469
8826
  * @param fieldName - Name of the File-type field containing the attachment
8827
+ * @param options - Optional {@link EntityDeleteAttachmentOptions} (e.g. `folderKey` for folder-scoped entities)
8470
8828
  * @returns Promise resolving to {@link EntityDeleteAttachmentResponse}
8471
8829
  *
8472
8830
  * @example
@@ -8485,10 +8843,13 @@ class EntityService extends BaseService {
8485
8843
  *
8486
8844
  * // Delete attachment for a specific record and field
8487
8845
  * await entities.deleteAttachment(entityId, recordId, 'Documents');
8846
+ *
8847
+ * // Folder-scoped: pass the entity's folder key
8848
+ * await entities.deleteAttachment(entityId, recordId, 'Documents', { folderKey: "<folderKey>" });
8488
8849
  * ```
8489
8850
  */
8490
- async deleteAttachment(entityId, recordId, fieldName) {
8491
- const response = await this.delete(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_ATTACHMENT(entityId, recordId, fieldName));
8851
+ async deleteAttachment(entityId, recordId, fieldName, options) {
8852
+ const response = await this.delete(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE_ATTACHMENT(entityId, recordId, fieldName), { headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }) });
8492
8853
  return response.data;
8493
8854
  }
8494
8855
  /**
@@ -8538,10 +8899,6 @@ class EntityService extends BaseService {
8538
8899
  * @internal
8539
8900
  */
8540
8901
  async create(name, fields, options) {
8541
- this.validateName(name, 'entity');
8542
- for (const field of fields) {
8543
- this.validateName(field.fieldName, 'field');
8544
- }
8545
8902
  const opts = options ?? {};
8546
8903
  const payload = {
8547
8904
  ...(opts.description !== undefined && { description: opts.description }),
@@ -8555,23 +8912,27 @@ class EntityService extends BaseService {
8555
8912
  externalFields: opts.externalFields ?? [],
8556
8913
  },
8557
8914
  };
8558
- const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPSERT, payload);
8915
+ const response = await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPSERT, payload, { headers: createHeaders({ [FOLDER_KEY]: opts.folderKey }) });
8559
8916
  return response.data;
8560
8917
  }
8561
8918
  /**
8562
8919
  * Deletes a Data Fabric entity and all its records
8563
8920
  *
8564
8921
  * @param id - UUID of the entity to delete
8922
+ * @param options - Optional {@link EntityDeleteByIdOptions} (e.g. `folderKey` for folder-scoped entities)
8565
8923
  * @returns Promise resolving when the entity is deleted
8566
8924
  *
8567
8925
  * @example
8568
8926
  * ```typescript
8569
8927
  * await entities.deleteById("<entityId>");
8928
+ *
8929
+ * // Folder-scoped: pass the entity's folder key
8930
+ * await entities.deleteById("<entityId>", { folderKey: "<folderKey>" });
8570
8931
  * ```
8571
8932
  * @internal
8572
8933
  */
8573
- async deleteById(id) {
8574
- await this.delete(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE(id));
8934
+ async deleteById(id, options) {
8935
+ await this.delete(DATA_FABRIC_ENDPOINTS.ENTITY.DELETE(id), { headers: createHeaders({ [FOLDER_KEY]: options?.folderKey }) });
8575
8936
  }
8576
8937
  /**
8577
8938
  * Updates an existing Data Fabric entity — schema and/or metadata.
@@ -8618,6 +8979,12 @@ class EntityService extends BaseService {
8618
8979
  * { id: "<fieldId>", lengthLimit: 1000 },
8619
8980
  * ],
8620
8981
  * });
8982
+ *
8983
+ * // Folder-scoped entity: add a field to an entity that lives in a non-tenant folder
8984
+ * await entities.updateById("<entityId>", {
8985
+ * folderKey: "<folderKey>",
8986
+ * addFields: [{ fieldName: "notes", type: EntityFieldDataType.MULTILINE_TEXT }],
8987
+ * });
8621
8988
  * ```
8622
8989
  * @internal
8623
8990
  */
@@ -8633,7 +9000,7 @@ class EntityService extends BaseService {
8633
9000
  ...(opts.displayName !== undefined && { displayName: opts.displayName }),
8634
9001
  ...(opts.description !== undefined && { description: opts.description }),
8635
9002
  ...(opts.isRbacEnabled !== undefined && { isRbacEnabled: opts.isRbacEnabled }),
8636
- });
9003
+ }, { headers: createHeaders({ [FOLDER_KEY]: opts.folderKey }) });
8637
9004
  }
8638
9005
  }
8639
9006
  /**
@@ -8644,7 +9011,8 @@ class EntityService extends BaseService {
8644
9011
  * @private
8645
9012
  */
8646
9013
  async applySchemaUpdate(entityId, options) {
8647
- const entityResponse = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_BY_ID(entityId));
9014
+ const folderHeaders = createHeaders({ [FOLDER_KEY]: options.folderKey });
9015
+ const entityResponse = await this.get(DATA_FABRIC_ENDPOINTS.ENTITY.GET_BY_ID(entityId), { headers: folderHeaders });
8648
9016
  const raw = entityResponse.data;
8649
9017
  // Carry forward existing non-system fields from GET response (skip system/primary-key fields)
8650
9018
  let fields = (raw.fields ?? [])
@@ -8684,6 +9052,7 @@ class EntityService extends BaseService {
8684
9052
  ...(update.isUnique !== undefined && { isUnique: update.isUnique }),
8685
9053
  ...(update.isRbacEnabled !== undefined && { isRbacEnabled: update.isRbacEnabled }),
8686
9054
  ...(update.isEncrypted !== undefined && { isEncrypted: update.isEncrypted }),
9055
+ ...(update.isHiddenField !== undefined && { isHiddenField: update.isHiddenField }),
8687
9056
  ...(update.defaultValue !== undefined && { defaultValue: update.defaultValue }),
8688
9057
  ...(hasConstraintUpdate && f.sqlType && { sqlType: { ...f.sqlType, ...constraintUpdate } }),
8689
9058
  };
@@ -8692,9 +9061,6 @@ class EntityService extends BaseService {
8692
9061
  // Build and append new fields
8693
9062
  const newFields = [];
8694
9063
  if (options.addFields?.length) {
8695
- for (const field of options.addFields) {
8696
- this.validateName(field.fieldName, 'field');
8697
- }
8698
9064
  newFields.push(...options.addFields.map(f => this.buildSchemaFieldPayload(f)));
8699
9065
  }
8700
9066
  await this.post(DATA_FABRIC_ENDPOINTS.ENTITY.UPSERT, {
@@ -8709,7 +9075,7 @@ class EntityService extends BaseService {
8709
9075
  isInsightsEnabled: raw.isInsightsEnabled ?? false,
8710
9076
  externalFields: raw.externalFields ?? [],
8711
9077
  },
8712
- });
9078
+ }, { headers: folderHeaders });
8713
9079
  }
8714
9080
  /**
8715
9081
  * Orchestrates all field mapping transformations
@@ -8795,9 +9161,15 @@ class EntityService extends BaseService {
8795
9161
  }
8796
9162
  /** Converts a user-facing EntityCreateFieldOptions to the raw API field payload */
8797
9163
  buildSchemaFieldPayload(field) {
8798
- this.validateName(field.fieldName, 'field');
8799
9164
  const fieldType = field.type ?? exports.EntityFieldDataType.STRING;
8800
9165
  this.validateFieldConstraints(fieldType, field, field.fieldName);
9166
+ const isRelationship = fieldType === exports.EntityFieldDataType.RELATIONSHIP;
9167
+ const isFile = fieldType === exports.EntityFieldDataType.FILE;
9168
+ if ((isRelationship || isFile) && (!field.referenceEntityId || !field.referenceFieldId)) {
9169
+ throw new ValidationError({
9170
+ message: `Field '${field.fieldName}' of type ${fieldType} requires both referenceEntityId and referenceFieldId (UUIDs of the target entity and field).`,
9171
+ });
9172
+ }
8801
9173
  const mapping = EntitySchemaFieldTypeMap[fieldType];
8802
9174
  return {
8803
9175
  name: field.fieldName,
@@ -8812,10 +9184,13 @@ class EntityService extends BaseService {
8812
9184
  isUnique: field.isUnique ?? false,
8813
9185
  isRbacEnabled: field.isRbacEnabled ?? false,
8814
9186
  isEncrypted: field.isEncrypted ?? false,
9187
+ isHiddenField: field.isHiddenField ?? false,
8815
9188
  ...(field.defaultValue !== undefined && { defaultValue: field.defaultValue }),
8816
9189
  ...(field.choiceSetId !== undefined && { choiceSetId: field.choiceSetId }),
8817
- ...(field.referenceEntityName !== undefined && { referenceEntityName: field.referenceEntityName }),
8818
- ...(field.referenceFieldName !== undefined && { referenceFieldName: field.referenceFieldName }),
9190
+ ...((isRelationship || isFile) && { isForeignKey: true }),
9191
+ ...(isRelationship && { referenceType: exports.ReferenceType.ManyToOne }),
9192
+ ...(field.referenceEntityId !== undefined && { referenceEntity: { id: field.referenceEntityId } }),
9193
+ ...(field.referenceFieldId !== undefined && { referenceField: { id: field.referenceFieldId } }),
8819
9194
  };
8820
9195
  }
8821
9196
  /**
@@ -8919,24 +9294,7 @@ class EntityService extends BaseService {
8919
9294
  return {};
8920
9295
  }
8921
9296
  }
8922
- validateName(name, context) {
8923
- if (name.length < 3 || name.length > 100 || !/^[a-zA-Z]\w*$/.test(name)) {
8924
- const suggestion = name.replace(/\W/g, '').replace(/^[0-9_]+/, '');
8925
- const defaultName = `My${context.charAt(0).toUpperCase() + context.slice(1)}`;
8926
- throw new ValidationError({
8927
- message: `Invalid ${context} name '${name}'. Must start with a letter, contain only letters, numbers, and underscores, 3–100 characters (e.g., "${suggestion || defaultName}").`
8928
- });
8929
- }
8930
- if (context === 'field' && EntityService.RESERVED_FIELD_NAMES.has(name)) {
8931
- throw new ValidationError({
8932
- message: `Field name '${name}' is reserved. Reserved names: ${[...EntityService.RESERVED_FIELD_NAMES].join(', ')}.`
8933
- });
8934
- }
8935
- }
8936
9297
  }
8937
- EntityService.RESERVED_FIELD_NAMES = new Set([
8938
- 'Id', 'CreatedBy', 'CreateTime', 'UpdatedBy', 'UpdateTime'
8939
- ]);
8940
9298
  __decorate([
8941
9299
  track('Entities.GetById')
8942
9300
  ], EntityService.prototype, "getById", null);
@@ -9309,6 +9667,13 @@ function createProcessMethods(processData, service) {
9309
9667
  if (!processData.folderKey)
9310
9668
  throw new Error('Folder key is undefined');
9311
9669
  return service.getIncidents(processData.processKey, processData.folderKey);
9670
+ },
9671
+ getElementStats(startTime, endTime, packageVersion) {
9672
+ if (!processData.processKey)
9673
+ throw new Error('Process key is undefined');
9674
+ if (!processData.packageId)
9675
+ throw new Error('Package ID is undefined');
9676
+ return service.getElementStats(processData.processKey, processData.packageId, startTime, endTime, packageVersion);
9312
9677
  }
9313
9678
  };
9314
9679
  }
@@ -9370,6 +9735,28 @@ async function fetchInstanceStatusTimeline(postFn, startTime, endTime, isCaseMan
9370
9735
  });
9371
9736
  return response.data ?? [];
9372
9737
  }
9738
+ /**
9739
+ * Builds the request body for the ElementCountByStatus endpoint.
9740
+ *
9741
+ * @param processKey - Process key to filter by
9742
+ * @param packageId - Package identifier
9743
+ * @param startTime - Start of the time range to query
9744
+ * @param endTime - End of the time range to query
9745
+ * @param packageVersion - Package version to filter by
9746
+ * @returns Request body for the ElementCountByStatus endpoint
9747
+ * @internal
9748
+ */
9749
+ function buildElementCountByStatusBody(processKey, packageId, startTime, endTime, packageVersion) {
9750
+ return {
9751
+ commonParams: {
9752
+ processKey,
9753
+ packageId,
9754
+ startTime: startTime.getTime(),
9755
+ endTime: endTime.getTime(),
9756
+ version: packageVersion
9757
+ }
9758
+ };
9759
+ }
9373
9760
 
9374
9761
  /**
9375
9762
  * Maps fields for Incident entities
@@ -9534,7 +9921,9 @@ function createProcessInstanceMethods(instanceData, service) {
9534
9921
  async getExecutionHistory() {
9535
9922
  if (!instanceData.instanceId)
9536
9923
  throw new Error('Process instance ID is undefined');
9537
- return service.getExecutionHistory(instanceData.instanceId);
9924
+ if (!instanceData.folderKey)
9925
+ throw new Error('Process instance folder key is undefined');
9926
+ return service.getExecutionHistory(instanceData.instanceId, instanceData.folderKey);
9538
9927
  },
9539
9928
  async getBpmn() {
9540
9929
  if (!instanceData.instanceId)
@@ -9600,6 +9989,40 @@ exports.DebugMode = void 0;
9600
9989
  DebugMode["SingleStep"] = "SingleStep";
9601
9990
  })(exports.DebugMode || (exports.DebugMode = {}));
9602
9991
 
9992
+ /**
9993
+ * Maestro Cases Models
9994
+ * Model classes for Maestro cases
9995
+ */
9996
+ /**
9997
+ * Creates methods for a case object
9998
+ *
9999
+ * @param caseData - The case data (response from API)
10000
+ * @param service - The cases service instance
10001
+ * @returns Object containing case methods
10002
+ */
10003
+ function createCaseMethods(caseData, service) {
10004
+ return {
10005
+ getElementStats(startTime, endTime, packageVersion) {
10006
+ if (!caseData.processKey)
10007
+ throw new Error('Process key is undefined');
10008
+ if (!caseData.packageId)
10009
+ throw new Error('Package ID is undefined');
10010
+ return service.getElementStats(caseData.processKey, caseData.packageId, startTime, endTime, packageVersion);
10011
+ }
10012
+ };
10013
+ }
10014
+ /**
10015
+ * Creates an actionable case by combining API case data with operational methods.
10016
+ *
10017
+ * @param caseData - The case data from API
10018
+ * @param service - The cases service instance
10019
+ * @returns A case object with added methods
10020
+ */
10021
+ function createCaseWithMethods(caseData, service) {
10022
+ const methods = createCaseMethods(caseData, service);
10023
+ return Object.assign({}, caseData, methods);
10024
+ }
10025
+
9603
10026
  /**
9604
10027
  * Case Instance Types
9605
10028
  * Types and interfaces for Maestro case instance management
@@ -9811,12 +10234,6 @@ const ProcessInstanceMap = {
9811
10234
  createdAt: 'createdTime',
9812
10235
  updatedAt: 'updatedTime'
9813
10236
  };
9814
- /**
9815
- * Maps fields for Process Instance Execution History to ensure consistent naming
9816
- */
9817
- const ProcessInstanceExecutionHistoryMap = {
9818
- startTime: 'startedTime'
9819
- };
9820
10237
 
9821
10238
  class ProcessInstancesService extends BaseService {
9822
10239
  /**
@@ -9897,11 +10314,66 @@ class ProcessInstancesService extends BaseService {
9897
10314
  /**
9898
10315
  * Get execution history (spans) for a process instance
9899
10316
  * @param instanceId The ID of the instance to get history for
9900
- * @returns Promise<ProcessInstanceExecutionHistoryResponse[]>
10317
+ * @param folderKey The folder key for authorization
10318
+ * @returns Promise resolving to execution history
10319
+ * {@link ProcessInstanceExecutionHistoryResponse}
10320
+ * @example
10321
+ * ```typescript
10322
+ * // Get execution history for a process instance
10323
+ * const history = await processInstances.getExecutionHistory(
10324
+ * <instanceId>,
10325
+ * <folderKey>
10326
+ * );
10327
+ *
10328
+ * // Analyze execution timeline
10329
+ * history.forEach(span => {
10330
+ * console.log(`Activity: ${span.name}`);
10331
+ * console.log(`Start: ${span.startedTime}`);
10332
+ * console.log(`End: ${span.endTime}`);
10333
+ * });
10334
+ * ```
9901
10335
  */
9902
- async getExecutionHistory(instanceId) {
9903
- const response = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_EXECUTION_HISTORY(instanceId));
9904
- return response.data.map(historyItem => transformData(historyItem, ProcessInstanceExecutionHistoryMap));
10336
+ async getExecutionHistory(instanceId, folderKey) {
10337
+ const headers = createHeaders({ [FOLDER_KEY]: folderKey });
10338
+ const elementExecResponse = await this.get(MAESTRO_ENDPOINTS.INSTANCES.GET_ELEMENT_EXECUTIONS(instanceId), { headers });
10339
+ const traceId = elementExecResponse.data.traceId;
10340
+ const spansResponse = await this.get(MAESTRO_ENDPOINTS.TRACES.GET_SPANS(traceId), { headers });
10341
+ // Build span lookup keyed by elementRunId extracted from Attributes JSON
10342
+ const spanMap = new Map();
10343
+ for (const span of spansResponse.data) {
10344
+ try {
10345
+ const attrs = span.Attributes ? JSON.parse(span.Attributes) : null;
10346
+ if (attrs?.elementRunId) {
10347
+ spanMap.set(attrs.elementRunId, span);
10348
+ }
10349
+ }
10350
+ catch {
10351
+ // skip spans with unparseable Attributes — they won't match any elementRunId
10352
+ }
10353
+ }
10354
+ const results = [];
10355
+ for (const elementExec of elementExecResponse.data.elementExecutions) {
10356
+ for (const run of elementExec.elementRuns) {
10357
+ const span = spanMap.get(run.elementRunId);
10358
+ if (span) {
10359
+ results.push(this.mapSpanToHistory(span));
10360
+ }
10361
+ }
10362
+ }
10363
+ return results;
10364
+ }
10365
+ mapSpanToHistory(span) {
10366
+ return {
10367
+ id: span.Id,
10368
+ traceId: span.TraceId,
10369
+ parentId: span.ParentId,
10370
+ name: span.Name,
10371
+ startedTime: span.StartTime,
10372
+ endTime: span.EndTime,
10373
+ attributes: span.Attributes,
10374
+ updatedTime: span.UpdatedAt,
10375
+ expiredTime: span.ExpiryTimeUtc,
10376
+ };
9905
10377
  }
9906
10378
  /**
9907
10379
  * Get BPMN XML file for a process instance
@@ -10217,6 +10689,52 @@ class MaestroProcessesService extends BaseService {
10217
10689
  const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_RUN_COUNT, buildInsightsTopBody(startTime, endTime, false, options));
10218
10690
  return (data ?? []).map(process => ({ ...process, name: process.packageId }));
10219
10691
  }
10692
+ /**
10693
+ * Get the top 10 BPMN elements ranked by failure count within a time range.
10694
+ *
10695
+ * Returns an array of up to 10 elements sorted by how many times they failed,
10696
+ * useful for identifying the most error-prone activities in processes.
10697
+ *
10698
+ * @param startTime - Start of the time range to query
10699
+ * @param endTime - End of the time range to query
10700
+ * @param options - Optional filters (packageId, processKey, version)
10701
+ * @returns Promise resolving to an array of {@link ElementGetTopFailedCountResponse}
10702
+ * @example
10703
+ * ```typescript
10704
+ * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes';
10705
+ *
10706
+ * const maestroProcesses = new MaestroProcesses(sdk);
10707
+ *
10708
+ * // Get top failing elements for the last 7 days
10709
+ * const topFailing = await maestroProcesses.getTopElementFailedCount(
10710
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
10711
+ * new Date()
10712
+ * );
10713
+ *
10714
+ * for (const element of topFailing) {
10715
+ * console.log(`${element.elementName} (${element.elementType}): ${element.failedCount} failures`);
10716
+ * }
10717
+ * ```
10718
+ *
10719
+ * @example
10720
+ * ```typescript
10721
+ * // Get top failing elements for a specific process
10722
+ * const filtered = await maestroProcesses.getTopElementFailedCount(
10723
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
10724
+ * new Date(),
10725
+ * { processKey: '<processKey>' }
10726
+ * );
10727
+ * ```
10728
+ */
10729
+ async getTopElementFailedCount(startTime, endTime, options) {
10730
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_ELEMENTS_WITH_FAILURE, buildInsightsTopBody(startTime, endTime, false, options));
10731
+ return (data ?? []).map(item => ({
10732
+ elementName: item.elementName,
10733
+ elementType: item.elementType,
10734
+ processKey: item.processKey,
10735
+ failedCount: item.count,
10736
+ }));
10737
+ }
10220
10738
  /**
10221
10739
  * Get all instances status counts aggregated by date for maestro processes.
10222
10740
  *
@@ -10347,6 +10865,41 @@ class MaestroProcessesService extends BaseService {
10347
10865
  const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_DURATION, buildInsightsTopBody(startTime, endTime, false, options));
10348
10866
  return (data ?? []).map(process => ({ ...process, name: process.packageId }));
10349
10867
  }
10868
+ /**
10869
+ * Get element stats for process instances
10870
+ *
10871
+ * Returns per-element execution counts (success, fail, terminated, paused, in-progress) and
10872
+ * duration percentile metrics (min, max, avg, p50, p95, p99) for BPMN elements within a process.
10873
+ *
10874
+ * @param processKey - Process key to filter by
10875
+ * @param packageId - Package identifier
10876
+ * @param startTime - Start of the time range to query
10877
+ * @param endTime - End of the time range to query
10878
+ * @param packageVersion - Package version to filter by
10879
+ * @returns Promise resolving to an array of {@link ElementStats}
10880
+ * @example
10881
+ * ```typescript
10882
+ * // Get element metrics for a process
10883
+ * const elements = await maestroProcesses.getElementStats(
10884
+ * '<processKey>',
10885
+ * '<packageId>',
10886
+ * new Date('2026-04-01'),
10887
+ * new Date(),
10888
+ * '1.0.1'
10889
+ * );
10890
+ *
10891
+ * // Analyze element performance
10892
+ * for (const element of elements) {
10893
+ * console.log(`Element: ${element.elementId}`);
10894
+ * console.log(` Success: ${element.successCount}, Failed: ${element.failCount}`);
10895
+ * console.log(` Avg duration: ${element.avgDurationMs}ms, P95: ${element.p95DurationMs}ms`);
10896
+ * }
10897
+ * ```
10898
+ */
10899
+ async getElementStats(processKey, packageId, startTime, endTime, packageVersion) {
10900
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.ELEMENT_COUNT_BY_STATUS, buildElementCountByStatusBody(processKey, packageId, startTime, endTime, packageVersion));
10901
+ return data ?? [];
10902
+ }
10350
10903
  }
10351
10904
  __decorate([
10352
10905
  track('MaestroProcesses.GetAll')
@@ -10357,6 +10910,9 @@ __decorate([
10357
10910
  __decorate([
10358
10911
  track('MaestroProcesses.GetTopRunCount')
10359
10912
  ], MaestroProcessesService.prototype, "getTopRunCount", null);
10913
+ __decorate([
10914
+ track('MaestroProcesses.GetTopElementFailedCount')
10915
+ ], MaestroProcessesService.prototype, "getTopElementFailedCount", null);
10360
10916
  __decorate([
10361
10917
  track('MaestroProcesses.GetInstanceStatusTimeline')
10362
10918
  ], MaestroProcessesService.prototype, "getInstanceStatusTimeline", null);
@@ -10366,6 +10922,9 @@ __decorate([
10366
10922
  __decorate([
10367
10923
  track('MaestroProcesses.GetTopExecutionDuration')
10368
10924
  ], MaestroProcessesService.prototype, "getTopExecutionDuration", null);
10925
+ __decorate([
10926
+ track('MaestroProcesses.GetElementStats')
10927
+ ], MaestroProcessesService.prototype, "getElementStats", null);
10369
10928
 
10370
10929
  /**
10371
10930
  * Service class for Maestro Process Incidents
@@ -10421,7 +10980,7 @@ var ProcessType;
10421
10980
  class CasesService extends BaseService {
10422
10981
  /**
10423
10982
  * Get all case management processes with their instance statistics
10424
- * @returns Promise resolving to array of Case objects
10983
+ * @returns Promise resolving to an array of {@link CaseGetAllWithMethodsResponse}
10425
10984
  *
10426
10985
  * @example
10427
10986
  * ```typescript
@@ -10445,10 +11004,10 @@ class CasesService extends BaseService {
10445
11004
  const response = await this.get(MAESTRO_ENDPOINTS.PROCESSES.GET_ALL, { params });
10446
11005
  // Extract processes array from response data and add name field
10447
11006
  const cases = response.data?.processes || [];
10448
- return cases.map(caseItem => ({
11007
+ return cases.map(caseItem => createCaseWithMethods({
10449
11008
  ...caseItem,
10450
11009
  name: this.extractCaseName(caseItem.packageId)
10451
- }));
11010
+ }, this));
10452
11011
  }
10453
11012
  /**
10454
11013
  * Get the top 5 case processes ranked by run count within a time range.
@@ -10491,6 +11050,52 @@ class CasesService extends BaseService {
10491
11050
  const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_RUN_COUNT, buildInsightsTopBody(startTime, endTime, true, options));
10492
11051
  return (data ?? []).map(process => ({ ...process, name: this.extractCaseName(process.packageId) }));
10493
11052
  }
11053
+ /**
11054
+ * Get the top 10 BPMN elements ranked by failure count within a time range.
11055
+ *
11056
+ * Returns an array of up to 10 elements sorted by how many times they failed,
11057
+ * useful for identifying the most error-prone activities in case processes.
11058
+ *
11059
+ * @param startTime - Start of the time range to query
11060
+ * @param endTime - End of the time range to query
11061
+ * @param options - Optional filters (packageId, processKey, version)
11062
+ * @returns Promise resolving to an array of {@link ElementGetTopFailedCountResponse}
11063
+ * @example
11064
+ * ```typescript
11065
+ * import { Cases } from '@uipath/uipath-typescript/cases';
11066
+ *
11067
+ * const cases = new Cases(sdk);
11068
+ *
11069
+ * // Get top failing elements for the last 7 days
11070
+ * const topFailing = await cases.getTopElementFailedCount(
11071
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
11072
+ * new Date()
11073
+ * );
11074
+ *
11075
+ * for (const element of topFailing) {
11076
+ * console.log(`${element.elementName} (${element.elementType}): ${element.failedCount} failures`);
11077
+ * }
11078
+ * ```
11079
+ *
11080
+ * @example
11081
+ * ```typescript
11082
+ * // Get top failing elements for a specific process
11083
+ * const filtered = await cases.getTopElementFailedCount(
11084
+ * new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
11085
+ * new Date(),
11086
+ * { processKey: '<processKey>' }
11087
+ * );
11088
+ * ```
11089
+ */
11090
+ async getTopElementFailedCount(startTime, endTime, options) {
11091
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_ELEMENTS_WITH_FAILURE, buildInsightsTopBody(startTime, endTime, true, options));
11092
+ return (data ?? []).map(item => ({
11093
+ elementName: item.elementName,
11094
+ elementType: item.elementType,
11095
+ processKey: item.processKey,
11096
+ failedCount: item.count,
11097
+ }));
11098
+ }
10494
11099
  /**
10495
11100
  * Get all instances status counts aggregated by date for case management processes.
10496
11101
  *
@@ -10621,6 +11226,40 @@ class CasesService extends BaseService {
10621
11226
  const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.TOP_PROCESSES_BY_DURATION, buildInsightsTopBody(startTime, endTime, true, options));
10622
11227
  return (data ?? []).map(process => ({ ...process, name: this.extractCaseName(process.packageId) }));
10623
11228
  }
11229
+ /**
11230
+ * Get element stats for case instances
11231
+ *
11232
+ * Returns per-element execution counts (success, fail, terminated, paused, in-progress) and
11233
+ * duration percentile metrics (min, max, avg, p50, p95, p99) for BPMN elements within a case.
11234
+ *
11235
+ * @param processKey - Process key to filter by
11236
+ * @param packageId - Package identifier
11237
+ * @param startTime - Start of the time range to query
11238
+ * @param endTime - End of the time range to query
11239
+ * @param packageVersion - Package version to filter by
11240
+ * @returns Promise resolving to an array of {@link ElementStats}
11241
+ * @example
11242
+ * ```typescript
11243
+ * // Get element metrics for a case
11244
+ * const elements = await cases.getElementStats(
11245
+ * '<processKey>',
11246
+ * '<packageId>',
11247
+ * new Date('2026-04-01'),
11248
+ * new Date(),
11249
+ * '1.0.1'
11250
+ * );
11251
+ *
11252
+ * // Find elements with failures
11253
+ * const failedElements = elements.filter(e => e.failCount > 0);
11254
+ * for (const element of failedElements) {
11255
+ * console.log(`Failed element: ${element.elementId}, failures: ${element.failCount}`);
11256
+ * }
11257
+ * ```
11258
+ */
11259
+ async getElementStats(processKey, packageId, startTime, endTime, packageVersion) {
11260
+ const { data } = await this.post(MAESTRO_ENDPOINTS.INSIGHTS.ELEMENT_COUNT_BY_STATUS, buildElementCountByStatusBody(processKey, packageId, startTime, endTime, packageVersion));
11261
+ return data ?? [];
11262
+ }
10624
11263
  /**
10625
11264
  * Extract a readable case name from the packageId
10626
11265
  * @param packageId - The full package identifier
@@ -10646,6 +11285,9 @@ __decorate([
10646
11285
  __decorate([
10647
11286
  track('Cases.GetTopRunCount')
10648
11287
  ], CasesService.prototype, "getTopRunCount", null);
11288
+ __decorate([
11289
+ track('Cases.GetTopElementFailedCount')
11290
+ ], CasesService.prototype, "getTopElementFailedCount", null);
10649
11291
  __decorate([
10650
11292
  track('Cases.GetInstanceStatusTimeline')
10651
11293
  ], CasesService.prototype, "getInstanceStatusTimeline", null);
@@ -10655,6 +11297,9 @@ __decorate([
10655
11297
  __decorate([
10656
11298
  track('Cases.GetTopExecutionDuration')
10657
11299
  ], CasesService.prototype, "getTopExecutionDuration", null);
11300
+ __decorate([
11301
+ track('Cases.GetElementStats')
11302
+ ], CasesService.prototype, "getElementStats", null);
10658
11303
 
10659
11304
  /**
10660
11305
  * Maps fields for Case Instance entities to ensure consistent naming
@@ -11863,37 +12508,6 @@ function validateName(resourceType, name) {
11863
12508
  return trimmed;
11864
12509
  }
11865
12510
 
11866
- /**
11867
- * Encodes a folder path for the `X-UIPATH-FolderPath-Encoded` header.
11868
- *
11869
- * Orchestrator decodes this header as **base64-encoded UTF-16 LE bytes**
11870
- * (see `HttpHeadersProviderExtensions.GetDecoded` + `OrganizationUnitProvider`
11871
- * in the Orchestrator repo, which call `Encoding.Unicode.GetString(...)`).
11872
- * URL-encoding is NOT what the server expects — it must be base64-of-UTF-16-LE
11873
- * bytes.
11874
- *
11875
- * @param folderPath - The folder path (e.g. 'Shared/Finance')
11876
- * @returns Base64 string suitable for the `X-UIPATH-FolderPath-Encoded` header
11877
- */
11878
- function encodeFolderPathHeader(folderPath) {
11879
- // Force little-endian regardless of host byte order. `Uint16Array` viewed
11880
- // as `Uint8Array` would use the host's native order — correct on LE hosts
11881
- // (x86/ARM-LE) but wrong on BE hosts. `DataView.setUint16(..., true)`
11882
- // pins LE.
11883
- const buf = new ArrayBuffer(folderPath.length * 2);
11884
- const view = new DataView(buf);
11885
- for (let i = 0; i < folderPath.length; i++) {
11886
- view.setUint16(i * 2, folderPath.charCodeAt(i), true);
11887
- }
11888
- const bytes = new Uint8Array(buf);
11889
- let binary = '';
11890
- for (let i = 0; i < bytes.byteLength; i++) {
11891
- binary += String.fromCharCode(bytes[i]);
11892
- }
11893
- // btoa is browser-native; Node 16+ also has it as a global
11894
- return btoa(binary);
11895
- }
11896
-
11897
12511
  /**
11898
12512
  * Resolves folder context into the appropriate Orchestrator folder headers.
11899
12513
  *
@@ -12041,6 +12655,26 @@ function describeFolderForError(folderId, folderKey, folderPath) {
12041
12655
  return '';
12042
12656
  }
12043
12657
 
12658
+ /**
12659
+ * Enum for Asset Value Scope
12660
+ */
12661
+ exports.AssetValueScope = void 0;
12662
+ (function (AssetValueScope) {
12663
+ AssetValueScope["Global"] = "Global";
12664
+ AssetValueScope["PerRobot"] = "PerRobot";
12665
+ })(exports.AssetValueScope || (exports.AssetValueScope = {}));
12666
+ /**
12667
+ * Enum for Asset Value Type
12668
+ */
12669
+ exports.AssetValueType = void 0;
12670
+ (function (AssetValueType) {
12671
+ AssetValueType["Text"] = "Text";
12672
+ AssetValueType["Bool"] = "Bool";
12673
+ AssetValueType["Integer"] = "Integer";
12674
+ AssetValueType["Credential"] = "Credential";
12675
+ AssetValueType["Secret"] = "Secret";
12676
+ })(exports.AssetValueType || (exports.AssetValueType = {}));
12677
+
12044
12678
  /**
12045
12679
  * Maps fields for Asset entities to ensure consistent naming
12046
12680
  */
@@ -12165,6 +12799,68 @@ class AssetService extends FolderScopedService {
12165
12799
  async getByName(name, options = {}) {
12166
12800
  return this.getByNameLookup('Asset', ASSET_ENDPOINTS.GET_BY_FOLDER, name, options, (raw) => transformData(pascalToCamelCaseKeys(raw), AssetMap));
12167
12801
  }
12802
+ /**
12803
+ * Updates the value of an existing asset by ID.
12804
+ *
12805
+ * Fetches the asset internally to determine its type, then updates only the value while
12806
+ * preserving the asset's name, scope, and description.
12807
+ *
12808
+ * **Supported value types:** `Text`, `Integer`, and `Bool` only. Other types
12809
+ * (`Credential`, `Secret`) throw a `ValidationError`.
12810
+ *
12811
+ * The `newValue` runtime type must match the asset's `valueType`:
12812
+ * - `Text` → `string`
12813
+ * - `Integer` → `number` (integer)
12814
+ * - `Bool` → `boolean`
12815
+ *
12816
+ * @param id - Asset ID
12817
+ * @param newValue - New value to apply (string for `Text`, number for `Integer`, boolean for `Bool`)
12818
+ * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`)
12819
+ * @returns Promise resolving when the asset has been updated
12820
+ *
12821
+ * @example
12822
+ * ```typescript
12823
+ * import { Assets } from '@uipath/uipath-typescript/assets';
12824
+ *
12825
+ * const assets = new Assets(sdk);
12826
+ *
12827
+ * // Update a Text asset by folder ID
12828
+ * await assets.updateValueById(<assetId>, 'new-value', { folderId: <folderId> });
12829
+ *
12830
+ * // Update an Integer asset by folder key (GUID)
12831
+ * await assets.updateValueById(<assetId>, 42, { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' });
12832
+ *
12833
+ * // Update a Bool asset by folder path
12834
+ * await assets.updateValueById(<assetId>, true, { folderPath: 'Shared/Finance' });
12835
+ * ```
12836
+ */
12837
+ async updateValueById(id, newValue, options) {
12838
+ if (!id) {
12839
+ throw new ValidationError({ message: 'id is required for updateValueById' });
12840
+ }
12841
+ if (newValue === null || newValue === undefined) {
12842
+ throw new ValidationError({ message: 'newValue is required for updateValueById' });
12843
+ }
12844
+ const headers = resolveFolderHeaders({
12845
+ folderId: options?.folderId,
12846
+ folderKey: options?.folderKey,
12847
+ folderPath: options?.folderPath,
12848
+ resourceType: 'Assets.updateValueById',
12849
+ fallbackFolderKey: this.config.folderKey,
12850
+ });
12851
+ const existingResponse = await this.get(ASSET_ENDPOINTS.GET_BY_ID(id), { headers });
12852
+ const existing = existingResponse.data;
12853
+ const valueField = resolveValueField(id, existing.ValueType, newValue);
12854
+ const body = {
12855
+ Id: id,
12856
+ Name: existing.Name,
12857
+ ValueScope: existing.ValueScope,
12858
+ ValueType: existing.ValueType,
12859
+ Description: existing.Description,
12860
+ [valueField]: newValue,
12861
+ };
12862
+ await this.put(ASSET_ENDPOINTS.GET_BY_ID(id), body, { headers });
12863
+ }
12168
12864
  }
12169
12865
  __decorate([
12170
12866
  track('Assets.GetAll')
@@ -12175,30 +12871,42 @@ __decorate([
12175
12871
  __decorate([
12176
12872
  track('Assets.GetByName')
12177
12873
  ], AssetService.prototype, "getByName", null);
12178
-
12179
- /**
12180
- * Enum for Asset Value Scope
12181
- */
12182
- exports.AssetValueScope = void 0;
12183
- (function (AssetValueScope) {
12184
- AssetValueScope["Global"] = "Global";
12185
- AssetValueScope["PerRobot"] = "PerRobot";
12186
- })(exports.AssetValueScope || (exports.AssetValueScope = {}));
12874
+ __decorate([
12875
+ track('Assets.UpdateValueById')
12876
+ ], AssetService.prototype, "updateValueById", null);
12187
12877
  /**
12188
- * Enum for Asset Value Type
12878
+ * Maps the asset's `valueType` to the PUT body field carrying the new value, validating
12879
+ * that the new value's runtime type matches the asset type.
12189
12880
  */
12190
- exports.AssetValueType = void 0;
12191
- (function (AssetValueType) {
12192
- AssetValueType["DBConnectionString"] = "DBConnectionString";
12193
- AssetValueType["HttpConnectionString"] = "HttpConnectionString";
12194
- AssetValueType["Text"] = "Text";
12195
- AssetValueType["Bool"] = "Bool";
12196
- AssetValueType["Integer"] = "Integer";
12197
- AssetValueType["Credential"] = "Credential";
12198
- AssetValueType["WindowsCredential"] = "WindowsCredential";
12199
- AssetValueType["KeyValueList"] = "KeyValueList";
12200
- AssetValueType["Secret"] = "Secret";
12201
- })(exports.AssetValueType || (exports.AssetValueType = {}));
12881
+ function resolveValueField(id, valueType, newValue) {
12882
+ switch (valueType) {
12883
+ case exports.AssetValueType.Text:
12884
+ if (typeof newValue !== 'string') {
12885
+ throw new ValidationError({
12886
+ message: `Asset ${id} has valueType Text; newValue must be a string, got ${typeof newValue}`,
12887
+ });
12888
+ }
12889
+ return 'StringValue';
12890
+ case exports.AssetValueType.Integer:
12891
+ if (typeof newValue !== 'number' || !Number.isInteger(newValue)) {
12892
+ throw new ValidationError({
12893
+ message: `Asset ${id} has valueType Integer; newValue must be an integer number, got ${typeof newValue}`,
12894
+ });
12895
+ }
12896
+ return 'IntValue';
12897
+ case exports.AssetValueType.Bool:
12898
+ if (typeof newValue !== 'boolean') {
12899
+ throw new ValidationError({
12900
+ message: `Asset ${id} has valueType Bool; newValue must be a boolean, got ${typeof newValue}`,
12901
+ });
12902
+ }
12903
+ return 'BoolValue';
12904
+ default:
12905
+ throw new ValidationError({
12906
+ message: `updateValueById only supports Text, Integer, or Bool assets; asset ${id} has valueType ${valueType}`,
12907
+ });
12908
+ }
12909
+ }
12202
12910
 
12203
12911
  /**
12204
12912
  * Maps fields for Bucket entities to ensure consistent naming
@@ -14115,6 +14823,39 @@ exports.FeedbackStatus = void 0;
14115
14823
  FeedbackStatus[FeedbackStatus["Dismissed"] = 2] = "Dismissed";
14116
14824
  })(exports.FeedbackStatus || (exports.FeedbackStatus = {}));
14117
14825
 
14826
+ /**
14827
+ * Columns available for ordering results.
14828
+ */
14829
+ exports.AgentListSortColumn = void 0;
14830
+ (function (AgentListSortColumn) {
14831
+ AgentListSortColumn["AgentName"] = "AgentName";
14832
+ AgentListSortColumn["ParentProcess"] = "ParentProcess";
14833
+ AgentListSortColumn["LastRun"] = "LastRun";
14834
+ AgentListSortColumn["HealthScore"] = "HealthScore";
14835
+ AgentListSortColumn["LastIncident"] = "LastIncident";
14836
+ AgentListSortColumn["FolderName"] = "FolderName";
14837
+ /** Quantity of AGU (Agent Units) consumed */
14838
+ AgentListSortColumn["QuantityAGU"] = "QuantityAGU";
14839
+ /** Quantity of PLTU (Platform Units) consumed */
14840
+ AgentListSortColumn["QuantityPLTU"] = "QuantityPLTU";
14841
+ AgentListSortColumn["FolderPath"] = "FolderPath";
14842
+ })(exports.AgentListSortColumn || (exports.AgentListSortColumn = {}));
14843
+
14844
+ /**
14845
+ * Types for the Agent Memory metrics service.
14846
+ */
14847
+ /**
14848
+ * Execution kind to filter Agent Memory queries by. Omit to include both
14849
+ * Debug and Runtime executions.
14850
+ */
14851
+ exports.AgentMemoryExecutionType = void 0;
14852
+ (function (AgentMemoryExecutionType) {
14853
+ /** Executions produced during agent debugging sessions. */
14854
+ AgentMemoryExecutionType["Debug"] = "Debug";
14855
+ /** Executions produced during production runtime. */
14856
+ AgentMemoryExecutionType["Runtime"] = "Runtime";
14857
+ })(exports.AgentMemoryExecutionType || (exports.AgentMemoryExecutionType = {}));
14858
+
14118
14859
  // Auto-generated from the OpenAPI spec — do not edit manually.
14119
14860
  var DocumentActionPriority;
14120
14861
  (function (DocumentActionPriority) {
@@ -14386,6 +15127,23 @@ var index = /*#__PURE__*/Object.freeze({
14386
15127
  get WordGroupType () { return WordGroupType; }
14387
15128
  });
14388
15129
 
15130
+ /**
15131
+ * Governance Service Types
15132
+ *
15133
+ * Public types exposed via `@uipath/uipath-typescript/governance`.
15134
+ */
15135
+ exports.PolicyEvaluationResult = void 0;
15136
+ (function (PolicyEvaluationResult) {
15137
+ /** Active policy permitted the action. */
15138
+ PolicyEvaluationResult["Allow"] = "Allow";
15139
+ /** Active policy blocked the action. */
15140
+ PolicyEvaluationResult["Deny"] = "Deny";
15141
+ /** Simulated (NoOp) policy would have permitted the action. */
15142
+ PolicyEvaluationResult["SimulatedAllow"] = "SimulatedAllow";
15143
+ /** Simulated (NoOp) policy would have blocked the action. */
15144
+ PolicyEvaluationResult["SimulatedDeny"] = "SimulatedDeny";
15145
+ })(exports.PolicyEvaluationResult || (exports.PolicyEvaluationResult = {}));
15146
+
14389
15147
  /**
14390
15148
  * Asset resolution utilities for UiPath Coded Apps
14391
15149
  *
@@ -14485,6 +15243,7 @@ exports.UserSettingsMap = UserSettingsMap;
14485
15243
  exports.ValidationError = ValidationError;
14486
15244
  exports.createAgentWithMethods = createAgentWithMethods;
14487
15245
  exports.createCaseInstanceWithMethods = createCaseInstanceWithMethods;
15246
+ exports.createCaseWithMethods = createCaseWithMethods;
14488
15247
  exports.createConversationWithMethods = createConversationWithMethods;
14489
15248
  exports.createEntityWithMethods = createEntityWithMethods;
14490
15249
  exports.createJobWithMethods = createJobWithMethods;