@uipath/authz-tool 1.1.0 → 1.2.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 (3) hide show
  1. package/dist/index.js +716 -157
  2. package/dist/tool.js +716 -157
  3. package/package.json +28 -37
package/dist/tool.js CHANGED
@@ -706,6 +706,7 @@ var init_open = __esm(() => {
706
706
  });
707
707
 
708
708
  // ../../filesystem/src/node.ts
709
+ import { randomUUID } from "node:crypto";
709
710
  import { existsSync } from "node:fs";
710
711
  import * as fs6 from "node:fs/promises";
711
712
  import * as os2 from "node:os";
@@ -787,6 +788,90 @@ class NodeFileSystem {
787
788
  async mkdir(dirPath) {
788
789
  await fs6.mkdir(dirPath, { recursive: true });
789
790
  }
791
+ async acquireLock(lockPath) {
792
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
793
+ const lockFile = `${canonicalPath}.lock`;
794
+ const ownerId = randomUUID();
795
+ const start = Date.now();
796
+ while (true) {
797
+ try {
798
+ await fs6.writeFile(lockFile, ownerId, { flag: "wx" });
799
+ return this.createLockRelease(lockFile, ownerId);
800
+ } catch (error) {
801
+ if (!this.hasErrnoCode(error, "EEXIST")) {
802
+ throw error;
803
+ }
804
+ const stats = await fs6.stat(lockFile).catch(() => null);
805
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
806
+ const reclaimed = await fs6.rm(lockFile, { force: true }).then(() => true).catch(() => false);
807
+ if (reclaimed)
808
+ continue;
809
+ }
810
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
811
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
812
+ }
813
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
814
+ }
815
+ }
816
+ }
817
+ async canonicalizeLockTarget(lockPath) {
818
+ const absolute = path2.resolve(lockPath);
819
+ const fullReal = await fs6.realpath(absolute).catch(() => null);
820
+ if (fullReal)
821
+ return fullReal;
822
+ const parent = path2.dirname(absolute);
823
+ const base = path2.basename(absolute);
824
+ const canonicalParent = await fs6.realpath(parent).catch(() => parent);
825
+ return path2.join(canonicalParent, base);
826
+ }
827
+ createLockRelease(lockFile, ownerId) {
828
+ const heartbeatStart = Date.now();
829
+ let heartbeatTimer;
830
+ let stopped = false;
831
+ const stopHeartbeat = () => {
832
+ stopped = true;
833
+ if (heartbeatTimer)
834
+ clearTimeout(heartbeatTimer);
835
+ };
836
+ const scheduleNextHeartbeat = () => {
837
+ if (stopped)
838
+ return;
839
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
840
+ stopped = true;
841
+ return;
842
+ }
843
+ heartbeatTimer = setTimeout(() => {
844
+ runHeartbeat();
845
+ }, LOCK_HEARTBEAT_MS);
846
+ heartbeatTimer.unref?.();
847
+ };
848
+ const runHeartbeat = async () => {
849
+ if (stopped)
850
+ return;
851
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
852
+ if (stopped)
853
+ return;
854
+ if (current !== ownerId) {
855
+ stopped = true;
856
+ return;
857
+ }
858
+ const now = Date.now() / 1000;
859
+ await fs6.utimes(lockFile, now, now).catch(() => {});
860
+ scheduleNextHeartbeat();
861
+ };
862
+ scheduleNextHeartbeat();
863
+ let released = false;
864
+ return async () => {
865
+ if (released)
866
+ return;
867
+ released = true;
868
+ stopHeartbeat();
869
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
870
+ if (current === ownerId) {
871
+ await fs6.rm(lockFile, { force: true });
872
+ }
873
+ };
874
+ }
790
875
  async rm(filePath) {
791
876
  await fs6.rm(filePath, { recursive: true, force: true });
792
877
  }
@@ -832,9 +917,13 @@ class NodeFileSystem {
832
917
  }
833
918
  }
834
919
  isEnoent(error) {
835
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
920
+ return this.hasErrnoCode(error, "ENOENT");
921
+ }
922
+ hasErrnoCode(error, code) {
923
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
836
924
  }
837
925
  }
926
+ var LOCK_HEARTBEAT_MS = 5000, LOCK_STALE_MS = 15000, LOCK_MAX_WAIT_MS = 20000, LOCK_MAX_HOLD_MS = 60000, LOCK_RETRY_MIN_MS = 100, LOCK_RETRY_JITTER_MS = 200;
838
927
  var init_node = __esm(() => {
839
928
  init_open();
840
929
  });
@@ -848,7 +937,7 @@ var init_src = __esm(() => {
848
937
 
849
938
  // ../../../node_modules/@uipath/coreipc/index.js
850
939
  var require_coreipc = __commonJS((exports, module) => {
851
- var __dirname = "/Users/alexandru.oltean/github/cli/node_modules/@uipath/coreipc";
940
+ var __dirname = "/home/runner/work/cli/cli/node_modules/@uipath/coreipc";
852
941
  /*! For license information please see index.js.LICENSE.txt */
853
942
  (function(e, t) {
854
943
  typeof exports == "object" && typeof module == "object" ? module.exports = t() : typeof define == "function" && define.amd ? define([], t) : typeof exports == "object" ? exports.ipc = t() : e.ipc = t();
@@ -19040,10 +19129,15 @@ var require_dist = __commonJS((exports) => {
19040
19129
  exports.RobotProxyConstructor = RobotProxyConstructor;
19041
19130
  __exportStar(require_agent(), exports);
19042
19131
  });
19132
+ // ../../auth/src/server.ts
19133
+ var init_server = __esm(() => {
19134
+ init_constants();
19135
+ });
19043
19136
  // package.json
19044
19137
  var package_default = {
19045
19138
  name: "@uipath/authz-tool",
19046
- version: "1.1.0",
19139
+ license: "MIT",
19140
+ version: "1.2.0",
19047
19141
  description: "CLI plugin for the UiPath Authorization service.",
19048
19142
  private: false,
19049
19143
  repository: {
@@ -19112,32 +19206,7 @@ class InvalidBaseUrlError extends Error {
19112
19206
  this.name = "InvalidBaseUrlError";
19113
19207
  }
19114
19208
  }
19115
- var DEFAULT_SCOPES = [
19116
- "offline_access",
19117
- "ProcessMining",
19118
- "OrchestratorApiUserAccess",
19119
- "StudioWebBackend",
19120
- "IdentityServerApi",
19121
- "ConnectionService",
19122
- "DataService",
19123
- "DataServiceApiUserAccess",
19124
- "DocumentUnderstanding",
19125
- "EnterpriseContextService",
19126
- "Directory",
19127
- "JamJamApi",
19128
- "LLMGateway",
19129
- "LLMOps",
19130
- "OMS",
19131
- "RCS.FolderAuthorization",
19132
- "RCS.TagsManagement",
19133
- "TestmanagerApiUserAccess",
19134
- "AutomationSolutions",
19135
- "StudioWebTypeCacheService",
19136
- "Docs.GPT.Search",
19137
- "Insights",
19138
- "ReferenceToken",
19139
- "Audit.Read"
19140
- ];
19209
+ var DEFAULT_SCOPES = ["openid", "profile", "offline_access"];
19141
19210
  var normalizeAndValidateBaseUrl = (rawUrl) => {
19142
19211
  let baseUrl = rawUrl;
19143
19212
  if (baseUrl.endsWith("/identity_/")) {
@@ -19187,7 +19256,8 @@ var resolveConfigAsync = async ({
19187
19256
  if (!clientSecret && fileAuth.clientSecret) {
19188
19257
  clientSecret = fileAuth.clientSecret;
19189
19258
  }
19190
- const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : DEFAULT_SCOPES;
19259
+ const isExternalAppAuth = clientId !== DEFAULT_CLIENT_ID && Boolean(clientSecret);
19260
+ const scopes = customScopes && customScopes.length > 0 ? customScopes : fileAuth.scopes && fileAuth.scopes.length > 0 ? fileAuth.scopes : isExternalAppAuth ? [] : DEFAULT_SCOPES;
19191
19261
  return {
19192
19262
  clientId,
19193
19263
  clientSecret,
@@ -19687,6 +19757,129 @@ function normalizeTokenRefreshFailure() {
19687
19757
  function normalizeTokenRefreshUnavailableFailure() {
19688
19758
  return "token refresh failed before authentication completed";
19689
19759
  }
19760
+ function errorMessage(error) {
19761
+ return error instanceof Error ? error.message : String(error);
19762
+ }
19763
+ function computeExpirationThreshold(ensureTokenValidityMinutes) {
19764
+ return new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
19765
+ }
19766
+ async function runRefreshLocked(inputs) {
19767
+ const {
19768
+ absolutePath,
19769
+ refreshToken: callerRefreshToken,
19770
+ customAuthority,
19771
+ ensureTokenValidityMinutes,
19772
+ loadEnvFile,
19773
+ saveEnvFile,
19774
+ refreshFn,
19775
+ resolveConfig
19776
+ } = inputs;
19777
+ const expirationThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
19778
+ let fresh;
19779
+ try {
19780
+ fresh = await loadEnvFile({ envPath: absolutePath });
19781
+ } catch (error) {
19782
+ return {
19783
+ kind: "fail",
19784
+ status: {
19785
+ loginStatus: "Refresh Failed",
19786
+ hint: "Could not read the auth file while refreshing. Retry, or run 'uip login' to re-authenticate.",
19787
+ tokenRefresh: {
19788
+ attempted: false,
19789
+ success: false,
19790
+ errorMessage: `auth file read failed: ${errorMessage(error)}`
19791
+ }
19792
+ }
19793
+ };
19794
+ }
19795
+ const freshAccess = fresh.UIPATH_ACCESS_TOKEN;
19796
+ const freshExp = freshAccess ? getTokenExpiration(freshAccess) : undefined;
19797
+ if (freshAccess && freshExp && freshExp > expirationThreshold) {
19798
+ return {
19799
+ kind: "ok",
19800
+ accessToken: freshAccess,
19801
+ refreshToken: fresh.UIPATH_REFRESH_TOKEN ?? callerRefreshToken,
19802
+ expiration: freshExp,
19803
+ tokenRefresh: { attempted: false, success: true }
19804
+ };
19805
+ }
19806
+ const tokenForIdP = fresh.UIPATH_REFRESH_TOKEN ?? callerRefreshToken;
19807
+ let refreshedAccess;
19808
+ let refreshedRefresh;
19809
+ try {
19810
+ const config = await resolveConfig({ customAuthority });
19811
+ const refreshed = await refreshFn({
19812
+ refreshToken: tokenForIdP,
19813
+ tokenEndpoint: config.tokenEndpoint,
19814
+ clientId: config.clientId,
19815
+ expectedAuthority: customAuthority
19816
+ });
19817
+ refreshedAccess = refreshed.accessToken;
19818
+ refreshedRefresh = refreshed.refreshToken;
19819
+ } catch (error) {
19820
+ const isOAuthFailure = isTokenRefreshOAuthFailure(error);
19821
+ const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
19822
+ const message = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
19823
+ return {
19824
+ kind: "fail",
19825
+ status: {
19826
+ loginStatus: "Refresh Failed",
19827
+ hint,
19828
+ tokenRefresh: {
19829
+ attempted: true,
19830
+ success: false,
19831
+ errorMessage: message
19832
+ }
19833
+ }
19834
+ };
19835
+ }
19836
+ const refreshedExp = getTokenExpiration(refreshedAccess);
19837
+ if (!refreshedExp || refreshedExp <= new Date) {
19838
+ return {
19839
+ kind: "fail",
19840
+ status: {
19841
+ loginStatus: "Refresh Failed",
19842
+ hint: "The identity server returned an unusable token. Run 'uip login' to re-authenticate.",
19843
+ tokenRefresh: {
19844
+ attempted: true,
19845
+ success: false,
19846
+ errorMessage: "refreshed token has no valid expiration claim"
19847
+ }
19848
+ }
19849
+ };
19850
+ }
19851
+ try {
19852
+ await saveEnvFile({
19853
+ envPath: absolutePath,
19854
+ data: {
19855
+ UIPATH_ACCESS_TOKEN: refreshedAccess,
19856
+ UIPATH_REFRESH_TOKEN: refreshedRefresh
19857
+ },
19858
+ merge: true
19859
+ });
19860
+ return {
19861
+ kind: "ok",
19862
+ accessToken: refreshedAccess,
19863
+ refreshToken: refreshedRefresh,
19864
+ expiration: refreshedExp,
19865
+ tokenRefresh: { attempted: true, success: true }
19866
+ };
19867
+ } catch (error) {
19868
+ const msg = errorMessage(error);
19869
+ return {
19870
+ kind: "ok",
19871
+ accessToken: refreshedAccess,
19872
+ refreshToken: refreshedRefresh,
19873
+ expiration: refreshedExp,
19874
+ persistenceWarning: `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`,
19875
+ tokenRefresh: {
19876
+ attempted: true,
19877
+ success: true,
19878
+ errorMessage: `persistence failed: ${msg}`
19879
+ }
19880
+ };
19881
+ }
19882
+ }
19690
19883
  var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
19691
19884
  const {
19692
19885
  resolveEnvFilePath = resolveEnvFilePathAsync,
@@ -19761,73 +19954,103 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
19761
19954
  let refreshToken = credentials.UIPATH_REFRESH_TOKEN;
19762
19955
  let expiration = getTokenExpiration(accessToken);
19763
19956
  let persistenceWarning;
19957
+ let lockReleaseFailed = false;
19764
19958
  let tokenRefresh;
19765
- const expirationThreshold = new Date(Date.now() + (ensureTokenValidityMinutes ?? 0) * 60 * 1000);
19766
- if (expiration && expiration <= expirationThreshold && refreshToken) {
19767
- let refreshedAccess;
19768
- let refreshedRefresh;
19959
+ const outerThreshold = computeExpirationThreshold(ensureTokenValidityMinutes);
19960
+ const tryGlobalCredsHint = async () => {
19961
+ const fs7 = getFs();
19962
+ const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
19963
+ if (absolutePath === globalPath)
19964
+ return;
19965
+ if (!await fs7.exists(globalPath))
19966
+ return;
19769
19967
  try {
19770
- const config = await resolveConfig({
19771
- customAuthority: credentials.UIPATH_URL
19772
- });
19773
- const refreshed = await refreshTokenFn({
19774
- refreshToken,
19775
- tokenEndpoint: config.tokenEndpoint,
19776
- clientId: config.clientId,
19777
- expectedAuthority: credentials.UIPATH_URL
19778
- });
19779
- refreshedAccess = refreshed.accessToken;
19780
- refreshedRefresh = refreshed.refreshToken;
19781
- } catch (error) {
19782
- const isOAuthFailure = isTokenRefreshOAuthFailure(error);
19783
- const hint = isOAuthFailure ? "Run 'uip login' to re-authenticate — the stored refresh token is invalid or expired." : "Token refresh failed. Check your network connection, then retry or run 'uip login' to re-authenticate.";
19784
- const errorMessage = isOAuthFailure ? normalizeTokenRefreshFailure() : normalizeTokenRefreshUnavailableFailure();
19785
- return {
19786
- loginStatus: "Refresh Failed",
19787
- hint,
19788
- tokenRefresh: {
19789
- attempted: true,
19790
- success: false,
19791
- errorMessage
19792
- }
19793
- };
19968
+ const globalCreds = await loadEnvFile({ envPath: globalPath });
19969
+ if (!globalCreds.UIPATH_ACCESS_TOKEN)
19970
+ return;
19971
+ const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
19972
+ if (globalExp && globalExp <= new Date)
19973
+ return;
19974
+ return `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
19975
+ } catch {
19976
+ return;
19794
19977
  }
19795
- const refreshedExp = getTokenExpiration(refreshedAccess);
19796
- if (!refreshedExp || refreshedExp <= new Date) {
19978
+ };
19979
+ if (expiration && expiration <= outerThreshold && refreshToken) {
19980
+ let release;
19981
+ try {
19982
+ release = await getFs().acquireLock(absolutePath);
19983
+ } catch (error) {
19984
+ const msg = errorMessage(error);
19985
+ const globalHint = await tryGlobalCredsHint();
19986
+ if (globalHint) {
19987
+ return {
19988
+ loginStatus: "Expired",
19989
+ accessToken,
19990
+ refreshToken,
19991
+ baseUrl: credentials.UIPATH_URL,
19992
+ organizationName: credentials.UIPATH_ORGANIZATION_NAME,
19993
+ organizationId: credentials.UIPATH_ORGANIZATION_ID,
19994
+ tenantName: credentials.UIPATH_TENANT_NAME,
19995
+ tenantId: credentials.UIPATH_TENANT_ID,
19996
+ expiration,
19997
+ source: "file" /* File */,
19998
+ hint: globalHint,
19999
+ tokenRefresh: {
20000
+ attempted: false,
20001
+ success: false,
20002
+ errorMessage: `lock acquisition failed: ${msg}`
20003
+ }
20004
+ };
20005
+ }
19797
20006
  return {
19798
20007
  loginStatus: "Refresh Failed",
19799
- hint: "The identity server returned an unusable token. Run 'uip login' to re-authenticate.",
20008
+ hint: "Could not acquire the auth-file lock — too many concurrent `uip` processes, or a permission issue on the auth directory. Retry, or run 'uip login' to re-authenticate.",
19800
20009
  tokenRefresh: {
19801
- attempted: true,
20010
+ attempted: false,
19802
20011
  success: false,
19803
- errorMessage: "refreshed token has no valid expiration claim"
20012
+ errorMessage: `lock acquisition failed: ${msg}`
19804
20013
  }
19805
20014
  };
19806
20015
  }
19807
- accessToken = refreshedAccess;
19808
- refreshToken = refreshedRefresh;
19809
- expiration = refreshedExp;
20016
+ let lockedFailure;
19810
20017
  try {
19811
- await saveEnvFile({
19812
- envPath: absolutePath,
19813
- data: {
19814
- UIPATH_ACCESS_TOKEN: accessToken,
19815
- UIPATH_REFRESH_TOKEN: refreshToken
19816
- },
19817
- merge: true
20018
+ const outcome = await runRefreshLocked({
20019
+ absolutePath,
20020
+ refreshToken,
20021
+ customAuthority: credentials.UIPATH_URL,
20022
+ ensureTokenValidityMinutes,
20023
+ loadEnvFile,
20024
+ saveEnvFile,
20025
+ refreshFn: refreshTokenFn,
20026
+ resolveConfig
19818
20027
  });
19819
- tokenRefresh = {
19820
- attempted: true,
19821
- success: true
19822
- };
19823
- } catch (error) {
19824
- const msg = error instanceof Error ? error.message : String(error);
19825
- persistenceWarning = `Access token refreshed in memory but could not be written to ${absolutePath}: ${msg}. The next CLI invocation will fail until the file can be updated — run 'uip login' to re-authenticate.`;
19826
- tokenRefresh = {
19827
- attempted: true,
19828
- success: true,
19829
- errorMessage: `persistence failed: ${msg}`
19830
- };
20028
+ if (outcome.kind === "fail") {
20029
+ lockedFailure = outcome.status;
20030
+ } else {
20031
+ accessToken = outcome.accessToken;
20032
+ refreshToken = outcome.refreshToken;
20033
+ expiration = outcome.expiration;
20034
+ tokenRefresh = outcome.tokenRefresh;
20035
+ if (outcome.persistenceWarning) {
20036
+ persistenceWarning = outcome.persistenceWarning;
20037
+ }
20038
+ }
20039
+ } finally {
20040
+ try {
20041
+ await release();
20042
+ } catch {
20043
+ lockReleaseFailed = true;
20044
+ }
20045
+ }
20046
+ if (lockedFailure) {
20047
+ const globalHint = await tryGlobalCredsHint();
20048
+ const base = globalHint ? {
20049
+ ...lockedFailure,
20050
+ loginStatus: "Expired",
20051
+ hint: globalHint
20052
+ } : lockedFailure;
20053
+ return lockReleaseFailed ? { ...base, lockReleaseFailed: true } : base;
19831
20054
  }
19832
20055
  }
19833
20056
  const result = {
@@ -19842,23 +20065,13 @@ var getLoginStatusWithDeps = async (options = {}, deps = {}) => {
19842
20065
  expiration,
19843
20066
  source: "file" /* File */,
19844
20067
  ...persistenceWarning ? { hint: persistenceWarning, persistenceFailed: true } : {},
20068
+ ...lockReleaseFailed ? { lockReleaseFailed: true } : {},
19845
20069
  ...tokenRefresh ? { tokenRefresh } : {}
19846
20070
  };
19847
20071
  if (result.loginStatus === "Expired") {
19848
- const fs7 = getFs();
19849
- const globalPath = fs7.path.join(fs7.env.homedir(), envFilePath);
19850
- if (absolutePath !== globalPath && await fs7.exists(globalPath)) {
19851
- try {
19852
- const globalCreds = await loadEnvFile({
19853
- envPath: globalPath
19854
- });
19855
- if (globalCreds.UIPATH_ACCESS_TOKEN) {
19856
- const globalExp = getTokenExpiration(globalCreds.UIPATH_ACCESS_TOKEN);
19857
- if (!globalExp || globalExp > new Date) {
19858
- result.hint = `Local credentials file at ${absolutePath} has expired credentials. Valid credentials exist in ${globalPath}. Remove the local file or run 'uip login' to re-authenticate.`;
19859
- }
19860
- }
19861
- } catch {}
20072
+ const globalHint = await tryGlobalCredsHint();
20073
+ if (globalHint) {
20074
+ result.hint = globalHint;
19862
20075
  }
19863
20076
  }
19864
20077
  return result;
@@ -19906,6 +20119,140 @@ var getAuthContext = async (options = {}) => {
19906
20119
  init_src();
19907
20120
  // ../../auth/src/logout.ts
19908
20121
  init_src();
20122
+
20123
+ // ../../auth/src/index.ts
20124
+ init_server();
20125
+
20126
+ // ../../common/src/singleton.ts
20127
+ var PREFIX = "@uipath/common/";
20128
+ var _g = globalThis;
20129
+ function singleton(ctorOrName) {
20130
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
20131
+ const key = Symbol.for(PREFIX + name);
20132
+ return {
20133
+ get(fallback) {
20134
+ return _g[key] ?? fallback;
20135
+ },
20136
+ set(value) {
20137
+ _g[key] = value;
20138
+ },
20139
+ clear() {
20140
+ delete _g[key];
20141
+ },
20142
+ getOrInit(factory, guard) {
20143
+ const existing = _g[key];
20144
+ if (existing != null && typeof existing === "object") {
20145
+ if (!guard || guard(existing)) {
20146
+ return existing;
20147
+ }
20148
+ }
20149
+ const instance = factory();
20150
+ _g[key] = instance;
20151
+ return instance;
20152
+ }
20153
+ };
20154
+ }
20155
+
20156
+ // ../../common/src/sdk-user-agent.ts
20157
+ var USER_AGENT_HEADER = "User-Agent";
20158
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
20159
+ function userAgentPatchKey(userAgent) {
20160
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
20161
+ }
20162
+ function splitUserAgentTokens(value) {
20163
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
20164
+ }
20165
+ function appendUserAgentToken(value, userAgent) {
20166
+ const tokens = splitUserAgentTokens(value);
20167
+ const seen = new Set(tokens);
20168
+ for (const token of splitUserAgentTokens(userAgent)) {
20169
+ if (!seen.has(token)) {
20170
+ tokens.push(token);
20171
+ seen.add(token);
20172
+ }
20173
+ }
20174
+ return tokens.join(" ");
20175
+ }
20176
+ function getEffectiveUserAgent(userAgent) {
20177
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
20178
+ }
20179
+ function isHeadersLike(headers) {
20180
+ return typeof headers === "object" && headers !== null && "get" in headers && typeof headers.get === "function" && "set" in headers && typeof headers.set === "function";
20181
+ }
20182
+ function getSdkUserAgentToken(pkg) {
20183
+ const packageName = pkg.name.replace(/^@uipath\//, "");
20184
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
20185
+ }
20186
+ function addSdkUserAgentHeader(headers, userAgent) {
20187
+ const result = { ...headers ?? {} };
20188
+ const effectiveUserAgent = getEffectiveUserAgent(userAgent);
20189
+ const headerName = Object.keys(result).find((key) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
20190
+ if (headerName) {
20191
+ result[headerName] = appendUserAgentToken(result[headerName], effectiveUserAgent);
20192
+ } else {
20193
+ result[USER_AGENT_HEADER] = effectiveUserAgent;
20194
+ }
20195
+ return result;
20196
+ }
20197
+ function withSdkUserAgentHeader(headers, userAgent) {
20198
+ const effectiveUserAgent = getEffectiveUserAgent(userAgent);
20199
+ if (isHeadersLike(headers)) {
20200
+ headers.set(USER_AGENT_HEADER, appendUserAgentToken(headers.get(USER_AGENT_HEADER), effectiveUserAgent));
20201
+ return headers;
20202
+ }
20203
+ if (Array.isArray(headers)) {
20204
+ const result = headers.map((entry) => {
20205
+ const [key, value] = entry;
20206
+ return [key, value];
20207
+ });
20208
+ const headerIndex = result.findIndex(([key]) => key.toLowerCase() === USER_AGENT_HEADER.toLowerCase());
20209
+ if (headerIndex >= 0) {
20210
+ const [key, value] = result[headerIndex];
20211
+ result[headerIndex] = [
20212
+ key,
20213
+ appendUserAgentToken(value, effectiveUserAgent)
20214
+ ];
20215
+ } else {
20216
+ result.push([USER_AGENT_HEADER, effectiveUserAgent]);
20217
+ }
20218
+ return result;
20219
+ }
20220
+ return addSdkUserAgentHeader(typeof headers === "object" && headers !== null ? { ...headers } : {}, effectiveUserAgent);
20221
+ }
20222
+ function withUserAgentInitOverride(initOverrides, userAgent) {
20223
+ return async (requestContext) => {
20224
+ const initWithUserAgent = {
20225
+ ...requestContext.init,
20226
+ headers: withSdkUserAgentHeader(requestContext.init.headers, userAgent)
20227
+ };
20228
+ const override = typeof initOverrides === "function" ? await initOverrides({
20229
+ ...requestContext,
20230
+ init: initWithUserAgent
20231
+ }) : initOverrides;
20232
+ return {
20233
+ ...override ?? {},
20234
+ headers: withSdkUserAgentHeader(override?.headers ?? initWithUserAgent.headers, userAgent)
20235
+ };
20236
+ };
20237
+ }
20238
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
20239
+ const prototype = BaseApiClass.prototype;
20240
+ const patchKey = userAgentPatchKey(userAgent);
20241
+ if (prototype[patchKey]) {
20242
+ return;
20243
+ }
20244
+ if (typeof prototype.request !== "function") {
20245
+ throw new Error("Generated BaseAPI request function not found.");
20246
+ }
20247
+ const originalRequest = prototype.request;
20248
+ prototype.request = function requestWithUserAgent(context, initOverrides) {
20249
+ return originalRequest.call(this, context, withUserAgentInitOverride(initOverrides, userAgent));
20250
+ };
20251
+ Object.defineProperty(prototype, patchKey, {
20252
+ value: true
20253
+ });
20254
+ }
20255
+
19909
20256
  // ../authz-sdk/generated/src/runtime.ts
19910
20257
  var BASE_PATH = "http://localhost".replace(/\/+$/, "");
19911
20258
 
@@ -20155,6 +20502,57 @@ class VoidApiResponse {
20155
20502
  return;
20156
20503
  }
20157
20504
  }
20505
+ // ../authz-sdk/package.json
20506
+ var package_default2 = {
20507
+ name: "@uipath/authz-sdk",
20508
+ license: "MIT",
20509
+ version: "1.2.0",
20510
+ description: "SDK for the UiPath Authorization Service API.",
20511
+ repository: {
20512
+ type: "git",
20513
+ url: "https://github.com/UiPath/cli.git",
20514
+ directory: "packages/admin/authz-sdk"
20515
+ },
20516
+ publishConfig: {
20517
+ registry: "https://npm.pkg.github.com/@uipath"
20518
+ },
20519
+ keywords: [
20520
+ "uipath",
20521
+ "authorization",
20522
+ "authz",
20523
+ "sdk"
20524
+ ],
20525
+ type: "module",
20526
+ main: "./dist/index.js",
20527
+ types: "./dist/src/index.d.ts",
20528
+ exports: {
20529
+ ".": {
20530
+ types: "./dist/src/index.d.ts",
20531
+ default: "./dist/index.js"
20532
+ }
20533
+ },
20534
+ files: [
20535
+ "dist"
20536
+ ],
20537
+ private: true,
20538
+ scripts: {
20539
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
20540
+ generate: "bun run src/scripts/generate-sdk.ts",
20541
+ lint: "biome check ."
20542
+ },
20543
+ devDependencies: {
20544
+ "@openapitools/openapi-generator-cli": "^2.31.1",
20545
+ "@types/node": "^25.5.2",
20546
+ "@uipath/auth": "workspace:*",
20547
+ "@uipath/common": "workspace:*",
20548
+ "@uipath/filesystem": "workspace:*",
20549
+ typescript: "^6.0.2"
20550
+ }
20551
+ };
20552
+
20553
+ // ../authz-sdk/src/user-agent.ts
20554
+ var SDK_USER_AGENT = getSdkUserAgentToken(package_default2);
20555
+ installSdkUserAgentHeader(BaseAPI, SDK_USER_AGENT);
20158
20556
 
20159
20557
  // ../authz-sdk/generated/src/models/ActionDetailDto.ts
20160
20558
  function ActionDetailDtoFromJSON(json) {
@@ -20681,7 +21079,8 @@ async function resolveConfig(plane, options) {
20681
21079
  return {
20682
21080
  config: new Configuration({
20683
21081
  basePath,
20684
- accessToken: async () => bearerToken
21082
+ accessToken: async () => bearerToken,
21083
+ headers: addSdkUserAgentHeader(undefined, SDK_USER_AGENT)
20685
21084
  }),
20686
21085
  organizationId: status.organizationId,
20687
21086
  tenantId: status.tenantId,
@@ -20841,10 +21240,15 @@ async function extractErrorDetails(error, options) {
20841
21240
  }
20842
21241
  if (parsedBody?.errorCode && typeof parsedBody.errorCode === "string") {
20843
21242
  context.errorCode = parsedBody.errorCode;
21243
+ } else if (parsedBody?.code && typeof parsedBody.code === "string") {
21244
+ context.errorCode = parsedBody.code;
20844
21245
  }
20845
21246
  if (parsedBody?.requestId && typeof parsedBody.requestId === "string") {
20846
21247
  context.requestId = parsedBody.requestId;
20847
21248
  }
21249
+ if (parsedBody?.traceId && typeof parsedBody.traceId === "string") {
21250
+ context.traceId = parsedBody.traceId;
21251
+ }
20848
21252
  if (status === 429) {
20849
21253
  const resp = response;
20850
21254
  const headersObj = resp?.headers;
@@ -20864,7 +21268,35 @@ async function extractErrorDetails(error, options) {
20864
21268
  }
20865
21269
  }
20866
21270
  const hasContext = Object.keys(context).length > 0;
20867
- return { result, message, details, ...hasContext ? { context } : {} };
21271
+ let parsedErrors;
21272
+ if (parsedBody?.errors && typeof parsedBody.errors === "object") {
21273
+ const errors = {};
21274
+ for (const [field, raw] of Object.entries(parsedBody.errors)) {
21275
+ if (Array.isArray(raw)) {
21276
+ const messages = raw.map((entry) => {
21277
+ if (typeof entry === "string")
21278
+ return entry;
21279
+ if (entry && typeof entry === "object" && typeof entry.message === "string") {
21280
+ return entry.message;
21281
+ }
21282
+ return String(entry);
21283
+ }).filter(Boolean);
21284
+ if (messages.length > 0)
21285
+ errors[field] = messages;
21286
+ } else if (typeof raw === "string") {
21287
+ errors[field] = [raw];
21288
+ }
21289
+ }
21290
+ if (Object.keys(errors).length > 0)
21291
+ parsedErrors = errors;
21292
+ }
21293
+ return {
21294
+ result,
21295
+ message,
21296
+ details,
21297
+ ...hasContext ? { context } : {},
21298
+ ...parsedErrors ? { parsedErrors } : {}
21299
+ };
20868
21300
  }
20869
21301
  async function extractErrorMessage(error, options) {
20870
21302
  const { message } = await extractErrorDetails(error, options);
@@ -20877,36 +21309,6 @@ Command.prototype.examples = function(examples) {
20877
21309
  examplesByCommand.set(this, examples);
20878
21310
  return this;
20879
21311
  };
20880
- // ../../common/src/singleton.ts
20881
- var PREFIX = "@uipath/common/";
20882
- var _g = globalThis;
20883
- function singleton(ctorOrName) {
20884
- const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
20885
- const key = Symbol.for(PREFIX + name);
20886
- return {
20887
- get(fallback) {
20888
- return _g[key] ?? fallback;
20889
- },
20890
- set(value) {
20891
- _g[key] = value;
20892
- },
20893
- clear() {
20894
- delete _g[key];
20895
- },
20896
- getOrInit(factory, guard) {
20897
- const existing = _g[key];
20898
- if (existing != null && typeof existing === "object") {
20899
- if (!guard || guard(existing)) {
20900
- return existing;
20901
- }
20902
- }
20903
- const instance = factory();
20904
- _g[key] = instance;
20905
- return instance;
20906
- }
20907
- };
20908
- }
20909
-
20910
21312
  // ../../common/src/output-context.ts
20911
21313
  function createStorage() {
20912
21314
  const [error, mod] = catchError2(() => __require("node:async_hooks"));
@@ -25996,6 +26398,60 @@ function escapeNonAscii(jsonText) {
25996
26398
  function needsAsciiSafeJson(sink) {
25997
26399
  return process.platform === "win32" && !sink.capabilities.isInteractive;
25998
26400
  }
26401
+ function isPlainRecord(value) {
26402
+ if (value === null || typeof value !== "object")
26403
+ return false;
26404
+ const prototype = Object.getPrototypeOf(value);
26405
+ return prototype === Object.prototype || prototype === null;
26406
+ }
26407
+ function toLowerCamelCaseKey(key) {
26408
+ if (!key)
26409
+ return key;
26410
+ if (/[_\-\s]/.test(key)) {
26411
+ const [firstPart, ...restParts] = key.split(/[_\-\s]+/).filter(Boolean);
26412
+ if (!firstPart)
26413
+ return key;
26414
+ return [
26415
+ toLowerCamelCaseSimpleKey(firstPart),
26416
+ ...restParts.map((part) => {
26417
+ const normalized = toLowerCamelCaseSimpleKey(part);
26418
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
26419
+ })
26420
+ ].join("");
26421
+ }
26422
+ return toLowerCamelCaseSimpleKey(key);
26423
+ }
26424
+ function toLowerCamelCaseSimpleKey(key) {
26425
+ if (/^[A-Z0-9]+$/.test(key))
26426
+ return key.toLowerCase();
26427
+ return key.replace(/^[A-Z]+(?=[A-Z][a-z]|\d|$)|^[A-Z]/, (match) => match.toLowerCase());
26428
+ }
26429
+ function toPascalCaseKey(key) {
26430
+ const lowerCamelKey = toLowerCamelCaseKey(key);
26431
+ return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
26432
+ }
26433
+ function toPascalCaseData(value) {
26434
+ if (Array.isArray(value))
26435
+ return value.map(toPascalCaseData);
26436
+ if (!isPlainRecord(value))
26437
+ return value;
26438
+ const result = {};
26439
+ for (const [key, nestedValue] of Object.entries(value)) {
26440
+ result[toPascalCaseKey(key)] = toPascalCaseData(nestedValue);
26441
+ }
26442
+ return result;
26443
+ }
26444
+ function normalizeDataKeys(data) {
26445
+ return toPascalCaseData(data);
26446
+ }
26447
+ function normalizeOutputKeys(data) {
26448
+ const result = {};
26449
+ for (const [key, value] of Object.entries(data)) {
26450
+ const pascalKey = toPascalCaseKey(key);
26451
+ result[pascalKey] = pascalKey === "Data" ? value : toPascalCaseData(value);
26452
+ }
26453
+ return result;
26454
+ }
25999
26455
  function printOutput(data, format = "json", logFn, asciiSafe = false) {
26000
26456
  if (!data) {
26001
26457
  logFn("Empty response object. No data to display.");
@@ -26058,7 +26514,7 @@ function wrapText(text, width) {
26058
26514
  function printTable(data, logFn, externalLogValue) {
26059
26515
  if (data.length === 0)
26060
26516
  return;
26061
- const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
26517
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
26062
26518
  const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
26063
26519
  const header = keys.map((key, i2) => key.padEnd(maxWidths[i2])).join(" | ");
26064
26520
  logFn(header);
@@ -26073,7 +26529,7 @@ function printTable(data, logFn, externalLogValue) {
26073
26529
  }
26074
26530
  }
26075
26531
  function printVerticalTable(data, logFn = console.log, externalLogValue) {
26076
- const keys = Object.keys(data).filter((key) => key !== "Code" && key !== "Log");
26532
+ const keys = Object.keys(data).filter((key) => !["code", "log"].includes(key.toLowerCase()));
26077
26533
  if (keys.length === 0)
26078
26534
  return;
26079
26535
  const maxKeyWidth = Math.max(...keys.map((key) => key.length));
@@ -26089,7 +26545,7 @@ function printVerticalTable(data, logFn = console.log, externalLogValue) {
26089
26545
  function printResizableTable(data, logFn = console.log, externalLogValue) {
26090
26546
  if (data.length === 0)
26091
26547
  return;
26092
- const keys = Object.keys(data[0]).filter((key) => key !== "Code" && key !== "Log");
26548
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
26093
26549
  if (keys.length === 0)
26094
26550
  return;
26095
26551
  if (!process.stdout.isTTY) {
@@ -26165,8 +26621,26 @@ function printResizableTable(data, logFn = console.log, externalLogValue) {
26165
26621
  function toYaml(data) {
26166
26622
  return dump(data);
26167
26623
  }
26624
+ class FilterEvaluationError extends Error {
26625
+ __brand = "FilterEvaluationError";
26626
+ filter;
26627
+ instructions;
26628
+ result = RESULTS.ValidationError;
26629
+ constructor(filter, cause) {
26630
+ const underlying = cause instanceof Error ? cause.message : String(cause);
26631
+ super(`Filter '${filter}' failed to evaluate: ${underlying}`);
26632
+ this.name = "FilterEvaluationError";
26633
+ this.filter = filter;
26634
+ this.instructions = `The --output-filter expression '${filter}' failed at evaluation time. ` + "Note that --output-filter operates on the 'Data' field of the envelope, not the full object. " + "For example, on a list result use 'length(@)' instead of 'Data | length(@)'.";
26635
+ }
26636
+ }
26168
26637
  function applyFilter(data, filter) {
26169
- const result = search(data, filter);
26638
+ let result;
26639
+ try {
26640
+ result = search(data, filter);
26641
+ } catch (err) {
26642
+ throw new FilterEvaluationError(filter, err);
26643
+ }
26170
26644
  if (result == null)
26171
26645
  return [];
26172
26646
  if (Array.isArray(result)) {
@@ -26183,13 +26657,18 @@ function applyFilter(data, filter) {
26183
26657
  }
26184
26658
  var OutputFormatter;
26185
26659
  ((OutputFormatter) => {
26186
- function success(data) {
26660
+ function success(data, options) {
26187
26661
  data.Log ??= getLogFilePath() || undefined;
26662
+ const normalize = !options?.preserveDataKeys;
26663
+ if (normalize) {
26664
+ data.Data = normalizeDataKeys(data.Data);
26665
+ }
26188
26666
  const filter = getOutputFilter();
26189
26667
  if (filter) {
26190
- data.Data = applyFilter(data.Data, filter);
26668
+ const filtered = applyFilter(data.Data, filter);
26669
+ data.Data = normalize ? normalizeDataKeys(filtered) : filtered;
26191
26670
  }
26192
- logOutput(data, getOutputFormat());
26671
+ logOutput(normalizeOutputKeys(data), getOutputFormat());
26193
26672
  }
26194
26673
  OutputFormatter.success = success;
26195
26674
  function error(data) {
@@ -26199,7 +26678,7 @@ var OutputFormatter;
26199
26678
  result: data.Result,
26200
26679
  message: data.Message
26201
26680
  });
26202
- logOutput(data, getOutputFormat());
26681
+ logOutput(normalizeOutputKeys(data), getOutputFormat());
26203
26682
  }
26204
26683
  OutputFormatter.error = error;
26205
26684
  function emitList(code, items, opts) {
@@ -26220,13 +26699,14 @@ var OutputFormatter;
26220
26699
  function log(data) {
26221
26700
  const format = getOutputFormat();
26222
26701
  const sink = getOutputSink();
26702
+ const normalized = toPascalCaseData(data);
26223
26703
  if (format === "json") {
26224
- const json2 = JSON.stringify(data);
26704
+ const json2 = JSON.stringify(normalized);
26225
26705
  const safe = needsAsciiSafeJson(sink) ? escapeNonAscii(json2) : json2;
26226
26706
  sink.writeErr(`${safe}
26227
26707
  `);
26228
26708
  } else {
26229
- for (const [key, value] of Object.entries(data)) {
26709
+ for (const [key, value] of Object.entries(normalized)) {
26230
26710
  sink.writeErr(`${key}: ${value}
26231
26711
  `);
26232
26712
  }
@@ -26235,12 +26715,16 @@ var OutputFormatter;
26235
26715
  OutputFormatter.log = log;
26236
26716
  function formatToString(data) {
26237
26717
  const filter = getOutputFilter();
26238
- if (filter && "Data" in data && data.Data != null) {
26239
- data.Data = applyFilter(data.Data, filter);
26718
+ if ("Data" in data && data.Data != null) {
26719
+ data.Data = normalizeDataKeys(data.Data);
26720
+ if (filter) {
26721
+ data.Data = normalizeDataKeys(applyFilter(data.Data, filter));
26722
+ }
26240
26723
  }
26724
+ const output = normalizeOutputKeys(data);
26241
26725
  const lines = [];
26242
26726
  const sink = getOutputSink();
26243
- printOutput(data, getOutputFormat(), (msg) => {
26727
+ printOutput(output, getOutputFormat(), (msg) => {
26244
26728
  lines.push(msg);
26245
26729
  }, needsAsciiSafeJson(sink));
26246
26730
  return lines.join(`
@@ -27655,6 +28139,22 @@ JSONPath.prototype.vm = vm;
27655
28139
  import { Option } from "commander";
27656
28140
  // ../../common/src/option-validators.ts
27657
28141
  import { InvalidArgumentError } from "commander";
28142
+ // ../../common/src/polling/types.ts
28143
+ var PollOutcome = {
28144
+ Completed: "completed",
28145
+ Timeout: "timeout",
28146
+ Interrupted: "interrupted",
28147
+ Aborted: "aborted",
28148
+ Failed: "failed"
28149
+ };
28150
+
28151
+ // ../../common/src/polling/poll-failure-mapping.ts
28152
+ var REASON_BY_OUTCOME = {
28153
+ [PollOutcome.Timeout]: "poll_timeout",
28154
+ [PollOutcome.Failed]: "poll_failed",
28155
+ [PollOutcome.Interrupted]: "poll_failed",
28156
+ [PollOutcome.Aborted]: "poll_aborted"
28157
+ };
27658
28158
  // ../../common/src/polling/terminal-statuses.ts
27659
28159
  var TERMINAL_STATUSES = new Set([
27660
28160
  "completed",
@@ -27863,17 +28363,21 @@ Command2.prototype.trackedAction = function(context, fn, properties) {
27863
28363
  const telemetryName = deriveCommandPath(command);
27864
28364
  const props = typeof properties === "function" ? properties(...args) : properties;
27865
28365
  const startTime = performance.now();
27866
- let errorMessage;
28366
+ let errorMessage2;
27867
28367
  const [error] = await catchError2(fn(...args));
27868
28368
  if (error) {
27869
- errorMessage = error instanceof Error ? error.message : String(error);
27870
- logger.error(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
28369
+ errorMessage2 = error instanceof Error ? error.message : String(error);
28370
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage2}`);
28371
+ const typed = error;
28372
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
28373
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
28374
+ const finalResult = customResult ?? RESULTS.Failure;
27871
28375
  OutputFormatter.error({
27872
- Result: RESULTS.Failure,
27873
- Message: errorMessage,
27874
- Instructions: "An unexpected error occurred. Run with --log-level debug for details."
28376
+ Result: finalResult,
28377
+ Message: errorMessage2,
28378
+ Instructions: customInstructions ?? "An unexpected error occurred. Run with --log-level debug for details."
27875
28379
  });
27876
- context.exit(1);
28380
+ context.exit(EXIT_CODES[finalResult]);
27877
28381
  }
27878
28382
  const durationMs = performance.now() - startTime;
27879
28383
  const success = !error && (process.exitCode === undefined || process.exitCode === 0);
@@ -27882,7 +28386,7 @@ Command2.prototype.trackedAction = function(context, fn, properties) {
27882
28386
  ...props,
27883
28387
  duration: String(durationMs),
27884
28388
  success: String(success),
27885
- ...errorMessage ? { errorMessage } : {}
28389
+ ...errorMessage2 ? { errorMessage: errorMessage2 } : {}
27886
28390
  }));
27887
28391
  });
27888
28392
  };
@@ -28135,6 +28639,57 @@ class VoidApiResponse2 {
28135
28639
  return;
28136
28640
  }
28137
28641
  }
28642
+ // ../identity-sdk/package.json
28643
+ var package_default3 = {
28644
+ name: "@uipath/identity-sdk",
28645
+ license: "MIT",
28646
+ version: "1.2.0",
28647
+ repository: {
28648
+ type: "git",
28649
+ url: "https://github.com/UiPath/cli.git",
28650
+ directory: "packages/admin/identity-sdk"
28651
+ },
28652
+ publishConfig: {
28653
+ registry: "https://npm.pkg.github.com/@uipath"
28654
+ },
28655
+ keywords: [
28656
+ "uipath",
28657
+ "identity",
28658
+ "sdk"
28659
+ ],
28660
+ type: "module",
28661
+ main: "./dist/index.js",
28662
+ types: "./dist/src/index.d.ts",
28663
+ exports: {
28664
+ ".": {
28665
+ types: "./dist/src/index.d.ts",
28666
+ default: "./dist/index.js"
28667
+ }
28668
+ },
28669
+ files: [
28670
+ "dist"
28671
+ ],
28672
+ private: true,
28673
+ scripts: {
28674
+ build: "bun build ./src/index.ts --outdir dist --format esm --target node && tsc -p tsconfig.build.json --noCheck",
28675
+ generate: "bun run src/scripts/generate-sdk.ts",
28676
+ lint: "biome check .",
28677
+ test: "vitest run",
28678
+ "test:coverage": "vitest run --coverage"
28679
+ },
28680
+ devDependencies: {
28681
+ "@uipath/auth": "workspace:*",
28682
+ "@uipath/common": "workspace:*",
28683
+ "@uipath/filesystem": "workspace:*",
28684
+ "@openapitools/openapi-generator-cli": "^2.31.1",
28685
+ "@types/node": "^25.5.2",
28686
+ typescript: "^6.0.2"
28687
+ }
28688
+ };
28689
+
28690
+ // ../identity-sdk/src/user-agent.ts
28691
+ var SDK_USER_AGENT2 = getSdkUserAgentToken(package_default3);
28692
+ installSdkUserAgentHeader(BaseAPI2, SDK_USER_AGENT2);
28138
28693
 
28139
28694
  // ../identity-sdk/generated/src/models/BulkSoftDeleteCommand.ts
28140
28695
  function BulkSoftDeleteCommandToJSON(json2) {
@@ -28655,19 +29210,23 @@ class UserApi extends BaseAPI2 {
28655
29210
  async function createIdentityConfig(options) {
28656
29211
  const ctx = await getAuthContext({
28657
29212
  ensureTokenValidityMinutes: options?.loginValidity,
28658
- requireOrganizationId: true,
29213
+ requireOrganizationId: options?.organization === undefined,
28659
29214
  requireTenantName: true
28660
29215
  });
28661
- const identityBasePath = `${ctx.baseUrl}/${ctx.organizationId}/identity_`;
28662
- const headers = {
29216
+ const organizationId = options?.organization ?? ctx.organizationId;
29217
+ if (organizationId === undefined || organizationId.length === 0) {
29218
+ throw new Error("Organization ID not available. Provide --organization or log in with an organization context.");
29219
+ }
29220
+ const identityBasePath = `${ctx.baseUrl}/${organizationId}/identity_`;
29221
+ const headers = addSdkUserAgentHeader({
28663
29222
  Authorization: `Bearer ${ctx.accessToken}`
28664
- };
29223
+ }, SDK_USER_AGENT2);
28665
29224
  return {
28666
29225
  config: new Configuration2({
28667
29226
  basePath: identityBasePath,
28668
29227
  headers
28669
29228
  }),
28670
- organizationId: ctx.organizationId ?? ""
29229
+ organizationId
28671
29230
  };
28672
29231
  }
28673
29232
  async function createApiClient2(ApiClass, options) {