@uipath/cli 1.205.0-preview.277 → 1.206.0-preview.279

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 (76) hide show
  1. package/dist/{applicationinsights-s28k1t0d.js → applicationinsights-pwe8sf3y.js} +1269 -1269
  2. package/dist/{browser-strategy-6atc7v8s.js → browser-strategy-p5fhwxqj.js} +6 -7
  3. package/dist/cli-q6fp9ccp.js +23 -0
  4. package/dist/contentStore-c51xqdn2.js +41 -0
  5. package/dist/environmentInfo-fn0za9jw.js +71 -0
  6. package/dist/feedbackPrompts-t1enxv1x.js +144 -0
  7. package/dist/handlers-93z27zrr.js +805 -0
  8. package/dist/index-16d4evd1.js +1051 -0
  9. package/dist/index-1vyte4ma.js +14 -0
  10. package/dist/index-21kns9qg.js +10 -0
  11. package/dist/{index-j2tzs5k6.js → index-2j7ss97f.js} +331 -2595
  12. package/dist/index-2k8rhmad.js +274 -0
  13. package/dist/{index-30618bjs.js → index-2mm750yx.js} +174 -234
  14. package/dist/{index-622x1qb5.js → index-3fvbddpw.js} +7092 -7092
  15. package/dist/{index-d3w0wn6k.js → index-5gce5wfd.js} +16 -16
  16. package/dist/index-5j0bfd3e.js +4744 -0
  17. package/dist/index-68xmrb9x.js +237 -0
  18. package/dist/index-6wj58qka.js +59 -0
  19. package/dist/index-898c4tfz.js +668 -0
  20. package/dist/index-8gr7ny79.js +365 -0
  21. package/dist/index-99emfvtm.js +13 -0
  22. package/dist/{index-pj3g8ftz.js → index-9db5vwx9.js} +2429 -1693
  23. package/dist/index-ayg25v46.js +151 -0
  24. package/dist/index-bf0e4evz.js +6180 -0
  25. package/dist/index-bpqx6f8h.js +92 -0
  26. package/dist/index-bpxh3fqv.js +392 -0
  27. package/dist/index-cc653qc1.js +1327 -0
  28. package/dist/{index-m5nwse9v.js → index-cj4v0jct.js} +21 -69
  29. package/dist/{index-469jgr1w.js → index-dsj3jrm0.js} +105 -106
  30. package/dist/{index-1yh8g550.js → index-epsr41wx.js} +8 -12
  31. package/dist/{index-yb4er9vd.js → index-jjejkkg4.js} +474 -528
  32. package/dist/index-kg1xrq51.js +171 -0
  33. package/dist/index-m8vqyv3g.js +72 -0
  34. package/dist/index-mzqm6xfh.js +45 -0
  35. package/dist/index-nsrrst23.js +44 -0
  36. package/dist/{index-h8cph72k.js → index-nzr4mx5p.js} +2 -22
  37. package/dist/index-p9s0gyrw.js +72 -0
  38. package/dist/index-qadhm1gn.js +271 -0
  39. package/dist/index-qwbyt2q5.js +95 -0
  40. package/dist/index-rbna3w6k.js +200 -0
  41. package/dist/index-rr5hdtcy.js +95 -0
  42. package/dist/{index-qa9gftnj.js → index-xd2w5pct.js} +3 -3
  43. package/dist/index-xpdtagqw.js +30 -0
  44. package/dist/{index-925304r7.js → index-y085rpen.js} +29 -25
  45. package/dist/index-y5ncb93a.js +240 -0
  46. package/dist/index-y7d0cth0.js +93 -0
  47. package/dist/{index-hdxtgckw.js → index-z070caqq.js} +56 -12
  48. package/dist/index-zdqbp34f.js +14 -0
  49. package/dist/index.js +38 -36
  50. package/dist/install-3gw33jcf.js +558 -0
  51. package/dist/{jmespath-e4a59c8w.js → jmespath-ab6tdc42.js} +1 -1
  52. package/dist/js-yaml-0c4svjwq.js +36 -0
  53. package/dist/{mcp-jssaz3wr.js → mcp-s50h6d56.js} +236 -472
  54. package/dist/{node-strategy-ggx3nmyj.js → node-strategy-p1n8wr5s.js} +16 -19
  55. package/dist/project-context-285hydnd.js +94 -0
  56. package/dist/prompt-hxbzt92e.js +13 -0
  57. package/dist/{server-9k50dfg6.js → server-gkr3c7hv.js} +28 -43
  58. package/dist/skillCatalog-fvw4wgw1.js +22 -0
  59. package/dist/skillsService-20es18vs.js +29 -0
  60. package/dist/{stdio-tmngemcz.js → stdio-kpsab5bz.js} +2 -4
  61. package/dist/{telemetry-drain-r92f0e4r.js → telemetry-drain-bw59e8f5.js} +8 -9
  62. package/dist/tree-j4w7p0pg.js +17 -0
  63. package/dist/updateService-pq7pkd42.js +522 -0
  64. package/dist/updateService.skills-4t1s7z45.js +22 -0
  65. package/dist/updateService.tools-f7tr6kc6.js +16 -0
  66. package/package.json +2 -2
  67. package/dist/cli-yw4s6t8k.js +0 -19
  68. package/dist/index-0gctz400.js +0 -17
  69. package/dist/index-4cq44eth.js +0 -19427
  70. package/dist/index-7tshyfxx.js +0 -157
  71. package/dist/index-e3bean3d.js +0 -9867
  72. package/dist/index-g8ck9tv6.js +0 -2
  73. package/dist/index-ngs0a2he.js +0 -15
  74. package/dist/index-yc4kw997.js +0 -13
  75. package/dist/js-yaml-69tsdrrf.js +0 -37
  76. package/dist/updateService-22p6d8dm.js +0 -14
@@ -1,210 +1,195 @@
1
1
  import {
2
- AUTH_FLOW_ENV_VAR,
3
- AuthProfileValidationError,
4
- DEFAULT_AUTH_FILENAME,
5
- DEFAULT_AUTH_PROFILE,
6
- DEFAULT_ENV_FILENAME,
7
- ENV_AUTH_ENABLE_VAR,
8
- ENV_AUTH_VARS,
9
- EnvAuthConfigError,
10
- authProfileExistsAsync,
11
- deleteAuthProfileAsync,
12
- describeAuthProfilesAsync,
13
- getActiveAuthProfile,
14
- getActiveAuthProfileFilePath,
15
- getLoginStatusAsync,
16
- isEnvAuthEnabled,
17
- isTenantSelectionError,
18
- listAuthProfileNamesAsync,
19
- loadEnvFileAsync,
20
- logout,
21
- normalizeAuthProfileName,
22
- parseAuthFlow,
23
- parseJWT,
24
- readAuthFromEnv,
25
- resolveEnvFileLocationAsync,
26
- resolveEnvFilePathAsync
27
- } from "./index-30618bjs.js";
2
+ getFileSystem2,
3
+ getFileSystemAsync2
4
+ } from "./index-z070caqq.js";
28
5
  import {
29
- AGENT_DEFS,
30
- AGENT_DISPLAY_NAMES,
31
- ALIASES_BY_COMMAND,
32
- ALL_AGENTS,
33
- COMMAND_ALIASES,
34
- HIDDEN_CHANNELS,
35
- HostOwnedToolError,
36
- InstallRefusedError,
37
- PUBLIC_CHANNELS,
38
- SkillSourceError,
39
- SkillsError,
40
- SkillsRegistryAuthError,
41
- TOOLS_DIRS_ENV_VAR,
42
- TOOLS_UPDATE_PHASES,
43
- TOOLS_WHITELIST,
44
- VALID_CHANNELS,
45
- WHITELIST_BY_COMMAND,
46
- WHITELIST_BY_SHORT_NAME,
47
- buildSkillCatalog,
48
- collapsePinnedLineErrors,
49
- compareSemver,
50
- describeCandidateFailure,
51
- dist_default,
52
- dist_default1 as dist_default2,
53
- dist_default2 as dist_default3,
54
- formatVersionPin,
55
- getAvailableSkills,
56
- getContentStoreForRead,
57
- getEffectiveRegistry,
58
- getEnvToolsDirsDeclaration,
59
- getGlobalNpmUipathDir,
60
- getInstalledTools,
61
- getSkillsDestinationHint,
62
- getSkillsDir,
63
- getSkillsSourceFailureDetails,
64
- hasDistinctGlobalPath,
65
- isBundledDistribution,
66
- isDevMode,
67
- isExactPin,
68
- isPreviewVersion,
69
- isValidSemver,
70
- isValidVersionPin,
71
- loadConfigAsync,
72
- majorOf,
73
- mergeState,
74
- package_default,
75
- parsePackageSpec,
76
- promptAgentSelection,
77
- readConfigFileAt,
78
- readExtraFiles,
79
- readManifest,
80
- readState,
81
- recordToolUpdateDate,
82
- refreshGlobalNpmUipathDir,
83
- rejectIfGlobalOnly,
84
- removeFromManifest,
85
- removeSkillCatalog,
86
- resolveConfigFilePathAsync,
87
- resolveNpmPrefixForToolsDir,
88
- resolvePinnedVersion,
89
- resolveRootDir,
90
- resolveRuntimeChannel,
91
- resolveSkillSource,
92
- resolveSkillsContext,
93
- resolveSkillsTargetVersion,
94
- resolveToolPackageName,
95
- resolveUpdateChannel,
96
- runAgentInstalls,
97
- runSkillsUpdate,
98
- runToolsUpdate,
99
- runUpdate,
100
- searchSkillCatalog,
101
- skillOwnerOf,
102
- todayLocal,
103
- toolFailureRemediation,
104
- toolService,
105
- truncateVersionsForDisplay,
106
- uninstallExtraFolders,
107
- uninstallSkill,
108
- versionLinePrefix,
109
- withConfigLock,
110
- writeConfigFileAt
111
- } from "./index-e3bean3d.js";
112
- import {
113
- AuthDimensions,
114
- BaseDimensions,
115
6
  CLI_APPLICATION_NAME,
116
- CONFIG_FILENAME,
117
- Command,
7
+ BaseDimensions,
118
8
  CommandDimensions,
119
- CommonTelemetryEvents,
120
- DEFAULT_FETCH_TIMEOUT_MS,
121
- EXIT_CODES,
122
- LogLevel,
123
- OUTPUT_FORMATS,
124
- Option,
125
- OutputFormatter,
126
- Pagination,
127
- REGISTER_EXPORT,
128
- RESULTS,
9
+ AuthDimensions,
129
10
  SkillsDimensions,
130
- TELEMETRY_ARG_VALUE_WITHHELD,
131
- UIPATH_HOME_DIR,
132
11
  assertNoCuratedDimensionTargets,
133
- buildCommandTerminalTelemetryProperties,
134
- buildEnvironmentProperties,
135
- buildSkillEventTelemetryAttribution,
136
- canPrompt,
12
+ redactProperties,
13
+ catchError,
137
14
  carriedErrorCode,
138
- carriedInstructions,
139
15
  carriedRetry,
140
- catchError,
141
- commandInvocationPath,
142
- commandTelemetryName,
143
- configureLogger,
144
- describeConnectivityError,
145
- detectAgent,
146
- detectAgentVersion,
147
- emitInvocationRequest,
148
- extractCommandHelp,
149
- formatErrorChain,
150
- getCompleter,
151
- getExitCode,
152
- getHelpRequested,
153
- getOutputFormat,
154
- getOutputFormatExplicit,
16
+ carriedInstructions,
17
+ RESULTS,
18
+ Command,
19
+ Option,
20
+ setPreviewBuild,
155
21
  getOutputSink,
156
- isOutputFormat,
157
- isTelemetryDisabled,
158
- loadOutputCodecsAsync,
22
+ LogLevel,
159
23
  logger,
160
- parseBoundedInt,
161
- processContext,
162
- readStdinWithTimeout,
163
- recordExitCode,
164
- redactProperties,
165
- requireConfirmation,
166
- resolveEnvReference,
167
- runWithInvocationRequest,
24
+ configureLogger,
168
25
  runWithTimings,
169
- sanitizeTelemetryToken,
170
- setExecutionContextAuthSignal,
26
+ setTimingCommand,
27
+ suppressTimingReport,
171
28
  setExitCode,
172
- setGlobalTelemetryProperties,
173
- setHelpRequested,
174
- setInteractiveFlag,
175
- setInteractivityMode,
176
- setOutputFilter,
29
+ getExitCode,
30
+ loadOutputCodecsAsync,
177
31
  setOutputFormat,
32
+ getOutputFormat,
178
33
  setOutputFormatExplicit,
179
- setPackagerFactoryProvider,
180
- setPreviewBuild,
181
- setSdkUserAgentHostToken,
182
- setTimingCommand,
183
- splitScopeList,
184
- suppressTimingReport,
34
+ getOutputFormatExplicit,
35
+ setHelpRequested,
36
+ getHelpRequested,
37
+ setOutputFilter,
38
+ OUTPUT_FORMATS,
39
+ isOutputFormat,
185
40
  takeRecordedCommandFailureTelemetry,
41
+ buildCommandTerminalTelemetryProperties,
42
+ CommonTelemetryEvents,
43
+ detectAgent,
44
+ detectAgentVersion,
45
+ setGlobalTelemetryProperties,
46
+ isTelemetryDisabled,
186
47
  telemetry,
187
- telemetryFlushAndShutdown,
188
48
  telemetryInit,
49
+ telemetryFlushAndShutdown,
189
50
  telemetryShutdownWithoutFlush,
190
- validateOutputFilter
191
- } from "./index-pj3g8ftz.js";
51
+ EXIT_CODES,
52
+ Pagination,
53
+ validateOutputFilter,
54
+ OutputFormatter,
55
+ configureProjectContextTelemetry,
56
+ buildSkillEventTelemetryAttribution,
57
+ sanitizeTelemetryToken,
58
+ commandTelemetryName,
59
+ commandInvocationPath,
60
+ runWithInvocationRequest,
61
+ emitInvocationRequest,
62
+ processContext,
63
+ TELEMETRY_ARG_VALUE_WITHHELD,
64
+ extractCommandHelp,
65
+ requireConfirmation,
66
+ UIPATH_HOME_DIR,
67
+ CONFIG_FILENAME,
68
+ setInteractivityMode,
69
+ setInteractiveFlag,
70
+ canPrompt,
71
+ parseBoundedInt,
72
+ setSdkUserAgentHostToken,
73
+ readStdinWithTimeout,
74
+ setPackagerFactoryProvider
75
+ } from "./index-9db5vwx9.js";
76
+ import {
77
+ VALID_CHANNELS,
78
+ HIDDEN_CHANNELS,
79
+ PUBLIC_CHANNELS,
80
+ withConfigLock,
81
+ readConfigFileAt,
82
+ writeConfigFileAt,
83
+ resolveConfigFilePathAsync,
84
+ loadConfigAsync,
85
+ isValidVersionPin,
86
+ majorOf,
87
+ resolvePinnedVersion,
88
+ isExactPin,
89
+ versionLinePrefix,
90
+ formatVersionPin
91
+ } from "./index-qadhm1gn.js";
92
+ import {
93
+ storage,
94
+ isInsideNodeModules,
95
+ isLocalWorkspaceDir,
96
+ discoverToolPaths,
97
+ importTool,
98
+ importPackagerTool,
99
+ importToolLibraryModule,
100
+ resolveToolsDirs
101
+ } from "./index-bpxh3fqv.js";
102
+ import {
103
+ DEFAULT_AUTH_PROFILE2,
104
+ INHERITED_AUTH_PROFILE_ENV2,
105
+ AuthProfileValidationError2,
106
+ normalizeAuthProfileName2,
107
+ getActiveAuthProfile2,
108
+ listAuthProfileNamesAsync2,
109
+ authProfileExistsAsync2,
110
+ deleteAuthProfileAsync2,
111
+ parseJWT2,
112
+ isEnvAuthEnabled2,
113
+ DEFAULT_AUTH_FILENAME2,
114
+ getLoginStatusAsync2,
115
+ describeAuthProfilesAsync2,
116
+ logout2
117
+ } from "./index-2mm750yx.js";
118
+ import {
119
+ buildIssueUrl,
120
+ VALID_TYPES,
121
+ VALID_PRIORITIES,
122
+ normalizeUrl,
123
+ createFeedbackIssue,
124
+ uploadAttachment,
125
+ validateAttachment
126
+ } from "./index-68xmrb9x.js";
127
+ import {
128
+ ALL_AGENTS,
129
+ AGENT_DISPLAY_NAMES,
130
+ AGENT_DEFS,
131
+ getSkillsDir,
132
+ getSkillsDestinationHint,
133
+ hasDistinctGlobalPath,
134
+ skillOwnerOf,
135
+ uninstallExtraFolders,
136
+ uninstallSkill,
137
+ rejectIfGlobalOnly
138
+ } from "./index-898c4tfz.js";
139
+ import {
140
+ isRegistryTlsError
141
+ } from "./index-qwbyt2q5.js";
142
+ import {
143
+ refreshGlobalNpmUipathDir,
144
+ TOOLS_DIRS_ENV_VAR,
145
+ getEnvToolsDirsDeclaration,
146
+ resolveNpmPrefixForToolsDir,
147
+ InstallRefusedError,
148
+ isBundledDistribution,
149
+ TOOLS_WHITELIST,
150
+ COMMAND_ALIASES,
151
+ ALIASES_BY_COMMAND,
152
+ WHITELIST_BY_COMMAND,
153
+ isValidSemver,
154
+ compareSemver,
155
+ resolveToolPackageName,
156
+ parsePackageSpec,
157
+ describeCandidateFailure,
158
+ getEffectiveRegistry,
159
+ isDevMode,
160
+ HostOwnedToolError,
161
+ truncateVersionsForDisplay,
162
+ toolService
163
+ } from "./index-16d4evd1.js";
164
+ import {
165
+ getInstalledTools,
166
+ toolFailureRemediation,
167
+ collapsePinnedLineErrors,
168
+ todayLocal,
169
+ readState,
170
+ recordToolUpdateDate,
171
+ mergeState
172
+ } from "./index-kg1xrq51.js";
192
173
  import {
193
- isBrowser
194
- } from "./index-0gctz400.js";
174
+ resolveUpdateChannel,
175
+ resolveRuntimeChannel,
176
+ isPreviewVersion
177
+ } from "./index-mzqm6xfh.js";
195
178
  import {
196
- getFileSystem,
197
- getFileSystemAsync
198
- } from "./index-hdxtgckw.js";
179
+ getSkillsSourceFailureDetails
180
+ } from "./index-6wj58qka.js";
181
+ import {
182
+ SkillSourceError,
183
+ SkillsRegistryAuthError
184
+ } from "./index-nsrrst23.js";
199
185
  import {
200
- AUTH_CANCELLED_ERROR_CODE,
201
- AUTH_RECLAIMED_ERROR_CODE,
202
- AUTH_TIMEOUT_ERROR_CODE,
203
- DEFAULT_AUTH_TIMEOUT_MS
204
- } from "./index-yc4kw997.js";
186
+ package_default
187
+ } from "./index-p9s0gyrw.js";
205
188
  import {
206
- __require
207
- } from "./index-1yh8g550.js";
189
+ COPYRIGHT_NOTICE,
190
+ populateTelemetryAuthContext,
191
+ trackAuthLogout
192
+ } from "./index-ayg25v46.js";
208
193
  // ../executor/project-executor/src/services/executor-tool-module.ts
209
194
  var EXECUTOR_FACTORY_EXPORT = "createExecutorFactory";
210
195
  function isExecutorFactoryModule(module) {
@@ -268,55 +253,13 @@ function registerExecutorFactoryFromModule(module, source) {
268
253
  executorsFactoryRepository.registerProjectExecutorFactory(factory);
269
254
  return factory;
270
255
  }
271
- // src/services/storage.ts
272
- class GeneralizedStorage {
273
- _initPromise;
274
- async init() {
275
- if (this._initPromise)
276
- return this._initPromise;
277
- const promise = getFileSystemAsync().then(() => {
278
- return;
279
- });
280
- this._initPromise = promise;
281
- promise.catch(() => {
282
- this._initPromise = undefined;
283
- });
284
- return promise;
285
- }
286
- get fs() {
287
- return getFileSystem();
288
- }
289
- async read(path) {
290
- const res = await this.fs.readFile(path);
291
- if (res === null)
292
- return null;
293
- if (typeof res === "string") {
294
- return new TextEncoder().encode(res);
295
- }
296
- return res;
297
- }
298
- async readText(path) {
299
- return this.fs.readFile(path, "utf-8");
300
- }
301
- async write(path, content) {
302
- await this.fs.writeFile(path, content);
303
- }
304
- async exists(path) {
305
- return this.fs.exists(path);
306
- }
307
- async readdir(path) {
308
- return this.fs.readdir(path);
309
- }
310
- async remove(path) {
311
- if (!await this.fs.exists(path))
312
- return;
313
- await this.fs.rm(path);
314
- }
315
- async mkdir(path) {
316
- await this.fs.mkdir(path);
317
- }
256
+ // src/services/project-context-telemetry.ts
257
+ function configureHostProjectContextTelemetry(program) {
258
+ configureProjectContextTelemetry(program, async (projectDirectory) => {
259
+ const { readProjectSolutionContext } = await import("./project-context-285hydnd.js");
260
+ return readProjectSolutionContext(projectDirectory);
261
+ });
318
262
  }
319
- var storage = new GeneralizedStorage;
320
263
 
321
264
  // src/utils/globalOptions.ts
322
265
  var VALID_LOG_LEVELS = {
@@ -413,16 +356,16 @@ function tryParseLogFile(state, args, i) {
413
356
  }
414
357
  return NOT_CONSUMED;
415
358
  }
416
- function applyProfileValue(state, value) {
359
+ function applyProfileValue(state, value, source = 0 /* Flag */) {
417
360
  let normalized;
418
361
  try {
419
- normalized = normalizeAuthProfileName(value);
362
+ normalized = normalizeAuthProfileName2(value);
420
363
  } catch (error) {
421
- if (!(error instanceof AuthProfileValidationError)) {
364
+ if (!(error instanceof AuthProfileValidationError2)) {
422
365
  throw error;
423
366
  }
424
367
  state.profile = undefined;
425
- state.profileError ??= error.message;
368
+ state.profileError ??= source === 1 /* Env */ ? `${INHERITED_AUTH_PROFILE_ENV2}: ${error.message}` : error.message;
426
369
  return;
427
370
  }
428
371
  if (state.profileError !== undefined) {
@@ -432,6 +375,7 @@ function applyProfileValue(state, value) {
432
375
  }
433
376
  function tryParseProfile(state, args, i) {
434
377
  if (args[i] === "--profile") {
378
+ state.sawProfileOption = true;
435
379
  if (i + 1 >= args.length) {
436
380
  state.profile = undefined;
437
381
  state.profileError ??= "error: option '--profile <name>' argument missing";
@@ -441,6 +385,7 @@ function tryParseProfile(state, args, i) {
441
385
  return { consumed: true, advance: 1 };
442
386
  }
443
387
  if (args[i]?.startsWith("--profile=")) {
388
+ state.sawProfileOption = true;
444
389
  applyProfileValue(state, args[i].substring("--profile=".length));
445
390
  return { consumed: true, advance: 0 };
446
391
  }
@@ -478,6 +423,7 @@ function stripGlobalOptions(args) {
478
423
  filter: undefined,
479
424
  logLevel: undefined,
480
425
  logFile: undefined,
426
+ sawProfileOption: false,
481
427
  profile: undefined,
482
428
  profileError: undefined,
483
429
  interactive: undefined
@@ -496,6 +442,10 @@ function stripGlobalOptions(args) {
496
442
  state.cleaned.push(args[i]);
497
443
  }
498
444
  }
445
+ const envProfile = process.env?.[INHERITED_AUTH_PROFILE_ENV2];
446
+ if (!state.sawProfileOption && envProfile) {
447
+ applyProfileValue(state, envProfile, 1 /* Env */);
448
+ }
499
449
  const envDefault = process.env?.UIP_DEFAULT_OUTPUT;
500
450
  const resolvedFormat = state.format ?? (envDefault && isOutputFormat(envDefault) ? envDefault : "json");
501
451
  return {
@@ -528,9 +478,6 @@ function isHelpOrVersionInvocation(args) {
528
478
  return false;
529
479
  }
530
480
 
531
- // src/copyright.ts
532
- var COPYRIGHT_NOTICE = "© 2026 UiPath";
533
-
534
481
  // src/utils/helpFormatter.ts
535
482
  var OUTPUT_FLAG = `--output <${OUTPUT_FORMATS.join("|")}>`;
536
483
  var GLOBAL_OPTIONS = [
@@ -758,6 +705,9 @@ function stringifyCell(value) {
758
705
  return JSON.stringify(value);
759
706
  return String(value);
760
707
  }
708
+ function isValueList(data) {
709
+ return typeof data[0] === "string";
710
+ }
761
711
  function renderExampleTable(items, maxWidth) {
762
712
  if (items.length === 0)
763
713
  return [];
@@ -808,15 +758,15 @@ function renderExampleObject(data, maxWidth) {
808
758
  const val = data[key];
809
759
  if (Array.isArray(val) && val.length > 0 && val.every(isPlainObject)) {
810
760
  lines.push(`${key}:`);
811
- for (const line2 of renderExampleTable(val, subWidth)) {
812
- lines.push(`${subIndent}${line2}`);
761
+ for (const line of renderExampleTable(val, subWidth)) {
762
+ lines.push(`${subIndent}${line}`);
813
763
  }
814
764
  continue;
815
765
  }
816
766
  if (isPlainObject(val)) {
817
767
  lines.push(`${key}:`);
818
- for (const line2 of renderExampleObject(val, subWidth)) {
819
- lines.push(`${subIndent}${line2}`);
768
+ for (const line of renderExampleObject(val, subWidth)) {
769
+ lines.push(`${subIndent}${line}`);
820
770
  }
821
771
  continue;
822
772
  }
@@ -841,7 +791,7 @@ function buildExampleLines(examples, contentWidth) {
841
791
  lines.push(`${indent}$ ${example.Command}`);
842
792
  lines.push("");
843
793
  const data = example.Output.Data;
844
- const outputLines = Array.isArray(data) ? renderExampleTable(data, innerWidth) : renderExampleObject(data, innerWidth);
794
+ const outputLines = !Array.isArray(data) ? renderExampleObject(data, innerWidth) : isValueList(data) ? data.flatMap((value) => wrapText(value, innerWidth)) : renderExampleTable(data, innerWidth);
845
795
  for (const line of outputLines) {
846
796
  lines.push(`${indent}${line}`);
847
797
  }
@@ -851,7 +801,7 @@ function buildExampleLines(examples, contentWidth) {
851
801
  }
852
802
  return lines;
853
803
  }
854
- function buildTableHelpSections(cmd, helper, isBrowser2) {
804
+ function buildTableHelpSections(cmd, helper, isBrowser) {
855
805
  const contentWidth = Math.max(getHelpWidth() - 4, 16);
856
806
  const baseHelp = extractCommandHelp(cmd, helper);
857
807
  const sections = [];
@@ -928,7 +878,7 @@ function buildTableHelpSections(cmd, helper, isBrowser2) {
928
878
  Lines: buildExampleLines(baseHelp.Examples, contentWidth)
929
879
  });
930
880
  }
931
- if (isRootCommand(cmd) && !isBrowser2) {
881
+ if (isRootCommand(cmd) && !isBrowser) {
932
882
  sections.push({
933
883
  Title: "Environment",
934
884
  Lines: renderStackedRows(ENVIRONMENT_ROWS, contentWidth)
@@ -942,7 +892,7 @@ function buildTableHelpSections(cmd, helper, isBrowser2) {
942
892
  }
943
893
  return sections;
944
894
  }
945
- function renderTableHelp(cmd, helper, isBrowser2) {
895
+ function renderTableHelp(cmd, helper, isBrowser) {
946
896
  const width = getHelpWidth();
947
897
  const description = helper.commandDescription(cmd);
948
898
  const parts = [];
@@ -951,7 +901,7 @@ function renderTableHelp(cmd, helper, isBrowser2) {
951
901
  } else {
952
902
  parts.push(renderCommandHeader(getCommandPath(cmd), description, width));
953
903
  }
954
- for (const section of buildTableHelpSections(cmd, helper, isBrowser2)) {
904
+ for (const section of buildTableHelpSections(cmd, helper, isBrowser)) {
955
905
  parts.push(renderSection(section, width));
956
906
  }
957
907
  return `${parts.join(`
@@ -981,11 +931,11 @@ function stripHelpTextEventsForStructuredHelp(root) {
981
931
  stack.push(...cmd.commands);
982
932
  }
983
933
  }
984
- function createHelpConfiguration(isBrowser2) {
934
+ function createHelpConfiguration(isBrowser) {
985
935
  const config = {
986
936
  formatHelp(cmd, helper) {
987
937
  if (rendersTableHelp()) {
988
- return renderTableHelp(cmd, helper, isBrowser2);
938
+ return renderTableHelp(cmd, helper, isBrowser);
989
939
  }
990
940
  const baseHelp = extractCommandHelp(cmd, helper);
991
941
  const subcommands = helper.visibleCommands(cmd).map((sub) => {
@@ -1006,7 +956,7 @@ function createHelpConfiguration(isBrowser2) {
1006
956
  };
1007
957
  if (isRootCommand(cmd)) {
1008
958
  helpData.GettingStarted = GETTING_STARTED_ROWS;
1009
- if (!isBrowser2)
959
+ if (!isBrowser)
1010
960
  helpData.Environment = ENVIRONMENT_ROWS;
1011
961
  }
1012
962
  const output = {
@@ -1017,7 +967,7 @@ function createHelpConfiguration(isBrowser2) {
1017
967
  return OutputFormatter.formatToString(output);
1018
968
  }
1019
969
  };
1020
- if (isBrowser2) {
970
+ if (isBrowser) {
1021
971
  config.styleTitle = (str) => str;
1022
972
  config.styleCommandText = (str) => str;
1023
973
  config.styleCommandDescription = (str) => str;
@@ -1124,6 +1074,9 @@ async function handleParseError(error, cleanedArgs, context, telemetryOptions) {
1124
1074
  function findUnknownToken(root, positionals) {
1125
1075
  let current = root;
1126
1076
  for (const token of positionals) {
1077
+ if (current.commands.length === 0 || current.registeredArguments.length > 0) {
1078
+ return;
1079
+ }
1127
1080
  const child = current.commands.find((cmd) => cmd.name() === token || cmd.aliases().includes(token));
1128
1081
  if (!child) {
1129
1082
  return token;
@@ -1220,15 +1173,6 @@ function runCliInvocation(fn) {
1220
1173
  return runWithTimings(TIMING_FALLBACK_COMMAND, () => runWithInvocationRequest(fn));
1221
1174
  }
1222
1175
  var TIMING_FALLBACK_COMMAND = "uip";
1223
- function withRecordedExit(context) {
1224
- return {
1225
- ...context,
1226
- exit: (code) => {
1227
- recordExitCode(code);
1228
- context.exit(code);
1229
- }
1230
- };
1231
- }
1232
1176
  function errorMessage(error) {
1233
1177
  return error instanceof Error ? error.message : String(error);
1234
1178
  }
@@ -1255,6 +1199,7 @@ function validateAndSetOutputFilter(filter, context) {
1255
1199
  async function initProgram(context, hooks = {}) {
1256
1200
  setSdkUserAgentHostToken(`uip/${package_default.version}`);
1257
1201
  const program = new Command;
1202
+ configureHostProjectContextTelemetry(program);
1258
1203
  program.name("uip").description(`UiPath CLI ${package_default.version}`).version(package_default.version, "-v, --version").enablePositionalOptions();
1259
1204
  const globalOptions = stripGlobalOptions(context.args);
1260
1205
  const {
@@ -1354,7 +1299,8 @@ async function initProgram(context, hooks = {}) {
1354
1299
  }
1355
1300
  const telemetryPromise = isHelpOrVersionInvocation(cleanedArgs) ? Promise.resolve() : telemetryInit({
1356
1301
  version: package_default.version,
1357
- defaultProperties: defaultTelemetryProperties
1302
+ defaultProperties: defaultTelemetryProperties,
1303
+ appInsights: !context.capabilities.isBrowser
1358
1304
  }).then(() => logger.debug("Telemetry initialized")).then(async () => {
1359
1305
  if (hooks.afterTelemetryInit) {
1360
1306
  await hooks.afterTelemetryInit();
@@ -1420,938 +1366,19 @@ async function parseAndExit(program, cleanedArgs, context) {
1420
1366
  await telemetryFlushAndShutdown();
1421
1367
  }
1422
1368
 
1423
- // src/utils/localWorkspace.ts
1424
- var MAX_WALK_DEPTH = 10;
1425
- var CLI_PACKAGE_NAME = "@uipath/cli";
1426
- function isInsideNodeModules(dir) {
1427
- const segments = dir.replace(/\\/g, "/").split("/").filter(Boolean);
1428
- return segments.includes("node_modules");
1429
- }
1430
- async function isLocalWorkspaceDir(dir) {
1431
- const fs = getFileSystem();
1432
- const pkgJsonPath = fs.path.join(dir, "package.json");
1433
- const [, exists] = await catchError(fs.exists(pkgJsonPath));
1434
- if (!exists)
1435
- return false;
1436
- const [, raw] = await catchError(fs.readFile(pkgJsonPath, "utf-8"));
1437
- if (!raw)
1438
- return false;
1439
- const [, pkg] = catchError(() => JSON.parse(raw));
1440
- if (!pkg)
1441
- return false;
1442
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
1443
- return CLI_PACKAGE_NAME in deps || !!pkg.workspaces;
1444
- }
1445
- async function hasGoverningLocalProject(startDir) {
1446
- const fs = getFileSystem();
1447
- const { dirname } = fs.path;
1448
- let path = startDir;
1449
- for (let i = 0;i < MAX_WALK_DEPTH; i++) {
1450
- if (!isInsideNodeModules(path) && await isLocalWorkspaceDir(path)) {
1451
- return true;
1452
- }
1453
- const parent = dirname(path);
1454
- if (parent === path)
1455
- break;
1456
- path = parent;
1457
- }
1458
- return false;
1459
- }
1460
-
1461
- // src/utils/toolLoader.ts
1462
- function isRunningFromSource() {
1463
- const [error, mainUrl] = catchError(() => import.meta.url);
1464
- if (error) {
1465
- return false;
1466
- }
1467
- return mainUrl.endsWith(".ts");
1468
- }
1469
- var _isRunningFromSource = isRunningFromSource();
1470
- var _isBrowser = !(typeof process !== "undefined" && process.versions && process.versions.node);
1471
- function joinPath(...parts) {
1472
- return parts.filter((p) => p).join("/").replace(/\/+/g, "/");
1473
- }
1474
- async function discoverToolPaths(toolsDirs) {
1475
- const [initError] = await catchError(storage.init());
1476
- if (initError) {
1477
- logger.error("Storage initialization failed:", initError);
1478
- return [];
1479
- }
1480
- const dirs = Array.isArray(toolsDirs) ? toolsDirs : [toolsDirs];
1481
- const discovered = [];
1482
- const seenPrefixes = new Set;
1483
- for (const toolsDir of dirs) {
1484
- if (!await storage.exists(toolsDir)) {
1485
- logger.debug(`Tools directory does not exist, skipping: ${toolsDir}`);
1486
- continue;
1487
- }
1488
- const toolNames = [...WHITELIST_BY_SHORT_NAME.keys()];
1489
- const resolvedPaths = await Promise.all(toolNames.map(async (toolName) => {
1490
- const toolDir = joinPath(toolsDir, toolName);
1491
- const possiblePaths = _isRunningFromSource ? [
1492
- joinPath(toolDir, "src", "tool.ts"),
1493
- joinPath(toolDir, "dist", "tool.js"),
1494
- joinPath(toolDir, "tool.js")
1495
- ] : [
1496
- joinPath(toolDir, "dist", "tool.js"),
1497
- joinPath(toolDir, "tool.js"),
1498
- joinPath(toolDir, "src", "tool.ts")
1499
- ];
1500
- const factoryPaths = _isRunningFromSource ? [
1501
- joinPath(toolDir, "src", "packager-tool.ts"),
1502
- joinPath(toolDir, "dist", "packager-tool.js")
1503
- ] : [
1504
- joinPath(toolDir, "dist", "packager-tool.js"),
1505
- joinPath(toolDir, "src", "packager-tool.ts")
1506
- ];
1507
- const [existResults, factoryExistResults, pkgJson] = await Promise.all([
1508
- Promise.all(possiblePaths.map((p) => storage.exists(p))),
1509
- Promise.all(factoryPaths.map((p) => storage.exists(p))),
1510
- storage.readText(joinPath(toolDir, "package.json")).catch(() => null)
1511
- ]);
1512
- const foundIndex = existResults.indexOf(true);
1513
- const factoryIndex = factoryExistResults.indexOf(true);
1514
- let description = "";
1515
- let version = "";
1516
- if (pkgJson) {
1517
- const [parseErr, pkg] = catchError(() => JSON.parse(pkgJson));
1518
- if (!parseErr) {
1519
- description = pkg.description ?? "";
1520
- version = pkg.version ?? "";
1521
- }
1522
- }
1523
- return {
1524
- toolName,
1525
- toolPath: foundIndex >= 0 ? possiblePaths[foundIndex] : null,
1526
- packagerToolPath: factoryIndex >= 0 ? factoryPaths[factoryIndex] : undefined,
1527
- description,
1528
- version
1529
- };
1530
- }));
1531
- for (const {
1532
- toolName,
1533
- toolPath,
1534
- packagerToolPath,
1535
- description,
1536
- version
1537
- } of resolvedPaths) {
1538
- if (!toolPath) {
1539
- continue;
1540
- }
1541
- const packageName = WHITELIST_BY_SHORT_NAME.get(toolName);
1542
- const commandPrefix = packageName ? TOOLS_WHITELIST.get(packageName) : undefined;
1543
- if (!commandPrefix || !packageName) {
1544
- logger.warn(`Tool '${toolName}' found at ${toolPath} but not in whitelist, skipping`);
1545
- continue;
1546
- }
1547
- if (seenPrefixes.has(commandPrefix)) {
1548
- logger.info(`Tool ${toolName} (command '${commandPrefix}') already found from a higher-priority path, skipping`);
1549
- continue;
1550
- }
1551
- seenPrefixes.add(commandPrefix);
1552
- logger.debug(`Discovered tool '${toolName}' v${version || "unknown"} at ${toolPath}`);
1553
- discovered.push({
1554
- toolName,
1555
- toolPath,
1556
- commandPrefix,
1557
- packageName,
1558
- description,
1559
- version,
1560
- packagerToolPath
1561
- });
1562
- }
1563
- }
1564
- return discovered;
1565
- }
1566
- async function importModuleByPath(modulePath) {
1567
- const savedTrackedAction = Command.prototype.trackedAction;
1568
- const [error, mod] = await catchError((async () => {
1569
- if (_isBrowser) {
1570
- const content = await storage.readText(modulePath);
1571
- if (!content)
1572
- return;
1573
- const blob = new Blob([content], { type: "text/javascript" });
1574
- const blobUrl = URL.createObjectURL(blob);
1575
- const [importError, imported] = await catchError(import(blobUrl));
1576
- URL.revokeObjectURL(blobUrl);
1577
- if (importError)
1578
- throw importError;
1579
- return imported;
1580
- } else {
1581
- const { pathToFileURL } = await import("node:url");
1582
- const fileUrl = pathToFileURL(modulePath).href;
1583
- return await import(fileUrl);
1584
- }
1585
- })());
1586
- if (savedTrackedAction && Command.prototype.trackedAction !== savedTrackedAction) {
1587
- Command.prototype.trackedAction = savedTrackedAction;
1588
- logger.warn(`Import of ${modulePath} overwrote Command.prototype.trackedAction — restored CLI version.`);
1589
- }
1590
- if (error)
1591
- throw error;
1592
- return mod;
1593
- }
1594
- async function importTool(discovered, options = {}) {
1595
- const { toolName, toolPath } = discovered;
1596
- logger.debug(`Loading tool '${toolName}' from ${toolPath}`);
1597
- const [error, toolModule] = await catchError(importModuleByPath(toolPath));
1598
- if (error) {
1599
- logger.error(`Failed to load tool ${toolName} (version: ${discovered.version || "unknown"}, path: ${toolPath}):`, error);
1600
- if (options.throwOnLoadError) {
1601
- throw error;
1602
- }
1603
- return;
1604
- }
1605
- const { metadata, registerCommands } = toolModule ?? {};
1606
- if (!metadata || !registerCommands) {
1607
- logger.warn(`Tool ${toolName} missing required exports (metadata or registerCommands), skipping`);
1608
- return;
1609
- }
1610
- logger.debug(`Tool '${toolName}' loaded successfully (prefix: ${metadata.commandPrefix}, version: ${metadata.version ?? "unknown"})`);
1611
- return { metadata, registerCommands };
1612
- }
1613
- async function importPackagerTool(discovered) {
1614
- const { toolName, packagerToolPath } = discovered;
1615
- if (!packagerToolPath)
1616
- return;
1617
- logger.debug(`Loading packager factory for '${toolName}' from ${packagerToolPath}`);
1618
- const [error, mod] = await catchError(importModuleByPath(packagerToolPath));
1619
- if (error) {
1620
- throw new Error(`Failed to load packager factory for '${toolName}' from ${packagerToolPath}: ${error instanceof Error ? error.message : error}`);
1621
- }
1622
- const register = mod?.[REGISTER_EXPORT];
1623
- if (typeof register !== "function") {
1624
- logger.debug(`Packager factory entry point for '${toolName}' (${packagerToolPath}) has no ` + `'${REGISTER_EXPORT}' export — treating it as a legacy entry point that ` + "registered its factories at import.");
1625
- return;
1626
- }
1627
- const [registerError] = catchError(() => {
1628
- register();
1629
- });
1630
- if (registerError) {
1631
- throw new Error(`Failed to register packager factories for '${toolName}' from ${packagerToolPath}: ${registerError.message}`);
1632
- }
1633
- }
1634
- async function importToolLibraryModule(discovered, moduleName) {
1635
- const { toolName, toolPath } = discovered;
1636
- if (!/^[a-z0-9-]+$/.test(moduleName)) {
1637
- throw new Error(`Invalid tool module name '${moduleName}'.`);
1638
- }
1639
- const modulePath = toolPath.replace(/tool\.(ts|js)$/, `${moduleName}.$1`);
1640
- if (modulePath === toolPath || !await storage.exists(modulePath)) {
1641
- throw new Error(`Tool '${toolName}' has no '${moduleName}' entry point next to ${toolPath}.`);
1642
- }
1643
- logger.debug(`Loading '${moduleName}' for '${toolName}' from ${modulePath}`);
1644
- const [error, mod] = await catchError(importModuleByPath(modulePath));
1645
- if (error) {
1646
- throw new Error(`Failed to load '${moduleName}' for '${toolName}' from ${modulePath}: ${error instanceof Error ? error.message : error}`);
1647
- }
1648
- return mod;
1649
- }
1650
- async function findNearestToolsDir(startDir, seen) {
1651
- const fs = getFileSystem();
1652
- const { dirname, join } = fs.path;
1653
- const results = [];
1654
- let searchPath = startDir;
1655
- for (let i = 0;i < MAX_WALK_DEPTH; i++) {
1656
- const candidate = join(searchPath, "node_modules", "@uipath");
1657
- const [, exists] = await catchError(fs.exists(candidate));
1658
- if (exists) {
1659
- if (seen.has(candidate)) {
1660
- break;
1661
- }
1662
- seen.add(candidate);
1663
- results.push(candidate);
1664
- if (!isInsideNodeModules(searchPath)) {
1665
- break;
1666
- }
1667
- logger.debug("Search path is inside node_modules, continuing walk for hoisted packages");
1668
- }
1669
- const parentPath = dirname(searchPath);
1670
- if (parentPath === searchPath) {
1671
- break;
1672
- }
1673
- searchPath = parentPath;
1674
- }
1675
- return results;
1676
- }
1677
- async function findNearestLocalCliToolsDir(startDir) {
1678
- const fs = getFileSystem();
1679
- const { dirname, join } = fs.path;
1680
- let searchPath = startDir;
1681
- for (let i = 0;i < MAX_WALK_DEPTH; i++) {
1682
- const candidate = join(searchPath, "node_modules", "@uipath");
1683
- const cliPackageJson = join(candidate, "cli", "package.json");
1684
- const [error, exists] = await catchError(fs.exists(cliPackageJson));
1685
- if (error) {
1686
- logger.debug(`fs.exists check failed for ${cliPackageJson}: ${String(error)}`);
1687
- } else if (exists) {
1688
- return candidate;
1689
- }
1690
- const parentPath = dirname(searchPath);
1691
- if (parentPath === searchPath) {
1692
- break;
1693
- }
1694
- searchPath = parentPath;
1695
- }
1696
- return null;
1697
- }
1698
- async function resolveToolsDirs(cliFilePath, cwd) {
1699
- const fs = getFileSystem();
1700
- const { dirname } = fs.path;
1701
- const seen = new Set;
1702
- const dirs = [];
1703
- const cliDir = dirname(cliFilePath);
1704
- const declaration = await getEnvToolsDirsDeclaration();
1705
- if (declaration) {
1706
- logger.debug(`Using only the host-declared tool directories: [${declaration.dirs.join(", ")}]`);
1707
- return [...declaration.dirs];
1708
- }
1709
- const localCliToolsDir = await findNearestLocalCliToolsDir(cwd);
1710
- if (localCliToolsDir) {
1711
- seen.add(localCliToolsDir);
1712
- dirs.push(localCliToolsDir);
1713
- logger.debug("CWD has a local @uipath/cli install; skipping CLI-path and global tool discovery");
1714
- return dirs;
1715
- }
1716
- dirs.push(...await findNearestToolsDir(cliDir, seen));
1717
- dirs.push(...await findNearestToolsDir(cwd, seen));
1718
- if (!await hasGoverningLocalProject(cliDir) && !await dirsContainAnyPlugin(dirs)) {
1719
- const globalUipath = await getGlobalNpmUipathDir();
1720
- if (globalUipath && !seen.has(globalUipath)) {
1721
- seen.add(globalUipath);
1722
- dirs.push(globalUipath);
1723
- }
1724
- }
1725
- return dirs;
1726
- }
1727
- async function dirsContainAnyPlugin(dirs) {
1728
- if (dirs.length === 0)
1729
- return false;
1730
- const fs = getFileSystem();
1731
- for (const dir of dirs) {
1732
- const [error, entries] = await catchError(fs.readdir(dir));
1733
- if (error) {
1734
- logger.debug(`fs.readdir failed for ${dir}: ${String(error)}`);
1735
- continue;
1736
- }
1737
- for (const entry of entries) {
1738
- if (WHITELIST_BY_SHORT_NAME.has(entry))
1739
- return true;
1740
- }
1741
- }
1742
- return false;
1743
- }
1744
-
1745
- // src/commands/completion/tree.ts
1746
- var isHiddenCommand = (cmd) => cmd._hidden === true;
1747
- function walkCommand(cmd) {
1748
- const options = cmd.options.map((o) => ({
1749
- flags: o.flags,
1750
- long: o.long?.replace(/^--/, "") ?? "",
1751
- short: o.short?.replace(/^-/, "") ?? "",
1752
- description: o.description,
1753
- completer: getCompleter(o)
1754
- }));
1755
- return {
1756
- name: cmd.name(),
1757
- description: cmd.description().split(`
1758
- `)[0],
1759
- subcommands: cmd.commands.filter((c) => !isHiddenCommand(c)).map(walkCommand),
1760
- options
1761
- };
1762
- }
1763
- async function buildFullTree(program, discovered) {
1764
- const root = walkCommand(program);
1765
- for (const entry of discovered) {
1766
- const tool = await importTool(entry, { throwOnLoadError: true });
1767
- if (!tool) {
1768
- logger.debug(`Skipping tool ${entry.toolName}: import returned null`);
1769
- continue;
1770
- }
1771
- const shadow = new Command(tool.metadata.commandPrefix).description(tool.metadata.description);
1772
- const [regErr] = await catchError(tool.registerCommands(shadow));
1773
- if (regErr) {
1774
- logger.debug(`Skipping tool ${entry.toolName}: ${regErr.message}`);
1775
- continue;
1776
- }
1777
- const toolNode = walkCommand(shadow);
1778
- const idx = root.subcommands.findIndex((n) => n.name === entry.commandPrefix);
1779
- if (idx >= 0) {
1780
- root.subcommands[idx] = toolNode;
1781
- } else {
1782
- root.subcommands.push(toolNode);
1783
- }
1784
- }
1785
- return root;
1786
- }
1787
- function detectShell() {
1788
- const raw = process.env.SHELL ?? "";
1789
- const shell = raw.includes("/") ? raw.slice(raw.lastIndexOf("/") + 1) : raw;
1790
- if (shell === "zsh")
1791
- return "zsh";
1792
- if (shell === "fish")
1793
- return "fish";
1794
- if (shell === "pwsh")
1795
- return "pwsh";
1796
- if (shell === "bash")
1797
- return "bash";
1798
- if (process.platform === "win32" || process.env.PSModulePath)
1799
- return "pwsh";
1800
- return "bash";
1801
- }
1802
- var posixSq = (s) => s.replace(/'/g, "'\\''");
1803
-
1804
- // src/commands/completion/bash.ts
1805
- function generateBash(root) {
1806
- const bin = root.name;
1807
- const fnName = `_${bin.replace(/-/g, "_")}`;
1808
- const lines = [];
1809
- lines.push(`# Generated by: ${bin} completion bash`);
1810
- lines.push(`# Install: ${bin} completion (writes a managed block in ~/.bashrc that sources this file)`);
1811
- lines.push("");
1812
- const lookup = {};
1813
- const optLookup = {};
1814
- function collect(node, path) {
1815
- if (node.subcommands.length > 0) {
1816
- lookup[path] = node.subcommands.map((s) => s.name).join(" ");
1817
- }
1818
- if (node.options.length > 0) {
1819
- optLookup[path] = node.options.map((o) => o.long ? `--${o.long}` : `-${o.short}`).join(" ");
1820
- }
1821
- for (const sub of node.subcommands) {
1822
- collect(sub, `${path} ${sub.name}`);
1823
- }
1824
- }
1825
- collect(root, bin);
1826
- lines.push(`${fnName}_subs() {`);
1827
- lines.push(' case "$1" in');
1828
- for (const [p, subs] of Object.entries(lookup)) {
1829
- lines.push(` '${posixSq(p)}') echo '${posixSq(subs)}' ;;`);
1830
- }
1831
- lines.push(" esac");
1832
- lines.push("}");
1833
- lines.push("");
1834
- lines.push(`${fnName}_opts() {`);
1835
- lines.push(' case "$1" in');
1836
- for (const [p, opts] of Object.entries(optLookup)) {
1837
- lines.push(` '${posixSq(p)}') echo '${posixSq(opts)}' ;;`);
1838
- }
1839
- lines.push(" esac");
1840
- lines.push("}");
1841
- lines.push("");
1842
- lines.push(`${fnName}() {`);
1843
- lines.push(" local cur path i w children");
1844
- lines.push(' cur="${COMP_WORDS[COMP_CWORD]}"');
1845
- lines.push("");
1846
- lines.push(` path="${bin}"`);
1847
- lines.push(" for ((i=1; i<COMP_CWORD; i++)); do");
1848
- lines.push(' w="${COMP_WORDS[i]}"');
1849
- lines.push(' [[ "$w" == -* ]] && continue');
1850
- lines.push(` children=" $(${fnName}_subs "$path") "`);
1851
- lines.push(' case "$children" in *" $w "*) path="$path $w" ;; esac');
1852
- lines.push(" done");
1853
- lines.push("");
1854
- lines.push(' if [[ "$cur" == -* ]]; then');
1855
- lines.push(` COMPREPLY=($(compgen -W "$(${fnName}_opts "$path")" -- "$cur"))`);
1856
- lines.push(" else");
1857
- lines.push(` COMPREPLY=($(compgen -W "$(${fnName}_subs "$path")" -- "$cur"))`);
1858
- lines.push(" fi");
1859
- lines.push("}");
1860
- lines.push("");
1861
- lines.push(`complete -F ${fnName} ${bin}`);
1862
- lines.push("");
1863
- return lines.join(`
1864
- `);
1865
- }
1866
-
1867
- // src/commands/completion/fish.ts
1868
- function generateFish(root) {
1869
- const bin = root.name;
1870
- const helperFn = `__${bin.replace(/-/g, "_")}_path_matches`;
1871
- const lines = [];
1872
- lines.push(`# Generated by: ${bin} completion fish`);
1873
- lines.push(`# Add to config: ${bin} completion fish | source`);
1874
- lines.push("# Use --opt=value (not --opt value) after subcommands — static completion can't know flag arity.");
1875
- lines.push("");
1876
- lines.push(`function ${helperFn}`);
1877
- lines.push(" set -l tokens (commandline -opc)");
1878
- lines.push(" set -l subs");
1879
- lines.push(" for i in (seq 2 (count $tokens))");
1880
- lines.push(" set -l tok $tokens[$i]");
1881
- lines.push(" string match -q -- '-*' $tok; and continue");
1882
- lines.push(" set -a subs $tok");
1883
- lines.push(" end");
1884
- lines.push(" test (count $subs) -eq (count $argv)");
1885
- lines.push(" or return 1");
1886
- lines.push(" for i in (seq (count $argv))");
1887
- lines.push(' test "$argv[$i]" = "$subs[$i]"');
1888
- lines.push(" or return 1");
1889
- lines.push(" end");
1890
- lines.push(" return 0");
1891
- lines.push("end");
1892
- lines.push("");
1893
- function emit(node, path) {
1894
- for (const segment of path) {
1895
- if (/[|()[\]{}"'$`\\]/.test(segment)) {
1896
- throw new Error(`Fish generator: command path segment "${segment}" contains shell-special characters; rename the command or extend the fish emitter to escape it.`);
1897
- }
1898
- }
1899
- const condition = path.length === 0 ? helperFn : `${helperFn} ${path.join(" ")}`;
1900
- for (const sub of node.subcommands) {
1901
- let line = `complete -c ${bin} -n "${condition}" -a '${posixSq(sub.name)}'`;
1902
- if (sub.description) {
1903
- line += ` -d '${posixSq(sub.description)}'`;
1904
- }
1905
- lines.push(line);
1906
- }
1907
- for (const opt of node.options) {
1908
- let line = `complete -c ${bin} -n "${condition}"`;
1909
- if (opt.long)
1910
- line += ` -l '${posixSq(opt.long)}'`;
1911
- if (opt.short)
1912
- line += ` -s '${posixSq(opt.short)}'`;
1913
- if (opt.flags.includes("<") || opt.flags.includes("[")) {
1914
- line += " -r";
1915
- }
1916
- if (opt.description) {
1917
- line += ` -d '${posixSq(opt.description)}'`;
1918
- }
1919
- lines.push(line);
1920
- }
1921
- for (const sub of node.subcommands) {
1922
- emit(sub, [...path, sub.name]);
1923
- }
1924
- }
1925
- emit(root, []);
1926
- lines.push("");
1927
- return lines.join(`
1928
- `);
1929
- }
1930
-
1931
- // src/commands/completion/pwsh.ts
1932
- function generatePwsh(root) {
1933
- const bin = root.name;
1934
- const subs = {};
1935
- const opts = {};
1936
- function collect(node, path) {
1937
- if (node.subcommands.length > 0) {
1938
- subs[path] = node.subcommands.map((s) => s.name);
1939
- }
1940
- if (node.options.length > 0) {
1941
- opts[path] = node.options.map((o) => o.long ? `--${o.long}` : `-${o.short}`);
1942
- }
1943
- for (const sub of node.subcommands) {
1944
- collect(sub, `${path} ${sub.name}`);
1945
- }
1946
- }
1947
- collect(root, bin);
1948
- const q = (s) => `'${s.replace(/'/g, "''")}'`;
1949
- const lines = [];
1950
- lines.push(`# Generated by: ${bin} completion pwsh`);
1951
- lines.push(`# Install: ${bin} completion (writes a managed block in $PROFILE that dot-sources this file)`);
1952
- lines.push("");
1953
- lines.push(`Register-ArgumentCompleter -Native -CommandName ${bin} -ScriptBlock {`);
1954
- lines.push(" param($wordToComplete, $commandAst, $cursorPosition)");
1955
- lines.push("");
1956
- lines.push(" $subcommands = @{");
1957
- for (const [p, children] of Object.entries(subs)) {
1958
- lines.push(` ${q(p)} = @(${children.map(q).join(", ")})`);
1959
- }
1960
- lines.push(" }");
1961
- lines.push(" $options = @{");
1962
- for (const [p, flags] of Object.entries(opts)) {
1963
- lines.push(` ${q(p)} = @(${flags.map(q).join(", ")})`);
1964
- }
1965
- lines.push(" }");
1966
- lines.push("");
1967
- lines.push(" $elements = $commandAst.CommandElements");
1968
- lines.push(` $path = ${q(bin)}`);
1969
- lines.push(" for ($i = 1; $i -lt $elements.Count; $i++) {");
1970
- lines.push(" $tok = $elements[$i].Extent.Text");
1971
- lines.push(" if ($tok -eq $wordToComplete) { break }");
1972
- lines.push(" if ($tok -like '-*') { continue }");
1973
- lines.push(" $children = $subcommands[$path]");
1974
- lines.push(' if ($children -and ($children -contains $tok)) { $path = "$path $tok" }');
1975
- lines.push(" }");
1976
- lines.push("");
1977
- lines.push(" if ($wordToComplete -like '-*') {");
1978
- lines.push(" $candidates = $options[$path]");
1979
- lines.push(" } else {");
1980
- lines.push(" $candidates = $subcommands[$path]");
1981
- lines.push(" }");
1982
- lines.push(" if ($null -eq $candidates) { return }");
1983
- lines.push(' $candidates | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {');
1984
- lines.push(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)");
1985
- lines.push(" }");
1986
- lines.push("}");
1987
- lines.push("");
1988
- return lines.join(`
1989
- `);
1990
- }
1991
-
1992
- // src/commands/completion/zsh.ts
1993
- var longOptionForKey = (key) => `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1994
- function renderArgWithPlaceholders(template) {
1995
- const parts = template.split(/\{([a-zA-Z][a-zA-Z0-9]*)\}/);
1996
- const out = [];
1997
- for (let i = 0;i < parts.length; i++) {
1998
- if (i % 2 === 0) {
1999
- if (parts[i] !== "")
2000
- out.push(`'${posixSq(parts[i])}'`);
2001
- } else {
2002
- out.push(`"$_req_${parts[i]}"`);
2003
- }
2004
- }
2005
- return out.length > 0 ? out.join("") : "''";
2006
- }
2007
- function renderJqSelector(template) {
2008
- const requiredArgs = [];
2009
- const selector = template.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g, (_, name) => {
2010
- if (!requiredArgs.includes(name))
2011
- requiredArgs.push(name);
2012
- return `$${name}`;
2013
- });
2014
- return { selector, requiredArgs };
2015
- }
2016
- function generateZsh(root) {
2017
- const bin = root.name;
2018
- const fnPrefix = `_${bin.replace(/-/g, "_")}`;
2019
- const lines = [];
2020
- lines.push(`#compdef ${bin}`);
2021
- lines.push("");
2022
- lines.push(`# Generated by: ${bin} completion zsh`);
2023
- lines.push(`# Install: ${bin} completion (writes a managed block in ~/.zshrc that sources this file)`);
2024
- lines.push("");
2025
- lines.push(`${fnPrefix}_run_completer() {`);
2026
- lines.push(" local selector=$1; shift");
2027
- lines.push(" local -a jq_args");
2028
- lines.push(" while [[ ${1:-} == --arg ]]; do");
2029
- lines.push(' jq_args+=(--arg "$2" "$3")');
2030
- lines.push(" shift 3");
2031
- lines.push(" done");
2032
- lines.push(" (( ${+commands[jq]} )) || return 0");
2033
- lines.push(" local -a out");
2034
- lines.push(` out=(\${(f)"$("$@" 2>/dev/null | jq -r "\${jq_args[@]}" "$selector" 2>/dev/null)"})`);
2035
- lines.push(' (( ${#out} )) && compadd -- "${out[@]}"');
2036
- lines.push("}");
2037
- lines.push("");
2038
- function emitFunction(node, path) {
2039
- for (const segment of [...path, node.name]) {
2040
- if (/[|()[\]{}"'$`\\]/.test(segment)) {
2041
- throw new Error(`Zsh generator: command path segment "${segment}" contains shell-special characters; rename the command or extend the zsh emitter to escape it.`);
2042
- }
2043
- }
2044
- const fnName = path.length === 0 ? fnPrefix : `${fnPrefix}__${path.join("__").replace(/-/g, "_")}`;
2045
- lines.push(`${fnName}() {`);
2046
- if (path.length === 0) {
2047
- lines.push(` typeset -g ${fnPrefix}_bin=\${words[1]}`);
2048
- }
2049
- emitDynamicDispatch(node, lines, fnPrefix, bin);
2050
- emitSubcommandHandling(node, lines, fnPrefix, path);
2051
- emitOptionHandling(node, lines);
2052
- lines.push("}");
2053
- lines.push("");
2054
- for (const sub of node.subcommands) {
2055
- emitFunction(sub, [...path, sub.name]);
2056
- }
2057
- }
2058
- emitFunction(root, []);
2059
- lines.push(`compdef ${fnPrefix} ${bin}`);
2060
- lines.push("");
2061
- return lines.join(`
2062
- `);
2063
- }
2064
- function emitDynamicDispatch(node, lines, fnPrefix, bin) {
2065
- const completables = node.options.filter((o) => o.completer && o.long);
2066
- if (completables.length === 0)
2067
- return;
2068
- lines.push(" if (( CURRENT > 2 )); then");
2069
- lines.push(" local _prev=${words[CURRENT-1]}");
2070
- lines.push(" case $_prev in");
2071
- for (const opt of completables) {
2072
- const spec = opt.completer;
2073
- lines.push(` '--${posixSq(opt.long)}')`);
2074
- const { selector, requiredArgs } = renderJqSelector(spec.valueSelector);
2075
- const required = spec.requiresOptions ?? [];
2076
- const unguarded = requiredArgs.filter((n) => !required.includes(n));
2077
- if (unguarded.length > 0) {
2078
- throw new Error(`Zsh generator: valueSelector placeholder(s) {${unguarded.join("}, {")}} are not listed in requiresOptions — add them or the generated --arg will expand to an empty string.`);
2079
- }
2080
- for (const k of required) {
2081
- if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(k)) {
2082
- throw new Error(`Zsh generator: requiresOptions key "${k}" is not a valid camelCase identifier (used as a zsh variable name suffix).`);
2083
- }
2084
- lines.push(` local _req_${k}=""`);
2085
- lines.push(" local _i");
2086
- lines.push(" for ((_i=2; _i<CURRENT; _i++)); do");
2087
- lines.push(` [[ \${words[_i]} == ${longOptionForKey(k)} ]] && _req_${k}=\${words[_i+1]}`);
2088
- lines.push(" done");
2089
- lines.push(` [[ -z $_req_${k} ]] && return`);
2090
- }
2091
- const [cmdBin, ...cmdArgs] = spec.command;
2092
- const binToken = cmdBin === bin ? `"$${fnPrefix}_bin"` : `'${posixSq(cmdBin ?? bin)}'`;
2093
- const argsStr = cmdArgs.map(renderArgWithPlaceholders).join(" ");
2094
- const jqArgPairs = requiredArgs.map((name) => `--arg ${name} "$_req_${name}"`).join(" ");
2095
- const jqArgsPrefix = jqArgPairs ? `${jqArgPairs} ` : "";
2096
- lines.push(` ${fnPrefix}_run_completer '${posixSq(selector)}' ${jqArgsPrefix}${binToken} ${argsStr}`);
2097
- lines.push(" return");
2098
- lines.push(" ;;");
2099
- }
2100
- lines.push(" esac");
2101
- lines.push(" fi");
2102
- }
2103
- function emitSubcommandHandling(node, lines, fnPrefix, path) {
2104
- if (node.subcommands.length === 0)
2105
- return;
2106
- lines.push(" local i");
2107
- lines.push(" for ((i=2; i<CURRENT; i++)); do");
2108
- lines.push(" case $words[i] in");
2109
- for (const sub of node.subcommands) {
2110
- const subFn = `${fnPrefix}__${[...path, sub.name].join("__").replace(/-/g, "_")}`;
2111
- lines.push(` '${posixSq(sub.name)}') shift $((i-1)) words; ((CURRENT-=i-1)); ${subFn}; return ;;`);
2112
- }
2113
- lines.push(" esac");
2114
- lines.push(" done");
2115
- lines.push("");
2116
- lines.push(" local -a commands");
2117
- lines.push(" commands=(");
2118
- for (const sub of node.subcommands) {
2119
- lines.push(` '${posixSq(sub.name)}:${posixSq(sub.description)}'`);
2120
- }
2121
- lines.push(" )");
2122
- lines.push(" _describe -t commands 'command' commands");
2123
- }
2124
- function emitOptionHandling(node, lines) {
2125
- if (node.options.length === 0)
2126
- return;
2127
- lines.push(" local -a options");
2128
- lines.push(" options=(");
2129
- for (const opt of node.options) {
2130
- const desc = posixSq(opt.description);
2131
- if (opt.long)
2132
- lines.push(` '--${posixSq(opt.long)}:${desc}'`);
2133
- if (opt.short)
2134
- lines.push(` '-${posixSq(opt.short)}:${desc}'`);
2135
- }
2136
- lines.push(" )");
2137
- lines.push(" _describe -t options 'option' options");
2138
- }
2139
-
2140
- // src/commands/completion/install.ts
2141
- var blockStart = (bin) => `# >>> ${bin} completion >>>`;
2142
- var blockEnd = (bin) => `# <<< ${bin} completion <<<`;
2143
- var blockRe = (bin) => {
2144
- const escaped = bin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2145
- return new RegExp(`(?:\\r?\\n)*# >>> ${escaped} completion >>>[\\s\\S]*?# <<< ${escaped} completion <<<(?:\\r?\\n)*`, "g");
2146
- };
2147
- function normalizeShell(shell) {
2148
- switch (shell) {
2149
- case "bash":
2150
- case "zsh":
2151
- case "fish":
2152
- case "pwsh":
2153
- return shell;
2154
- case "powershell":
2155
- return "pwsh";
2156
- default:
2157
- return null;
2158
- }
2159
- }
2160
- function resolveUninstallTarget(shell, bin, fs) {
2161
- const home = fs.env.homedir();
2162
- const scriptDir = shell === "pwsh" && process.platform === "win32" ? fs.path.join(home, "Documents", "PowerShell", bin) : fs.path.join(home, ".config", bin);
2163
- switch (shell) {
2164
- case "zsh":
2165
- return {
2166
- bin,
2167
- shell,
2168
- rcPath: fs.path.join(home, ".zshrc"),
2169
- mode: "block",
2170
- scriptPath: fs.path.join(scriptDir, "completion.zsh")
2171
- };
2172
- case "bash": {
2173
- const bashRc = fs.path.join(home, process.platform === "darwin" ? ".bash_profile" : ".bashrc");
2174
- return {
2175
- bin,
2176
- shell,
2177
- rcPath: bashRc,
2178
- mode: "block",
2179
- scriptPath: fs.path.join(scriptDir, "completion.bash")
2180
- };
2181
- }
2182
- case "fish":
2183
- return {
2184
- bin,
2185
- shell,
2186
- rcPath: fs.path.join(home, ".config", "fish", "completions", `${bin}.fish`),
2187
- mode: "file"
2188
- };
2189
- case "pwsh": {
2190
- const pwshRc = process.platform === "win32" ? fs.path.join(home, "Documents", "PowerShell", "Microsoft.PowerShell_profile.ps1") : fs.path.join(home, ".config", "powershell", "Microsoft.PowerShell_profile.ps1");
2191
- return {
2192
- bin,
2193
- shell,
2194
- rcPath: pwshRc,
2195
- mode: "block",
2196
- scriptPath: fs.path.join(scriptDir, "completion.ps1")
2197
- };
2198
- }
2199
- }
2200
- }
2201
- function resolveTarget(shell, root, fs) {
2202
- const bin = root.name;
2203
- const paths = resolveUninstallTarget(shell, bin, fs);
2204
- const managedBlock = (line) => `${blockStart(bin)}
2205
- ${line}
2206
- ${blockEnd(bin)}`;
2207
- const requireScriptPath = () => {
2208
- if (!paths.scriptPath) {
2209
- throw new Error(`resolveUninstallTarget(${shell}) returned no scriptPath for block-mode install`);
2210
- }
2211
- return paths.scriptPath;
2212
- };
2213
- switch (shell) {
2214
- case "zsh": {
2215
- const scriptPath = requireScriptPath();
2216
- return {
2217
- ...paths,
2218
- content: managedBlock(`source '${posixSq(scriptPath)}'`),
2219
- scriptContent: generateZsh(root)
2220
- };
2221
- }
2222
- case "bash": {
2223
- const scriptPath = requireScriptPath();
2224
- return {
2225
- ...paths,
2226
- content: managedBlock(`source '${posixSq(scriptPath)}'`),
2227
- scriptContent: generateBash(root)
2228
- };
2229
- }
2230
- case "fish":
2231
- return {
2232
- ...paths,
2233
- content: generateFish(root)
2234
- };
2235
- case "pwsh": {
2236
- const scriptPath = requireScriptPath();
2237
- return {
2238
- ...paths,
2239
- content: managedBlock(`. '${scriptPath.replace(/'/g, "''")}'`),
2240
- scriptContent: generatePwsh(root)
2241
- };
2242
- }
2243
- }
2244
- }
2245
- function stripManagedBlock(content, bin) {
2246
- return content.replace(blockRe(bin), `
2247
- `);
2248
- }
2249
- async function writeScriptFile(target, fs) {
2250
- if (!target.scriptPath || target.scriptContent === undefined) {
2251
- return "skipped";
2252
- }
2253
- await fs.mkdir(fs.path.dirname(target.scriptPath));
2254
- const [existsErr, existsValue] = await catchError(fs.exists(target.scriptPath));
2255
- if (existsErr)
2256
- throw existsErr;
2257
- if (existsValue === true) {
2258
- const [readErr, prev] = await catchError(fs.readFile(target.scriptPath, "utf-8"));
2259
- if (readErr)
2260
- throw readErr;
2261
- if (prev === target.scriptContent)
2262
- return "skipped";
2263
- }
2264
- await fs.writeFile(target.scriptPath, target.scriptContent);
2265
- return "written";
2266
- }
2267
- async function doInstall(target, fs) {
2268
- const [existsErr, existsValue] = await catchError(fs.exists(target.rcPath));
2269
- if (existsErr)
2270
- throw existsErr;
2271
- const exists = existsValue === true;
2272
- await fs.mkdir(fs.path.dirname(target.rcPath));
2273
- if (target.mode === "file") {
2274
- let prev2 = null;
2275
- if (exists) {
2276
- const [readErr2, contents] = await catchError(fs.readFile(target.rcPath, "utf-8"));
2277
- if (readErr2)
2278
- throw readErr2;
2279
- prev2 = contents;
2280
- }
2281
- if (prev2 === target.content)
2282
- return "skipped";
2283
- await fs.writeFile(target.rcPath, target.content);
2284
- return exists ? "updated" : "installed";
2285
- }
2286
- const scriptWrite = await writeScriptFile(target, fs);
2287
- if (!exists) {
2288
- await fs.writeFile(target.rcPath, `${target.content}
2289
- `);
2290
- return "installed";
2291
- }
2292
- const [readErr, existing] = await catchError(fs.readFile(target.rcPath, "utf-8"));
2293
- if (readErr)
2294
- throw readErr;
2295
- const prev = existing ?? "";
2296
- const stripped = stripManagedBlock(prev, target.bin).replace(/\n+$/, "");
2297
- const sep = stripped ? `
2298
- ` : "";
2299
- const next = `${stripped}${sep}${target.content}
2300
- `;
2301
- const rcWritten = next !== prev;
2302
- if (rcWritten)
2303
- await fs.writeFile(target.rcPath, next);
2304
- if (!rcWritten && scriptWrite === "skipped")
2305
- return "skipped";
2306
- return prev.includes(blockStart(target.bin)) ? "updated" : "installed";
2307
- }
2308
- async function doUninstall(target, fs) {
2309
- const [existsErr, existsValue] = await catchError(fs.exists(target.rcPath));
2310
- if (existsErr)
2311
- throw existsErr;
2312
- if (target.mode === "file") {
2313
- if (!existsValue)
2314
- return "nothing";
2315
- await fs.rm(target.rcPath);
2316
- return "removed";
2317
- }
2318
- let removed = false;
2319
- if (existsValue) {
2320
- const [readErr, existing] = await catchError(fs.readFile(target.rcPath, "utf-8"));
2321
- if (readErr)
2322
- throw readErr;
2323
- const prev = existing ?? "";
2324
- if (prev.includes(blockStart(target.bin))) {
2325
- const next = stripManagedBlock(prev, target.bin).replace(/\n+$/, `
2326
- `);
2327
- await fs.writeFile(target.rcPath, next);
2328
- removed = true;
2329
- }
2330
- }
2331
- if (target.scriptPath) {
2332
- const [scriptExistsErr, scriptExists] = await catchError(fs.exists(target.scriptPath));
2333
- if (scriptExistsErr)
2334
- throw scriptExistsErr;
2335
- if (scriptExists) {
2336
- await fs.rm(target.scriptPath);
2337
- removed = true;
2338
- }
2339
- }
2340
- return removed ? "removed" : "nothing";
2341
- }
2342
-
2343
- // src/commands/completion.ts
2344
- async function handleUninstall(shell, program, context, fs) {
2345
- const target = resolveUninstallTarget(shell, program.name(), fs);
2346
- const [err, action] = await catchError(doUninstall(target, fs));
2347
- if (err) {
2348
- OutputFormatter.error({
2349
- Result: RESULTS.Failure,
2350
- Message: err.message,
2351
- Instructions: `Check write access to ${target.rcPath}.`
2352
- });
2353
- context.exit(1);
2354
- return;
1369
+ // src/commands/completion.ts
1370
+ async function handleUninstall(shell, program, context, fs) {
1371
+ const { doUninstall, resolveUninstallTarget } = await import("./install-3gw33jcf.js");
1372
+ const target = resolveUninstallTarget(shell, program.name(), fs);
1373
+ const [err, action] = await catchError(doUninstall(target, fs));
1374
+ if (err) {
1375
+ OutputFormatter.error({
1376
+ Result: RESULTS.Failure,
1377
+ Message: err.message,
1378
+ Instructions: `Check write access to ${target.rcPath}.`
1379
+ });
1380
+ context.exit(1);
1381
+ return;
2355
1382
  }
2356
1383
  OutputFormatter.success({
2357
1384
  Result: "Success",
@@ -2381,7 +1408,9 @@ function handlePrint(target) {
2381
1408
  });
2382
1409
  }
2383
1410
  async function handleInteractiveInstall(target, context, fs) {
2384
- const [promptErr, ok] = await catchError(dist_default({
1411
+ const { confirm } = await import("./index-1vyte4ma.js");
1412
+ const { doInstall } = await import("./install-3gw33jcf.js");
1413
+ const [promptErr, ok] = await catchError(confirm({
2385
1414
  message: `Install ${target.shell} completion to ${target.rcPath}?`,
2386
1415
  default: true
2387
1416
  }));
@@ -2429,6 +1458,8 @@ async function handleInteractiveInstall(target, context, fs) {
2429
1458
  }
2430
1459
  function registerCompletionCommand(program, discovered, context) {
2431
1460
  program.command("completion").description(`Install or output the shell completion script. Interactive in a TTY; with an explicit shell argument, dumps the script to stdout. Dynamic flag-value completion (e.g. --package-name <TAB>) is zsh-only and requires \`jq\` on PATH; static subcommand/option-name completion works on bash, zsh, fish, and pwsh.`).argument("[shell]", "Shell type: bash, zsh, fish, pwsh (alias: powershell). Auto-detected from $SHELL, $PSModulePath, and platform when omitted.").option("--print", "Print the target rc file path and the block that would be written, without touching the filesystem").option("--uninstall", "Remove the managed completion block (or fish completion file) instead of installing").trackedAction(context, async (shellArg, opts) => {
1461
+ const { normalizeShell, resolveTarget } = await import("./install-3gw33jcf.js");
1462
+ const { buildFullTree, detectShell } = await import("./tree-j4w7p0pg.js");
2432
1463
  const rawShell = shellArg ?? detectShell();
2433
1464
  const shell = normalizeShell(rawShell);
2434
1465
  if (!shell) {
@@ -2440,7 +1471,7 @@ function registerCompletionCommand(program, discovered, context) {
2440
1471
  context.exit(1);
2441
1472
  return;
2442
1473
  }
2443
- const fs = await getFileSystemAsync();
1474
+ const fs = await getFileSystemAsync2();
2444
1475
  if (opts.uninstall) {
2445
1476
  return handleUninstall(shell, program, context, fs);
2446
1477
  }
@@ -2629,7 +1660,7 @@ async function resolveForWrite(explicit) {
2629
1660
  if (r.absolutePath) {
2630
1661
  return { path: r.absolutePath };
2631
1662
  }
2632
- const fs = getFileSystem();
1663
+ const fs = getFileSystem2();
2633
1664
  return {
2634
1665
  path: fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR, CONFIG_FILENAME)
2635
1666
  };
@@ -2904,214 +1935,6 @@ function registerConfigCommand(program, context) {
2904
1935
  }, clearTelemetryProperties);
2905
1936
  }
2906
1937
 
2907
- // src/services/promptSelect.ts
2908
- var promptSelect = async (options, message) => {
2909
- try {
2910
- return await dist_default3({
2911
- message,
2912
- choices: options.map((name, value) => ({ name, value }))
2913
- });
2914
- } catch (error) {
2915
- if (error instanceof Error && error.name === "ExitPromptError") {
2916
- const cancellation = Object.assign(new Error("Selection cancelled by user"), {
2917
- exitCode: 130,
2918
- terminalSignal: "SIGINT"
2919
- });
2920
- cancellation.name = "ExitPromptError";
2921
- throw cancellation;
2922
- }
2923
- throw error;
2924
- }
2925
- };
2926
-
2927
- // src/services/auth.ts
2928
- class NodeAuth {
2929
- async interactiveLogin(options) {
2930
- const { interactiveLogin } = await import("./index-7tshyfxx.js");
2931
- return await interactiveLogin({
2932
- ...options,
2933
- selectFromList: promptSelect
2934
- });
2935
- }
2936
- async clientCredentialsLogin(options) {
2937
- const { clientCredentialsLogin } = await import("./index-7tshyfxx.js");
2938
- return await clientCredentialsLogin(options);
2939
- }
2940
- async getLoginStatus(options) {
2941
- const { getLoginStatusAsync: getLoginStatusAsync2 } = await import("./index-7tshyfxx.js");
2942
- return getLoginStatusAsync2(options);
2943
- }
2944
- async fetchTenants(baseUrl, accessToken, organizationId) {
2945
- const { fetchTenantsAndOrganizations } = await import("./index-7tshyfxx.js");
2946
- return fetchTenantsAndOrganizations(baseUrl, accessToken, organizationId);
2947
- }
2948
- async saveTenantSelection(envFilePath, tenantName, tenantId) {
2949
- const { saveEnvFileAsync } = await import("./index-7tshyfxx.js");
2950
- await saveEnvFileAsync({
2951
- envPath: envFilePath,
2952
- data: {
2953
- UIPATH_TENANT_NAME: tenantName,
2954
- UIPATH_TENANT_ID: tenantId
2955
- },
2956
- merge: true
2957
- });
2958
- }
2959
- }
2960
-
2961
- class BrowserAuth {
2962
- async interactiveLogin(options) {
2963
- const { interactiveLogin } = await import("./index-7tshyfxx.js");
2964
- return await interactiveLogin(options);
2965
- }
2966
- async clientCredentialsLogin(options) {
2967
- const { clientCredentialsLogin } = await import("./index-7tshyfxx.js");
2968
- return await clientCredentialsLogin(options);
2969
- }
2970
- async getLoginStatus(options) {
2971
- const { getLoginStatusAsync: getLoginStatusAsync2 } = await import("./index-7tshyfxx.js");
2972
- return getLoginStatusAsync2(options);
2973
- }
2974
- async fetchTenants(baseUrl, accessToken, organizationId) {
2975
- const { fetchTenantsAndOrganizations } = await import("./index-7tshyfxx.js");
2976
- return fetchTenantsAndOrganizations(baseUrl, accessToken, organizationId);
2977
- }
2978
- async saveTenantSelection(envFilePath, tenantName, tenantId) {
2979
- const { saveEnvFileAsync } = await import("./index-7tshyfxx.js");
2980
- await saveEnvFileAsync({
2981
- envPath: envFilePath,
2982
- data: {
2983
- UIPATH_TENANT_NAME: tenantName,
2984
- UIPATH_TENANT_ID: tenantId
2985
- },
2986
- merge: true
2987
- });
2988
- }
2989
- }
2990
- var auth = isBrowser() ? new BrowserAuth : new NodeAuth;
2991
-
2992
- // src/services/authTelemetry.ts
2993
- var AuthTelemetryEvents = {
2994
- Login: "Authenticate.LogIn",
2995
- TenantSelected: "Authenticate.TenantSelected",
2996
- TokenRefresh: "Authenticate.TokenRefresh",
2997
- Logout: "Authenticate.LogOut"
2998
- };
2999
- var UIPATH_EMAIL_DOMAIN = "uipath.com";
3000
- var decodeTokenClaims = (accessToken) => {
3001
- try {
3002
- const parts = accessToken.split(".");
3003
- if (parts.length !== 3) {
3004
- return;
3005
- }
3006
- const payload = parts[1];
3007
- const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
3008
- const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
3009
- const decoded = atob(padded);
3010
- return JSON.parse(decoded);
3011
- } catch {
3012
- return;
3013
- }
3014
- };
3015
- var isInternalUserEmail = (email) => {
3016
- const at = email.lastIndexOf("@");
3017
- if (at < 0) {
3018
- return false;
3019
- }
3020
- const domain = email.slice(at + 1).trim().toLowerCase();
3021
- return domain === UIPATH_EMAIL_DOMAIN || domain.endsWith(`.${UIPATH_EMAIL_DOMAIN}`);
3022
- };
3023
- var getInternalUserFlag = (claims) => {
3024
- const email = claims?.email ?? claims?.preferred_username;
3025
- if (typeof email !== "string" || !email.includes("@")) {
3026
- return;
3027
- }
3028
- return String(isInternalUserEmail(email));
3029
- };
3030
- var readAuthIdentity = async (deps) => {
3031
- const envAuthEnabled = deps.isEnvAuthEnabled ?? isEnvAuthEnabled;
3032
- const readEnv = deps.readAuthFromEnv ?? readAuthFromEnv;
3033
- const resolveEnvFilePath = deps.resolveEnvFilePath ?? resolveEnvFilePathAsync;
3034
- const loadEnvFile = deps.loadEnvFile ?? loadEnvFileAsync;
3035
- const getProfileFilePath = deps.getActiveProfileFilePath ?? getActiveAuthProfileFilePath;
3036
- if (envAuthEnabled()) {
3037
- const [error, status] = catchError(() => readEnv());
3038
- if (error || !status)
3039
- return;
3040
- return {
3041
- accessToken: status.accessToken,
3042
- tenantId: status.tenantId,
3043
- organizationId: status.organizationId,
3044
- baseUrl: status.baseUrl
3045
- };
3046
- }
3047
- const [resolveError, resolved] = await catchError(resolveEnvFilePath(getProfileFilePath() ?? DEFAULT_ENV_FILENAME));
3048
- if (resolveError || !resolved?.absolutePath)
3049
- return;
3050
- const [loadError, credentials] = await catchError(loadEnvFile({ envPath: resolved.absolutePath }));
3051
- if (loadError || !credentials)
3052
- return;
3053
- return {
3054
- accessToken: credentials.UIPATH_ACCESS_TOKEN,
3055
- authFlow: parseAuthFlow(credentials[AUTH_FLOW_ENV_VAR]),
3056
- tenantId: credentials.UIPATH_TENANT_ID,
3057
- organizationId: credentials.UIPATH_ORGANIZATION_ID,
3058
- baseUrl: credentials.UIPATH_URL
3059
- };
3060
- };
3061
- var populateTelemetryAuthContext = async (deps = {}) => {
3062
- const identity = await readAuthIdentity(deps);
3063
- if (!identity) {
3064
- setExecutionContextAuthSignal(undefined);
3065
- return;
3066
- }
3067
- setExecutionContextAuthSignal(identity.authFlow === "client_credentials" || identity.authFlow === "federated_credentials" ? "service_account" : undefined);
3068
- const claims = identity.accessToken ? decodeTokenClaims(identity.accessToken) : undefined;
3069
- const userId = claims?.sub;
3070
- const isInternalUser = getInternalUserFlag(claims);
3071
- const envProps = identity.baseUrl ? buildEnvironmentProperties(identity.baseUrl) : {};
3072
- const defaultProps = {
3073
- ...userId ? { [BaseDimensions.CloudUserId]: userId } : {},
3074
- ...identity.tenantId ? { [BaseDimensions.CloudTenantId]: identity.tenantId } : {},
3075
- ...identity.organizationId ? { [BaseDimensions.CloudOrganizationId]: identity.organizationId } : {},
3076
- ...envProps,
3077
- ...isInternalUser !== undefined ? { [BaseDimensions.IsInternalUser]: isInternalUser } : {}
3078
- };
3079
- if (Object.keys(defaultProps).length === 0)
3080
- return;
3081
- setGlobalTelemetryProperties(defaultProps);
3082
- telemetry.setDefaultProperties(defaultProps);
3083
- logger.debug("[Telemetry] auth context populated at startup");
3084
- };
3085
- var trackAuthLogin = (flow, result) => {
3086
- telemetry.trackEvent(AuthTelemetryEvents.Login, {
3087
- [AuthDimensions.AuthenticationMethod]: flow,
3088
- [AuthDimensions.Success]: String(result.success),
3089
- ...!result.success ? { [CommandDimensions.ErrorMessage]: result.errorMessage } : {}
3090
- });
3091
- };
3092
- var trackTenantSelection = (result) => {
3093
- telemetry.trackEvent(AuthTelemetryEvents.TenantSelected, {
3094
- [AuthDimensions.Success]: String(result.success),
3095
- ...!result.success && result.errorMessage ? { [CommandDimensions.ErrorMessage]: result.errorMessage } : {}
3096
- });
3097
- };
3098
- var trackTokenRefresh = (status) => {
3099
- if (!status.tokenRefresh?.attempted)
3100
- return;
3101
- telemetry.trackEvent(AuthTelemetryEvents.TokenRefresh, {
3102
- [AuthDimensions.Success]: String(status.tokenRefresh.success),
3103
- ...status.tokenRefresh.errorMessage ? {
3104
- [CommandDimensions.ErrorMessage]: status.tokenRefresh.errorMessage
3105
- } : {}
3106
- });
3107
- };
3108
- var trackAuthLogout = (result) => {
3109
- telemetry.trackEvent(AuthTelemetryEvents.Logout, {
3110
- [AuthDimensions.Success]: String(result.success),
3111
- ...!result.success && result.reason ? { [AuthDimensions.Reason]: result.reason } : {}
3112
- });
3113
- };
3114
-
3115
1938
  // src/commands/profiles/delete.ts
3116
1939
  var PROFILES_DELETE_EXAMPLES = [
3117
1940
  {
@@ -3173,20 +1996,20 @@ function registerDeleteCommand(profilesCommand, context) {
3173
1996
  });
3174
1997
  }
3175
1998
  async function rejectUndeletableProfile(profileArg, context) {
3176
- if (profileArg === DEFAULT_AUTH_PROFILE) {
3177
- rejectAsInvalid(context, `'${DEFAULT_AUTH_PROFILE}' is the built-in profile and cannot be deleted.`, "Run 'uip logout' to remove the credentials of the default profile.");
1999
+ if (profileArg === DEFAULT_AUTH_PROFILE2) {
2000
+ rejectAsInvalid(context, `'${DEFAULT_AUTH_PROFILE2}' is the built-in profile and cannot be deleted.`, "Run 'uip logout' to remove the credentials of the default profile.");
3178
2001
  return true;
3179
2002
  }
3180
- if (getActiveAuthProfile() === profileArg) {
2003
+ if (getActiveAuthProfile2() === profileArg) {
3181
2004
  rejectAsInvalid(context, `Cannot delete profile '${profileArg}' while '--profile ${profileArg}' selects it.`, `Re-run without '--profile ${profileArg}'.`);
3182
2005
  return true;
3183
2006
  }
3184
- const [nameError] = catchError(() => normalizeAuthProfileName(profileArg));
2007
+ const [nameError] = catchError(() => normalizeAuthProfileName2(profileArg));
3185
2008
  if (nameError) {
3186
2009
  rejectAsInvalid(context, nameError.message, "Use a profile name of letters, numbers, '.', '_' and '-'.");
3187
2010
  return true;
3188
2011
  }
3189
- const [existsError, exists] = await catchError(authProfileExistsAsync(profileArg));
2012
+ const [existsError, exists] = await catchError(authProfileExistsAsync2(profileArg));
3190
2013
  if (existsError) {
3191
2014
  rejectAsInvalid(context, existsError.message, LIST_INSTRUCTION);
3192
2015
  return true;
@@ -3204,7 +2027,7 @@ async function deleteSingle(profileArg, options, context) {
3204
2027
  if (!requireConfirmation(options, `delete profile '${profileArg}' and its stored credentials`)) {
3205
2028
  return;
3206
2029
  }
3207
- const [deleteError, removedPath] = await catchError(deleteAuthProfileAsync(profileArg));
2030
+ const [deleteError, removedPath] = await catchError(deleteAuthProfileAsync2(profileArg));
3208
2031
  if (deleteError) {
3209
2032
  OutputFormatter.error({
3210
2033
  Result: RESULTS.Failure,
@@ -3251,7 +2074,7 @@ function reportNothingToDelete(activeProfile, skippedActive, context) {
3251
2074
  async function deleteEach(targets) {
3252
2075
  const results = [];
3253
2076
  for (const name of targets) {
3254
- const [deleteError, removedPath] = await catchError(deleteAuthProfileAsync(name));
2077
+ const [deleteError, removedPath] = await catchError(deleteAuthProfileAsync2(name));
3255
2078
  if (deleteError) {
3256
2079
  results.push({
3257
2080
  Name: name,
@@ -3269,12 +2092,12 @@ async function deleteEach(targets) {
3269
2092
  return results;
3270
2093
  }
3271
2094
  async function deleteAll(options, context) {
3272
- const [listError, names] = await catchError(listAuthProfileNamesAsync());
2095
+ const [listError, names] = await catchError(listAuthProfileNamesAsync2());
3273
2096
  if (listError) {
3274
2097
  reportUnreadableProfiles(listError, context);
3275
2098
  return;
3276
2099
  }
3277
- const activeProfile = getActiveAuthProfile();
2100
+ const activeProfile = getActiveAuthProfile2();
3278
2101
  const named = names ?? [];
3279
2102
  const targets = named.filter((name) => name !== activeProfile);
3280
2103
  const skippedActive = activeProfile !== undefined && named.includes(activeProfile);
@@ -3365,7 +2188,7 @@ function toRow(profile, allFields) {
3365
2188
  }
3366
2189
  function registerListCommand(profilesCommand, context) {
3367
2190
  profilesCommand.command("list").description("List login profiles").option("--all-fields", "Include the authority URL, token expiry, and credentials file path").examples(PROFILES_LIST_EXAMPLES).trackedAction(context, async (options) => {
3368
- const [error, profiles] = await catchError(describeAuthProfilesAsync());
2191
+ const [error, profiles] = await catchError(describeAuthProfilesAsync2());
3369
2192
  if (error) {
3370
2193
  OutputFormatter.error({
3371
2194
  Result: RESULTS.Failure,
@@ -3395,251 +2218,6 @@ function registerProfilesCommand(loginCommand, context) {
3395
2218
  }
3396
2219
 
3397
2220
  // src/commands/login.ts
3398
- function resolveCallbackTimeoutOverrideMs() {
3399
- const raw = process.env.UIPATH_CLI_AUTH_CALLBACK_TIMEOUT_MS?.trim();
3400
- if (!raw || !/^\d+$/.test(raw)) {
3401
- return;
3402
- }
3403
- const ms = Number.parseInt(raw, 10);
3404
- if (ms < 1000 || ms > DEFAULT_AUTH_TIMEOUT_MS) {
3405
- return;
3406
- }
3407
- return ms;
3408
- }
3409
- function resolveAuthFilePath(folder) {
3410
- const profilePath = getActiveAuthProfileFilePath();
3411
- if (profilePath && !folder) {
3412
- return profilePath;
3413
- }
3414
- if (folder) {
3415
- return getFileSystem().path.join(folder, DEFAULT_AUTH_FILENAME);
3416
- }
3417
- return DEFAULT_ENV_FILENAME;
3418
- }
3419
- function rejectProfileFileConflict(context, folder) {
3420
- const profile = getActiveAuthProfile();
3421
- if (!profile || folder === undefined) {
3422
- return false;
3423
- }
3424
- OutputFormatter.error({
3425
- Result: RESULTS.ValidationError,
3426
- Message: "error: option '--profile' cannot be used with option '--file'",
3427
- Instructions: "Use --profile <name> for a named login profile, or --file <folder> for an explicit credentials folder."
3428
- });
3429
- context.exit(EXIT_CODES.ValidationError);
3430
- return true;
3431
- }
3432
- var ENV_AUTH_FALLBACK_HINT = "Headless? Set UIPATH_CLI_ENABLE_ENV_AUTH=true with UIPATH_CLI_AUTH_TOKEN, UIPATH_CLI_ORGANIZATION_NAME, UIPATH_CLI_ORGANIZATION_ID, UIPATH_CLI_TENANT_NAME, and UIPATH_CLI_TENANT_ID to skip the browser flow.";
3433
- function instructionsForLoginError(error, message, noBrowser) {
3434
- if (/[\r\n]/.test(message)) {
3435
- return `See message above for details. ${ENV_AUTH_FALLBACK_HINT}`;
3436
- }
3437
- const code = error instanceof Object && "code" in error ? error.code : undefined;
3438
- if (code === "EPERM" || code === "EACCES") {
3439
- return `The callback listener on port 8104 was blocked by the OS or sandbox (${String(code)}). Grant local-network permission or run outside the sandbox, then try again. ${ENV_AUTH_FALLBACK_HINT}`;
3440
- }
3441
- if (code === "EADDRINUSE") {
3442
- return `Port 8104 is already in use by another application (a stale 'uip login' would have been released automatically). Close the application holding the port, then try again. ${ENV_AUTH_FALLBACK_HINT}`;
3443
- }
3444
- if (code === "EADDRNOTAVAIL") {
3445
- return `The callback listener could not bind to the loopback address. Check that 127.0.0.1 resolves locally, then try again. ${ENV_AUTH_FALLBACK_HINT}`;
3446
- }
3447
- if (code === AUTH_RECLAIMED_ERROR_CODE) {
3448
- return "Only one 'uip login' can wait for a sign-in at a time, and a newer one took over the callback port. If that wasn't you, run 'uip login' again to take it back.";
3449
- }
3450
- if (code === AUTH_TIMEOUT_ERROR_CODE) {
3451
- return noBrowser ? `No sign-in callback was received within the timeout. The printed URL may not have been opened, may have been copied incompletely (a line-wrapped or truncated copy is rejected by the identity server), or the sign-in was not completed. Retry and open the URL exactly as printed. ${ENV_AUTH_FALLBACK_HINT}` : `The browser did not return an authorization code within the timeout. Make sure your default browser opened, complete the sign-in, then retry. ${ENV_AUTH_FALLBACK_HINT}`;
3452
- }
3453
- const connectivity = describeConnectivityError(error);
3454
- if (connectivity) {
3455
- return connectivity.instructions;
3456
- }
3457
- return `Inspect command arguments and message and try again. ${ENV_AUTH_FALLBACK_HINT}`;
3458
- }
3459
- function loginErrorMessage(error) {
3460
- logger.debug(`login command error:
3461
- ${formatErrorChain(error)}`);
3462
- const base = error instanceof Error ? error.message : String(error);
3463
- const connectivity = describeConnectivityError(error);
3464
- if (connectivity && connectivity.message !== base) {
3465
- return `${base}: ${connectivity.message}`;
3466
- }
3467
- return base;
3468
- }
3469
- function instructionsForStatusError(err) {
3470
- if (err instanceof EnvAuthConfigError || isEnvAuthEnabled()) {
3471
- return "Check the UIPATH_CLI_* environment variables and re-run.";
3472
- }
3473
- const connectivity = describeConnectivityError(err);
3474
- if (connectivity) {
3475
- return connectivity.instructions;
3476
- }
3477
- return "Failed to read login status. Check your credentials file.";
3478
- }
3479
- function credentialSourceLabel(source) {
3480
- switch (source) {
3481
- case "robot" /* Robot */:
3482
- return "Robot";
3483
- case "env-vars" /* EnvironmentVariables */:
3484
- return "EnvironmentVariables";
3485
- case "saved-login" /* SavedLogin */:
3486
- return "SavedLogin";
3487
- default:
3488
- return "N/A";
3489
- }
3490
- }
3491
- function legacyProviderLabel(source) {
3492
- switch (source) {
3493
- case "robot" /* Robot */:
3494
- return "Robot";
3495
- case "env-vars" /* EnvironmentVariables */:
3496
- return "Environment";
3497
- case "saved-login" /* SavedLogin */:
3498
- return "File";
3499
- default:
3500
- return "N/A";
3501
- }
3502
- }
3503
- function authFlowLabel(flow) {
3504
- switch (flow) {
3505
- case "authorization_code":
3506
- return "Interactive";
3507
- case "client_credentials":
3508
- return "ClientCredentials";
3509
- case "federated_credentials":
3510
- return "FederatedCredentials";
3511
- }
3512
- }
3513
- function identityLabel(identity) {
3514
- if (identity.type === "User") {
3515
- return identity.userEmail ?? identity.userName ?? identity.userId;
3516
- }
3517
- return identity.clientId ? `External application ${identity.clientId}` : "External application";
3518
- }
3519
- function buildIdentityHeadline(identity) {
3520
- if (!identity)
3521
- return {};
3522
- const label = identityLabel(identity);
3523
- return {
3524
- ...label ? { Identity: label } : {},
3525
- IdentityType: identity.type,
3526
- ...identity.authFlow ? { AuthFlow: authFlowLabel(identity.authFlow) } : {}
3527
- };
3528
- }
3529
- function buildIdentityDetail(identity) {
3530
- if (!identity)
3531
- return {};
3532
- return {
3533
- ...identity.userId ? { UserId: identity.userId } : {},
3534
- ...identity.userEmail ? { UserEmail: identity.userEmail } : {},
3535
- ...identity.userName ? { UserName: identity.userName } : {},
3536
- ...identity.clientId ? { ClientId: identity.clientId } : {}
3537
- };
3538
- }
3539
- function buildScopeDetail(scopes, detailed) {
3540
- return detailed && scopes ? { Scopes: scopes } : {};
3541
- }
3542
- function buildRefreshData(status) {
3543
- const data = {
3544
- Status: status.loginStatus,
3545
- Organization: status.organizationName || status.organizationId || "N/A",
3546
- Tenant: status.tenantName || status.tenantId || "N/A",
3547
- "Expiration Date": status.expiration
3548
- };
3549
- if (status.hint)
3550
- data.Hint = status.hint;
3551
- if (status.baseUrl)
3552
- data.BaseUrl = status.baseUrl;
3553
- if (status.organizationId)
3554
- data.OrganizationId = status.organizationId;
3555
- if (status.organizationName)
3556
- data.OrganizationName = status.organizationName;
3557
- if (status.tenantId)
3558
- data.TenantId = status.tenantId;
3559
- if (status.tenantName)
3560
- data.TenantName = status.tenantName;
3561
- const emitToken = getOutputFormat() === "json" && (getOutputFormatExplicit() || !getOutputSink().capabilities.isInteractive);
3562
- if (emitToken && status.accessToken) {
3563
- data.AccessToken = status.accessToken;
3564
- }
3565
- return data;
3566
- }
3567
- function buildLoginData(credentials) {
3568
- const {
3569
- UIPATH_ACCESS_TOKEN: _token,
3570
- UIPATH_REFRESH_TOKEN: _refresh,
3571
- [AUTH_FLOW_ENV_VAR]: _authFlow,
3572
- ...safeCredentials
3573
- } = credentials;
3574
- if (getOutputFormat() === "table") {
3575
- return {
3576
- UIPATH_URL: credentials.UIPATH_URL,
3577
- UIPATH_ORGANIZATION_NAME: credentials.UIPATH_ORGANIZATION_NAME,
3578
- UIPATH_TENANT_NAME: credentials.UIPATH_TENANT_NAME
3579
- };
3580
- }
3581
- return safeCredentials;
3582
- }
3583
- function loginRetryCommand(args = []) {
3584
- const profile = getActiveAuthProfile();
3585
- return [
3586
- "uip",
3587
- "login",
3588
- ...profile ? ["--profile", profile] : [],
3589
- ...args
3590
- ].join(" ");
3591
- }
3592
- function quotedLoginRetryCommand(args = []) {
3593
- return `'${loginRetryCommand(args)}'`;
3594
- }
3595
- function authenticateInstruction() {
3596
- return getActiveAuthProfile() ? `Run ${quotedLoginRetryCommand()} to authenticate this profile.` : "Run 'uip login' to authenticate.";
3597
- }
3598
- function authenticateFirstInstruction() {
3599
- return getActiveAuthProfile() ? `Run ${quotedLoginRetryCommand()} to authenticate this profile.` : "Run 'uip login' to authenticate first.";
3600
- }
3601
- function reauthenticateInstruction() {
3602
- return getActiveAuthProfile() ? `Run ${quotedLoginRetryCommand()} to re-authenticate this profile.` : "Run 'uip login' to re-authenticate.";
3603
- }
3604
- function tenantSelectionInstructions(authFlow) {
3605
- if (authFlow === "client_credentials" || authFlow === "federated_credentials") {
3606
- return `Run ${quotedLoginRetryCommand(["--tenant", "<name>"])} to select a tenant.`;
3607
- }
3608
- return `Run ${quotedLoginRetryCommand(["--tenant", "<name>"])} or run from an interactive terminal to select a tenant during login. Use ${quotedLoginRetryCommand(["--interactive"])} to force a prompt.`;
3609
- }
3610
- function noCredentialsInstruction() {
3611
- const profile = getActiveAuthProfile();
3612
- return profile ? `No credentials found for profile "${profile}". ${authenticateInstruction()}` : "No credentials found. Run 'uip login' to authenticate.";
3613
- }
3614
- function emitRefreshFailure(status) {
3615
- const refreshFailed = status.loginStatus === "Refresh Failed";
3616
- OutputFormatter.error({
3617
- Result: RESULTS.AuthenticationError,
3618
- Message: refreshFailed ? `Token refresh failed. ${reauthenticateInstruction()}` : `Not authenticated. ${authenticateInstruction()}`,
3619
- Instructions: status.hint ?? defaultRefreshFailureInstructions(status),
3620
- ...status.refreshTelemetrySuppressed ? { SuppressTelemetry: true } : {}
3621
- });
3622
- }
3623
- function isUserCancellationError(error) {
3624
- if (!(error instanceof Error)) {
3625
- return false;
3626
- }
3627
- const exitCode = error.exitCode;
3628
- const code = error.code;
3629
- return error.name === "ExitPromptError" || exitCode === 130 || code === AUTH_CANCELLED_ERROR_CODE || error.message === "Selection cancelled by user";
3630
- }
3631
- function defaultRefreshFailureInstructions(status) {
3632
- switch (status.loginStatus) {
3633
- case "Refresh Failed":
3634
- return "The stored refresh token is invalid or expired.";
3635
- case "Expired":
3636
- return "The access token has expired and no refresh token is available.";
3637
- case "Not logged in":
3638
- return noCredentialsInstruction();
3639
- default:
3640
- return authenticateInstruction();
3641
- }
3642
- }
3643
2221
  var LOGIN_EXAMPLES = [
3644
2222
  {
3645
2223
  Description: "Interactively log in and select a tenant",
@@ -3842,226 +2420,14 @@ var LOGIN_WHICH_EXAMPLES = [
3842
2420
  "UIPATH_CLI_TENANT_NAME",
3843
2421
  "UIPATH_CLI_TENANT_ID"
3844
2422
  ]
3845
- }
3846
- }
3847
- }
3848
- ];
3849
- function registerLoginCommand(program, context) {
3850
- const loginCommand = program.command("login").description("Login to UiPath Cloud").option("-f, --file <folder>", "Path to credentials folder").option("--authority <url>", "Custom authority URL, e.g. https://cloud.uipath.com (default), https://govcloud.uipath.us (Public Sector), or your Automation Suite host. https:// may be omitted (cloud.uipath.com works)").option("--client-id <id>", "External application ID. Requires --client-secret or --client-assertion. Use env.ENV_NAME to read from an environment variable").option("--client-secret <secret>", "External application secret. Requires --client-id. Use env.ENV_NAME to read from an environment variable").option("--client-assertion <jwt>", "OIDC token (JWT) for federated login (workload identity), used instead of a secret. Use env.ENV_NAME to read from an environment variable (recommended). Requires --client-id").option("-s, --scope <scopes>", "Custom scopes or Application scopes (External Apps). Comma- or space-separated values.").option("-t, --tenant <name>", "Tenant name (non-interactive mode)").option("--organization <name>", "Organization logical name to pre-select during browser login (bypasses the org picker for users in multiple organizations)").option("--no-browser", "Don't open a browser; print the authorize URL and wait for the callback (for headless/automation-driven login). Blocks until the sign-in completes — when a person will do the sign-in, they should run the command themselves in their own terminal, not through an agent's shell tool").examples(LOGIN_EXAMPLES).trackedAction(context, async (options) => {
3851
- if (rejectProfileFileConflict(context, options.file)) {
3852
- return;
3853
- }
3854
- const envFilePath = resolveAuthFilePath(options.file);
3855
- let clientId;
3856
- let clientSecret;
3857
- let explicitAssertion;
3858
- try {
3859
- clientId = resolveEnvReference(options.clientId);
3860
- clientSecret = resolveEnvReference(options.clientSecret);
3861
- explicitAssertion = resolveEnvReference(options.clientAssertion);
3862
- } catch (e) {
3863
- const message = e instanceof Error ? e.message : String(e);
3864
- OutputFormatter.error({
3865
- Result: RESULTS.ConfigError,
3866
- Message: message,
3867
- Instructions: "Inspect command arguments and try again."
3868
- });
3869
- context.exit(1);
3870
- return;
3871
- }
3872
- if (options.clientAssertion && !options.clientAssertion.startsWith("env.")) {
3873
- getOutputSink().writeErr(`WARNING: Passing --client-assertion as a literal value exposes the token in shell history, process listings, and CI logs. Prefer --client-assertion env.YOUR_TOKEN_VAR.
3874
- `);
3875
- }
3876
- const clientAssertion = explicitAssertion;
3877
- if (clientSecret && clientAssertion) {
3878
- OutputFormatter.error({
3879
- Result: RESULTS.ConfigError,
3880
- Message: "--client-secret cannot be combined with --client-assertion.",
3881
- Instructions: "Federated login replaces the client secret. Use either --client-secret (client credentials) or --client-assertion (workload identity), not both."
3882
- });
3883
- context.exit(1);
3884
- return;
3885
- }
3886
- if (clientAssertion && !clientId) {
3887
- OutputFormatter.error({
3888
- Result: RESULTS.ConfigError,
3889
- Message: "Federated login requires --client-id (the external application ID).",
3890
- Instructions: "Pass --client-id <app-id> along with --client-assertion."
3891
- });
3892
- context.exit(1);
3893
- return;
3894
- }
3895
- if (clientSecret && !clientId) {
3896
- OutputFormatter.error({
3897
- Result: RESULTS.ConfigError,
3898
- Message: "Client credentials login requires --client-id (the external application ID).",
3899
- Instructions: "Pass --client-id <app-id> along with --client-secret."
3900
- });
3901
- context.exit(1);
3902
- return;
3903
- }
3904
- if (clientId && !clientSecret && !clientAssertion) {
3905
- OutputFormatter.error({
3906
- Result: RESULTS.ConfigError,
3907
- Message: "--client-id requires --client-secret or --client-assertion.",
3908
- Instructions: "For an external application, pass --client-secret (client credentials) or --client-assertion (federated login) with --client-id. For browser login, drop --client-id."
3909
- });
3910
- context.exit(1);
3911
- return;
3912
- }
3913
- const authFlow = clientAssertion ? "federated_credentials" : clientSecret ? "client_credentials" : "authorization_code";
3914
- if (authFlow === "authorization_code" && canPrompt()) {
3915
- getOutputSink().writeErr(`${COPYRIGHT_NOTICE}
3916
- `);
3917
- }
3918
- const noBrowser = options.browser === false || process.env.UIPATH_CLI_NO_BROWSER === "true";
3919
- if (options.organization && (clientSecret || clientAssertion)) {
3920
- logger.warn(clientSecret ? "--organization is ignored when using client credentials; the organization is fixed by the client-id." : "--organization is ignored for federated login; the organization is fixed by the client-id.");
3921
- }
3922
- if (noBrowser && (clientSecret || clientAssertion)) {
3923
- logger.warn(clientSecret ? "--no-browser has no effect with client credentials; no browser is opened." : "--no-browser has no effect for federated login; no browser is opened.");
3924
- }
3925
- logger.info(clientAssertion ? "→ Authenticating with Federated Credentials (workload identity)..." : clientSecret ? "→ Authenticating with Client Credentials..." : noBrowser ? "→ Headless login: open the printed authorize URL to continue..." : "→ Opening browser for authentication. Sign in via the browser to continue...");
3926
- let tenantFetchError;
3927
- const handleAuthEvent = (event) => {
3928
- switch (event.type) {
3929
- case "info":
3930
- logger.info(event.message);
3931
- break;
3932
- case "warn":
3933
- logger.warn(event.message);
3934
- break;
3935
- case "tenant-fetch-failed":
3936
- tenantFetchError = event.message;
3937
- logger.error(`Could not establish an active tenant: ${event.message}`);
3938
- break;
3939
- case "saved":
3940
- logger.info(event.locality === "local" ? `Credentials saved locally to ${event.path}` : `Credentials saved to ${event.path}`);
3941
- break;
3942
- case "auth-url":
3943
- getOutputSink().writeErr(`UIPATH_AUTH_URL ${event.url}
3944
- `);
3945
- getOutputSink().writeErr(`
3946
- Open this URL in a browser to sign in:
3947
-
3948
- ${event.url}
3949
-
3950
- `);
3951
- getOutputSink().writeErr(`Open the URL exactly as printed — a line-wrapped or truncated copy is rejected by the identity server.
3952
-
3953
- `);
3954
- getOutputSink().writeErr(`Waiting for the sign-in to complete — this command blocks until the browser finishes (or the wait times out).
3955
- ` + `Agents/automation: if a person is doing the sign-in, have them run 'uip login' in their own terminal instead of running it on their behalf.
3956
-
3957
- `);
3958
- break;
3959
- case "port-reclaimed":
3960
- getOutputSink().writeErr(`${event.message}
3961
- `);
3962
- break;
3963
- }
3964
- };
3965
- const scopes = splitScopeList(options.scope);
3966
- const [error, authResult] = await catchError(auth.interactiveLogin({
3967
- envFilePath,
3968
- authority: options.authority,
3969
- clientId,
3970
- clientSecret,
3971
- clientAssertion,
3972
- scope: scopes.length > 0 ? scopes : undefined,
3973
- tenant: options.tenant,
3974
- organization: options.organization,
3975
- interactive: canPrompt(),
3976
- noBrowser,
3977
- timeoutMs: resolveCallbackTimeoutOverrideMs(),
3978
- signal: context.pollSignal,
3979
- onEvent: handleAuthEvent
3980
- }));
3981
- if (error) {
3982
- if (isUserCancellationError(error)) {
3983
- if (error.code === AUTH_CANCELLED_ERROR_CODE) {
3984
- throw Object.assign(error, { exitCode: 130 });
3985
- }
3986
- throw error;
3987
- }
3988
- if (isTenantSelectionError(error)) {
3989
- trackAuthLogin(authFlow, { success: true });
3990
- trackTenantSelection({
3991
- success: false,
3992
- errorMessage: error.message
3993
- });
3994
- const tenants = error.availableTenants;
3995
- const pickInstructions = tenantSelectionInstructions(authFlow);
3996
- OutputFormatter.error({
3997
- Result: RESULTS.ConfigError,
3998
- Message: error.message.split(`
3999
- `)[0],
4000
- Instructions: `${pickInstructions} Available tenants: ${tenants.join(", ")}.`,
4001
- Data: { AvailableTenants: tenants }
4002
- });
4003
- context.exit(1);
4004
- return;
4005
- }
4006
- const message = loginErrorMessage(error);
4007
- trackAuthLogin(authFlow, {
4008
- success: false,
4009
- errorMessage: message
4010
- });
4011
- if (tenantFetchError) {
4012
- trackTenantSelection({
4013
- success: false,
4014
- errorMessage: tenantFetchError
4015
- });
4016
- }
4017
- const httpStatus = error instanceof Object && "status" in error && typeof error.status === "number" ? error.status : undefined;
4018
- OutputFormatter.error({
4019
- Result: RESULTS.AuthenticationError,
4020
- Message: message,
4021
- Instructions: instructionsForLoginError(error, message, noBrowser),
4022
- ...httpStatus ? { Context: { httpStatus } } : {}
4023
- });
4024
- context.exit(2);
4025
- return;
4026
- }
4027
- if (!authResult?.UIPATH_TENANT_ID || !authResult.UIPATH_TENANT_NAME) {
4028
- const message = "No active tenant selected";
4029
- trackAuthLogin(authFlow, {
4030
- success: false,
4031
- errorMessage: message
4032
- });
4033
- trackTenantSelection({
4034
- success: false,
4035
- ...tenantFetchError ? { errorMessage: tenantFetchError } : {}
4036
- });
4037
- OutputFormatter.error({
4038
- Result: RESULTS.ConfigError,
4039
- Message: message,
4040
- Instructions: tenantSelectionInstructions(authFlow)
4041
- });
4042
- context.exit(1);
4043
- return;
4044
- }
4045
- trackAuthLogin(authFlow, { success: true });
4046
- if (authResult?.UIPATH_ORGANIZATION_ID) {
4047
- trackTenantSelection(authResult.UIPATH_TENANT_ID ? { success: true } : {
4048
- success: false,
4049
- ...tenantFetchError ? { errorMessage: tenantFetchError } : {}
4050
- });
4051
- }
4052
- logger.info("✓ Authenticated");
4053
- if (authResult?.UIPATH_ORGANIZATION_ID) {
4054
- logger.info(`✓ Organization ID: ${authResult.UIPATH_ORGANIZATION_ID}`);
4055
- }
4056
- if (authResult?.UIPATH_TENANT_NAME) {
4057
- const tenantReason = options.tenant ? " (from --tenant)" : canPrompt() ? "" : " (only tenant in this organization)";
4058
- logger.info(`✓ Tenant: ${authResult.UIPATH_TENANT_NAME}${tenantReason}`);
2423
+ }
4059
2424
  }
4060
- OutputFormatter.success({
4061
- Result: RESULTS.Success,
4062
- Code: "Authenticated",
4063
- Data: buildLoginData(authResult ?? {})
4064
- });
2425
+ }
2426
+ ];
2427
+ function registerLoginCommand(program, context) {
2428
+ const loginCommand = program.command("login").description("Login to UiPath Cloud").option("-f, --file <folder>", "Path to credentials folder").option("--authority <url>", "Custom authority URL, e.g. https://cloud.uipath.com (default), https://govcloud.uipath.us (Public Sector), or your Automation Suite host. https:// may be omitted (cloud.uipath.com works)").option("--client-id <id>", "External application ID. Requires --client-secret or --client-assertion. Use env.ENV_NAME to read from an environment variable").option("--client-secret <secret>", "External application secret. Requires --client-id. Use env.ENV_NAME to read from an environment variable").option("--client-assertion <jwt>", "OIDC token (JWT) for federated login (workload identity), used instead of a secret. Use env.ENV_NAME to read from an environment variable (recommended). Requires --client-id").option("-s, --scope <scopes>", "Custom scopes or Application scopes (External Apps). Comma- or space-separated values.").option("-t, --tenant <name>", "Tenant name (non-interactive mode)").option("--organization <name>", "Organization logical name to pre-select during browser login (bypasses the org picker for users in multiple organizations)").option("--no-browser", "Don't open a browser; print the authorize URL and wait for the callback (for headless/automation-driven login). Blocks until the sign-in completes — when a person will do the sign-in, they should run the command themselves in their own terminal, not through an agent's shell tool").examples(LOGIN_EXAMPLES).trackedAction(context, async (options) => {
2429
+ const { runLogin } = await import("./handlers-93z27zrr.js");
2430
+ await runLogin(context, options);
4065
2431
  }, (options) => ({
4066
2432
  HasClientCredentials: !!(options.clientId && options.clientSecret),
4067
2433
  HasTenant: !!options.tenant,
@@ -4069,291 +2435,31 @@ Open this URL in a browser to sign in:
4069
2435
  Interactive: canPrompt()
4070
2436
  }));
4071
2437
  loginCommand.command("status").description("Show current login status and session information").addOption(new Option("--detailed", "Also show the scopes the access token carries").hideHelp()).examples(LOGIN_STATUS_EXAMPLES).trackedAction(context, async (options) => {
4072
- const [statusError, status] = await catchError(auth.getLoginStatus());
4073
- if (statusError) {
4074
- OutputFormatter.error({
4075
- Result: RESULTS.ConfigError,
4076
- Message: loginErrorMessage(statusError),
4077
- Instructions: instructionsForStatusError(statusError)
4078
- });
4079
- context.exit(1);
4080
- return;
4081
- }
4082
- trackTokenRefresh(status);
4083
- const activeProfile = getActiveAuthProfile();
4084
- const statusData = {
4085
- Status: status.loginStatus,
4086
- ...buildIdentityHeadline(status.identity),
4087
- CredentialSource: credentialSourceLabel(status.source),
4088
- Provider: legacyProviderLabel(status.source),
4089
- ...buildIdentityDetail(status.identity),
4090
- ...buildScopeDetail(status.scopes, options.detailed === true),
4091
- ...activeProfile && status.source === "saved-login" /* SavedLogin */ ? { Profile: activeProfile } : {},
4092
- BaseUrl: status.baseUrl,
4093
- Organization: status.organizationName || status.organizationId || "N/A"
4094
- };
4095
- if (status.organizationId) {
4096
- statusData.OrganizationId = status.organizationId;
4097
- }
4098
- statusData.Tenant = status.tenantName || status.tenantId || "N/A";
4099
- if (status.tenantId) {
4100
- statusData.TenantId = status.tenantId;
4101
- }
4102
- statusData["Expiration Date"] = status.expiration;
4103
- if (status.hint) {
4104
- statusData.Hint = status.hint;
4105
- } else if (status.loginStatus !== "Logged in") {
4106
- statusData.Hint = defaultRefreshFailureInstructions(status);
4107
- }
4108
- OutputFormatter.success({
4109
- Result: RESULTS.Success,
4110
- Code: "LoginStatus",
4111
- Data: statusData
4112
- });
2438
+ const { runLoginStatus } = await import("./handlers-93z27zrr.js");
2439
+ await runLoginStatus(context, options);
4113
2440
  });
4114
2441
  loginCommand.command("refresh").description("Refresh the access token proactively and emit a machine-readable session payload " + "(access token, org/tenant identity, expiration). Programmatic consumers (e.g. the Flow " + "VSCode extension) call this to guarantee the returned token will still be valid " + "for the next N minutes. `login status`, by contrast, is a status report — it " + "only rotates tokens incidentally when the stored access token is already past " + "its expiry, and never performs proactive refresh.").option("--login-validity <minutes>", "Refresh only if the access token expires within this many minutes. " + "Default 5. Pass 0 to skip proactive refresh and only rotate if already expired.", (raw) => parseBoundedInt(raw, "--login-validity", {
4115
2442
  min: 0,
4116
2443
  max: 60 * 24 * 365
4117
2444
  }), 5).examples(LOGIN_REFRESH_EXAMPLES).trackedAction(context, async (options) => {
4118
- const [statusError, status] = await catchError(auth.getLoginStatus({
4119
- ensureTokenValidityMinutes: options.loginValidity
4120
- }));
4121
- if (statusError) {
4122
- OutputFormatter.error({
4123
- Result: RESULTS.AuthenticationError,
4124
- Message: `Could not read credentials: ${loginErrorMessage(statusError)}`,
4125
- Instructions: instructionsForStatusError(statusError)
4126
- });
4127
- context.exit(2);
4128
- return;
4129
- }
4130
- trackTokenRefresh(status);
4131
- if (status.loginStatus !== "Logged in") {
4132
- emitRefreshFailure(status);
4133
- context.exit(2);
4134
- return;
4135
- }
4136
- OutputFormatter.success({
4137
- Result: RESULTS.Success,
4138
- Code: status.persistenceFailed ? "LoginRefreshPartial" : "LoginRefresh",
4139
- Data: buildRefreshData(status)
4140
- });
2445
+ const { runLoginRefresh } = await import("./handlers-93z27zrr.js");
2446
+ await runLoginRefresh(context, options);
4141
2447
  }, (options) => ({
4142
2448
  LoginValidityMinutes: options.loginValidity
4143
2449
  }));
4144
2450
  registerProfilesCommand(loginCommand, context);
4145
2451
  const tenantCommand = loginCommand.command("tenant").description("Manage tenants");
4146
2452
  tenantCommand.command("list").description("List all available tenants").option("-f, --file <folder>", "Path to credentials folder").examples(LOGIN_TENANT_LIST_EXAMPLES).trackedAction(context, async (options) => {
4147
- if (rejectProfileFileConflict(context, options.file)) {
4148
- return;
4149
- }
4150
- const [statusError, status] = await catchError(auth.getLoginStatus({
4151
- envFilePath: resolveAuthFilePath(options.file)
4152
- }));
4153
- if (statusError) {
4154
- OutputFormatter.error({
4155
- Result: RESULTS.ConfigError,
4156
- Message: loginErrorMessage(statusError),
4157
- Instructions: instructionsForStatusError(statusError)
4158
- });
4159
- context.exit(1);
4160
- return;
4161
- }
4162
- trackTokenRefresh(status);
4163
- if (status.loginStatus !== "Logged in" || !status.accessToken || !status.baseUrl || !status.organizationId) {
4164
- OutputFormatter.error({
4165
- Result: RESULTS.AuthenticationError,
4166
- Message: "Not authenticated",
4167
- Instructions: status.hint || authenticateFirstInstruction()
4168
- });
4169
- context.exit(2);
4170
- return;
4171
- }
4172
- const [fetchError, data] = await catchError(auth.fetchTenants(status.baseUrl, status.accessToken, status.organizationName || status.organizationId));
4173
- if (fetchError) {
4174
- const connectivity = describeConnectivityError(fetchError);
4175
- OutputFormatter.error({
4176
- Result: RESULTS.Failure,
4177
- Message: loginErrorMessage(fetchError),
4178
- Instructions: connectivity?.instructions ?? "Failed to fetch tenants. Check your network connection and try again."
4179
- });
4180
- context.exit(1);
4181
- return;
4182
- }
4183
- const tenantRows = data.tenants.map((t) => ({
4184
- TenantName: t.name,
4185
- TenantId: t.id
4186
- }));
4187
- OutputFormatter.success({
4188
- Result: RESULTS.Success,
4189
- Code: "TenantList",
4190
- Data: tenantRows
4191
- });
2453
+ const { runTenantList } = await import("./handlers-93z27zrr.js");
2454
+ await runTenantList(context, options);
4192
2455
  });
4193
2456
  tenantCommand.command("set").description("Set the active tenant by name").argument("<name>", "Tenant name to set as active").option("-f, --file <folder>", "Path to credentials folder").examples(LOGIN_TENANT_SET_EXAMPLES).trackedAction(context, async (name, options) => {
4194
- if (rejectProfileFileConflict(context, options.file)) {
4195
- return;
4196
- }
4197
- if (isEnvAuthEnabled()) {
4198
- OutputFormatter.error({
4199
- Result: RESULTS.ConfigError,
4200
- Message: "Cannot change the active tenant while environment-variable authentication is enabled.",
4201
- Instructions: "Update UIPATH_CLI_TENANT_NAME and UIPATH_CLI_TENANT_ID, or unset UIPATH_CLI_ENABLE_ENV_AUTH to use file-based login."
4202
- });
4203
- context.exit(1);
4204
- return;
4205
- }
4206
- const envFilePath = resolveAuthFilePath(options.file);
4207
- const [locationError, location] = await catchError(resolveEnvFileLocationAsync(envFilePath));
4208
- if (locationError) {
4209
- OutputFormatter.error({
4210
- Result: RESULTS.Failure,
4211
- Message: `Failed to locate credentials file: ${locationError.message}`,
4212
- Instructions: "Check filesystem permissions on the current directory and your home directory, then re-run."
4213
- });
4214
- context.exit(1);
4215
- return;
4216
- }
4217
- if (!location.exists) {
4218
- if (location.unusable) {
4219
- OutputFormatter.error({
4220
- Result: RESULTS.Failure,
4221
- Message: `Credentials file at ${location.absolutePath} is not usable: ${location.unusable.message}`,
4222
- Instructions: location.unusable.reason === "not-a-file" ? `Path resolves to a directory or special file. Move or rename ${location.absolutePath}, then run ${quotedLoginRetryCommand()} to recreate the credentials file.` : `Check filesystem permissions on ${location.absolutePath} and re-run.`
4223
- });
4224
- context.exit(1);
4225
- return;
4226
- }
4227
- OutputFormatter.error({
4228
- Result: RESULTS.AuthenticationError,
4229
- Message: "Not authenticated",
4230
- Instructions: authenticateFirstInstruction()
4231
- });
4232
- context.exit(2);
4233
- return;
4234
- }
4235
- const resolvedEnvFilePath = location.absolutePath;
4236
- const [statusError, status] = await catchError(auth.getLoginStatus({ envFilePath: resolvedEnvFilePath }));
4237
- if (statusError) {
4238
- OutputFormatter.error({
4239
- Result: RESULTS.ConfigError,
4240
- Message: loginErrorMessage(statusError),
4241
- Instructions: instructionsForStatusError(statusError)
4242
- });
4243
- context.exit(1);
4244
- return;
4245
- }
4246
- trackTokenRefresh(status);
4247
- if (status.loginStatus !== "Logged in" || !status.accessToken || !status.baseUrl || !status.organizationId) {
4248
- OutputFormatter.error({
4249
- Result: RESULTS.AuthenticationError,
4250
- Message: "Not authenticated",
4251
- Instructions: status.hint || authenticateFirstInstruction()
4252
- });
4253
- context.exit(2);
4254
- return;
4255
- }
4256
- const [fetchError, data] = await catchError(auth.fetchTenants(status.baseUrl, status.accessToken, status.organizationName || status.organizationId));
4257
- if (fetchError) {
4258
- const connectivity = describeConnectivityError(fetchError);
4259
- OutputFormatter.error({
4260
- Result: RESULTS.Failure,
4261
- Message: loginErrorMessage(fetchError),
4262
- Instructions: connectivity?.instructions ?? "Failed to fetch tenants. Check your network connection and try again."
4263
- });
4264
- context.exit(1);
4265
- return;
4266
- }
4267
- const matchedTenant = data.tenants.find((t) => t.name === name);
4268
- if (!matchedTenant) {
4269
- const availableNames = data.tenants.map((t) => t.name).join(", ");
4270
- OutputFormatter.error({
4271
- Result: RESULTS.ValidationError,
4272
- Message: `Tenant "${name}" not found`,
4273
- Instructions: `argument should be one of ${availableNames}`
4274
- });
4275
- context.exit(3);
4276
- return;
4277
- }
4278
- const [saveError] = await catchError(auth.saveTenantSelection(resolvedEnvFilePath, matchedTenant.name, matchedTenant.id));
4279
- if (saveError) {
4280
- OutputFormatter.error({
4281
- Result: RESULTS.Failure,
4282
- Message: saveError.message,
4283
- Instructions: "Failed to save tenant selection. Check file permissions and try again."
4284
- });
4285
- context.exit(1);
4286
- return;
4287
- }
4288
- OutputFormatter.success({
4289
- Result: RESULTS.Success,
4290
- Code: "TenantSet",
4291
- Data: {
4292
- Name: matchedTenant.name,
4293
- Id: matchedTenant.id
4294
- }
4295
- });
2457
+ const { runTenantSet } = await import("./handlers-93z27zrr.js");
2458
+ await runTenantSet(context, name, options);
4296
2459
  }, (name) => ({ TenantName: name }));
4297
2460
  loginCommand.command("which").description("Print the auth source uip would use for the current cwd.").examples(LOGIN_WHICH_EXAMPLES).trackedAction(context, async () => {
4298
- if (isEnvAuthEnabled()) {
4299
- emitAuthEnv();
4300
- return;
4301
- }
4302
- const profile = getActiveAuthProfile();
4303
- const [locationError, location] = await catchError(resolveEnvFileLocationAsync(resolveAuthFilePath()));
4304
- if (locationError) {
4305
- OutputFormatter.error({
4306
- Result: RESULTS.Failure,
4307
- Message: `Failed to locate credentials file: ${locationError.message}`,
4308
- Instructions: "Check filesystem permissions on the current directory and your home directory, then re-run."
4309
- });
4310
- context.exit(1);
4311
- return;
4312
- }
4313
- if (location.exists) {
4314
- const data = {
4315
- Path: location.absolutePath,
4316
- Exists: true,
4317
- Source: location.source,
4318
- ...profile ? { Profile: profile } : {}
4319
- };
4320
- OutputFormatter.success({
4321
- Result: RESULTS.Success,
4322
- Code: "AuthFile",
4323
- Data: data
4324
- });
4325
- return;
4326
- }
4327
- if (location.unusable) {
4328
- OutputFormatter.error({
4329
- Result: RESULTS.Failure,
4330
- Message: `Credentials file at ${location.absolutePath} is not usable: ${location.unusable.message}`,
4331
- Instructions: location.unusable.reason === "not-a-file" ? `Path resolves to a directory or special file. Move or rename ${location.absolutePath}, then run ${quotedLoginRetryCommand()} to recreate the credentials file.` : `Check filesystem permissions on ${location.absolutePath} and re-run.`
4332
- });
4333
- context.exit(1);
4334
- return;
4335
- }
4336
- OutputFormatter.error({
4337
- Result: RESULTS.AuthenticationError,
4338
- Message: profile ? `No credentials file found for profile "${profile}".` : "No credentials file found.",
4339
- Instructions: profile ? `Run 'uip login --profile ${profile}' to authenticate this profile.` : "Run 'uip login' to authenticate, or set UIPATH_CLI_ENABLE_ENV_AUTH=true to use environment variables."
4340
- });
4341
- context.exit(2);
4342
- });
4343
- }
4344
- function emitAuthEnv() {
4345
- const vars = Object.values(ENV_AUTH_VARS);
4346
- const missingVars = vars.filter((name) => !process.env[name]);
4347
- const data = {
4348
- EnableVar: ENV_AUTH_ENABLE_VAR,
4349
- AllVarsPresent: missingVars.length === 0,
4350
- MissingVars: missingVars,
4351
- Vars: vars
4352
- };
4353
- OutputFormatter.success({
4354
- Result: RESULTS.Success,
4355
- Code: "AuthEnv",
4356
- Data: data
2461
+ const { runLoginWhich } = await import("./handlers-93z27zrr.js");
2462
+ await runLoginWhich(context);
4357
2463
  });
4358
2464
  }
4359
2465
 
@@ -4372,7 +2478,7 @@ var LOGOUT_EXAMPLES = [
4372
2478
  ];
4373
2479
  function registerLogoutCommand(program, context) {
4374
2480
  program.command("logout").description("Logout from UiPath Cloud by removing credentials").option("-f, --file <folder>", "Path to credentials folder").examples(LOGOUT_EXAMPLES).trackedAction(context, async (options) => {
4375
- if (getActiveAuthProfile() && options.file !== undefined) {
2481
+ if (getActiveAuthProfile2() && options.file !== undefined) {
4376
2482
  OutputFormatter.error({
4377
2483
  Result: RESULTS.ValidationError,
4378
2484
  Message: "error: option '--profile' cannot be used with option '--file'",
@@ -4381,8 +2487,8 @@ function registerLogoutCommand(program, context) {
4381
2487
  context.exit(EXIT_CODES.ValidationError);
4382
2488
  return;
4383
2489
  }
4384
- const file = options.file ? getFileSystem().path.join(options.file, DEFAULT_AUTH_FILENAME) : undefined;
4385
- const [logoutError, result] = await catchError(logout({ file }));
2490
+ const file = options.file ? getFileSystem2().path.join(options.file, DEFAULT_AUTH_FILENAME2) : undefined;
2491
+ const [logoutError, result] = await catchError(logout2({ file }));
4386
2492
  if (logoutError) {
4387
2493
  OutputFormatter.error({
4388
2494
  Result: RESULTS.Failure,
@@ -4420,7 +2526,7 @@ function registerLogoutCommand(program, context) {
4420
2526
  function registerMcpCommand(program) {
4421
2527
  const mcpCommand = program.command("mcp").description("Model Context Protocol (MCP) server");
4422
2528
  mcpCommand.command("serve").description("Start the MCP server (stdio transport)").trackedAction(processContext, async () => {
4423
- const { startMcpServer } = await import("./server-9k50dfg6.js");
2529
+ const { startMcpServer } = await import("./server-gkr3c7hv.js");
4424
2530
  await startMcpServer(program);
4425
2531
  });
4426
2532
  }
@@ -4428,7 +2534,7 @@ function registerMcpCommand(program) {
4428
2534
  // src/services/deviceId.ts
4429
2535
  var DEVICE_ID_FILENAME = "cli-device-id";
4430
2536
  async function getOrCreateDeviceId() {
4431
- const fs = getFileSystem();
2537
+ const fs = getFileSystem2();
4432
2538
  const homeDir = fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR);
4433
2539
  const filePath = fs.path.join(homeDir, DEVICE_ID_FILENAME);
4434
2540
  const existing = await fs.readFile(filePath, "utf-8");
@@ -4448,405 +2554,6 @@ async function getOrCreateDeviceId() {
4448
2554
  return newId;
4449
2555
  }
4450
2556
 
4451
- // src/services/environmentInfo.ts
4452
- import { arch as osArch, release as osRelease, type as osType } from "node:os";
4453
- function decodeJwtPayload(token) {
4454
- const parts = token.split(".");
4455
- if (parts.length !== 3)
4456
- return;
4457
- const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
4458
- const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
4459
- const [, parsed] = catchError(() => JSON.parse(atob(padded)));
4460
- return parsed;
4461
- }
4462
- async function getAuthContext() {
4463
- const [statusError, status] = await catchError(auth.getLoginStatus());
4464
- if (statusError || status.loginStatus !== "Logged in" || !status.accessToken) {
4465
- return {};
4466
- }
4467
- const claims = decodeJwtPayload(status.accessToken);
4468
- return {
4469
- email: claims?.email ?? claims?.preferred_username,
4470
- userId: claims?.sub,
4471
- organizationId: status.organizationId,
4472
- organizationName: status.organizationName,
4473
- tenantId: status.tenantId,
4474
- tenantName: status.tenantName
4475
- };
4476
- }
4477
- function buildEnvironmentString(authCtx) {
4478
- const lines = [];
4479
- if (authCtx.email)
4480
- lines.push(`User Email: ${authCtx.email}`);
4481
- lines.push(`CLI Version: ${package_default.version}`, `Node Version: ${process.version}`, `OS: ${osType()} ${osRelease()} (${osArch()})`, `Platform: ${process.platform}`);
4482
- const agent = detectAgent();
4483
- if (agent)
4484
- lines.push(`Coding Agent: ${agent}`);
4485
- const skillsVersion = process.env.UIPATH_SKILLS_VERSION;
4486
- if (skillsVersion)
4487
- lines.push(`Skills Plugin Version: ${skillsVersion}`);
4488
- if (authCtx.userId)
4489
- lines.push(`Cloud User ID: ${authCtx.userId}`);
4490
- if (authCtx.organizationName)
4491
- lines.push(`Cloud Organization: ${authCtx.organizationName}`);
4492
- if (authCtx.organizationId)
4493
- lines.push(`Cloud Organization ID: ${authCtx.organizationId}`);
4494
- if (authCtx.tenantName)
4495
- lines.push(`Tenant: ${authCtx.tenantName}`);
4496
- if (authCtx.tenantId)
4497
- lines.push(`Tenant ID: ${authCtx.tenantId}`);
4498
- return lines.join(`
4499
- `);
4500
- }
4501
-
4502
- // src/services/markdownToJiraWiki.ts
4503
- var SENTINEL = "\x00";
4504
- function countLeadingHashes(line) {
4505
- let n = 0;
4506
- while (n < line.length && n <= 6 && line[n] === "#")
4507
- n++;
4508
- return n;
4509
- }
4510
- function leadingSpaces(line) {
4511
- let n = 0;
4512
- while (n < line.length && line[n] === " ")
4513
- n++;
4514
- return n;
4515
- }
4516
- function convertInline(text) {
4517
- const codeSpans = [];
4518
- const boldSpans = [];
4519
- let s = text.replace(/`([^`\n]+)`/g, (_m, code) => {
4520
- codeSpans.push(code);
4521
- return `${SENTINEL}C${codeSpans.length - 1}${SENTINEL}`;
4522
- });
4523
- s = s.replace(/\[([^\]\n]{1,300})\]\(([^)\s\n]{1,800})\)/g, (_m, label, url) => `[${label}|${url}]`);
4524
- const toBoldPlaceholder = (_m, inner) => {
4525
- boldSpans.push(inner);
4526
- return `${SENTINEL}B${boldSpans.length - 1}${SENTINEL}`;
4527
- };
4528
- s = s.replace(/\*\*([^*\n]+)\*\*/g, toBoldPlaceholder);
4529
- s = s.replace(/__([^_\n]+)__/g, toBoldPlaceholder);
4530
- s = s.replace(/\*([^*\n]+)\*/g, (m, inner) => inner.trim() === "" || inner.startsWith(" ") || inner.endsWith(" ") ? m : `_${inner}_`);
4531
- s = s.replace(/~~([^~\n]+)~~/g, "-$1-");
4532
- s = s.replace(new RegExp(`${SENTINEL}B(\\d+)${SENTINEL}`, "g"), (_m, i) => `*${boldSpans[Number(i)]}*`);
4533
- s = s.replace(new RegExp(`${SENTINEL}C(\\d+)${SENTINEL}`, "g"), (_m, i) => `{{${codeSpans[Number(i)]}}}`);
4534
- return s;
4535
- }
4536
- function fenceLang(line) {
4537
- const t = line.trim();
4538
- if (!t.startsWith("```"))
4539
- return null;
4540
- const lang = t.slice(3).trim();
4541
- for (const ch of lang) {
4542
- if (ch === " " || ch === "\t")
4543
- return null;
4544
- }
4545
- return lang;
4546
- }
4547
- function markdownToJiraWiki(markdown) {
4548
- const lines = markdown.replace(/\r\n/g, `
4549
- `).split(`
4550
- `);
4551
- const out = [];
4552
- let inFence = false;
4553
- for (const line of lines) {
4554
- const lang = fenceLang(line);
4555
- if (lang !== null) {
4556
- if (inFence) {
4557
- out.push("{code}");
4558
- inFence = false;
4559
- } else {
4560
- out.push(lang ? `{code:${lang}}` : "{code}");
4561
- inFence = true;
4562
- }
4563
- continue;
4564
- }
4565
- if (inFence) {
4566
- out.push(line);
4567
- continue;
4568
- }
4569
- const hashes = countLeadingHashes(line);
4570
- if (hashes > 0 && (line[hashes] === " " || line[hashes] === "\t")) {
4571
- out.push(`h${hashes}. ${convertInline(line.slice(hashes).trim())}`);
4572
- continue;
4573
- }
4574
- const indent = leadingSpaces(line);
4575
- const depth = Math.floor(indent / 2) + 1;
4576
- const rest = line.slice(indent);
4577
- let d = 0;
4578
- while (d < rest.length && rest[d] >= "0" && rest[d] <= "9")
4579
- d++;
4580
- if (d > 0 && rest[d] === "." && rest[d + 1] === " ") {
4581
- out.push(`${"#".repeat(depth)} ${convertInline(rest.slice(d + 2))}`);
4582
- continue;
4583
- }
4584
- const marker = rest[0];
4585
- if ((marker === "-" || marker === "*" || marker === "+") && rest[1] === " ") {
4586
- out.push(`${"*".repeat(depth)} ${convertInline(rest.slice(2))}`);
4587
- continue;
4588
- }
4589
- out.push(convertInline(line));
4590
- }
4591
- if (inFence)
4592
- out.push("{code}");
4593
- return out.join(`
4594
- `);
4595
- }
4596
-
4597
- // src/services/feedbackService.ts
4598
- var FEEDBACK_ENDPOINT = process.env.UIPATH_CLI_FEEDBACK_ENDPOINT || atob("aHR0cHM6Ly9zdHVkaW8tZmVlZGJhY2suYXp1cmUtYXBpLm5ldC9jb2RpbmctYWdlbnRz");
4599
- var PROJECT_ID = "10677";
4600
- var CLI_COMPONENT_ID = "29590";
4601
- var FIELD_ENVIRONMENT = "customfield_11434";
4602
- var FIELD_STEPS_TO_REPRODUCE = "customfield_11433";
4603
- var JIRA_BROWSE_BASE_URL = "https://uipath.atlassian.net/browse";
4604
- function buildIssueUrl(key) {
4605
- return `${JIRA_BROWSE_BASE_URL}/${key}`;
4606
- }
4607
- var VALID_TYPES = ["bug", "improvement"];
4608
- var VALID_PRIORITIES = ["critical", "normal", "minor"];
4609
- function normalizeUrl(value) {
4610
- return value.trim().replace(/[\r\n\t]+/g, "");
4611
- }
4612
- var FEEDBACK_TYPE_MAP = {
4613
- bug: { id: "1", name: "Bug" },
4614
- improvement: { id: "4", name: "Improvement" }
4615
- };
4616
- var PRIORITY_MAP = {
4617
- critical: "3",
4618
- normal: "5",
4619
- minor: "4"
4620
- };
4621
- var NON_LABEL_TOKENS = new Set([
4622
- "bug",
4623
- "improvement",
4624
- "critical",
4625
- "normal",
4626
- "minor"
4627
- ]);
4628
- function toLabel(value) {
4629
- const normalized = value.trim().replace(/[^\p{L}\p{N}]+/gu, "");
4630
- return normalized.length > 0 ? normalized : undefined;
4631
- }
4632
- function deriveLabelsFromTitle(title) {
4633
- const labels = [];
4634
- const leadingTag = /^\s*\[([^\]]+)\]/;
4635
- let rest = title;
4636
- let match = leadingTag.exec(rest);
4637
- while (match) {
4638
- const label = toLabel(match[1]);
4639
- if (label && !NON_LABEL_TOKENS.has(label.toLowerCase())) {
4640
- labels.push(label);
4641
- }
4642
- rest = rest.slice(match[0].length);
4643
- match = leadingTag.exec(rest);
4644
- }
4645
- return labels;
4646
- }
4647
- async function createFeedbackIssue(options) {
4648
- const feedbackType = FEEDBACK_TYPE_MAP[options.type];
4649
- const priorityId = PRIORITY_MAP[options.priority];
4650
- const descriptionParts = [markdownToJiraWiki(options.description)];
4651
- if (options.slackThreadUrl) {
4652
- descriptionParts.push(`Slack Thread: ${normalizeUrl(options.slackThreadUrl)}`);
4653
- }
4654
- const body = {
4655
- fields: {
4656
- project: { id: PROJECT_ID },
4657
- components: [{ id: CLI_COMPONENT_ID }],
4658
- versions: [],
4659
- summary: options.title,
4660
- description: descriptionParts.join(`
4661
- `),
4662
- issuetype: { id: feedbackType.id, name: feedbackType.name },
4663
- [FIELD_ENVIRONMENT]: options.environment,
4664
- [FIELD_STEPS_TO_REPRODUCE]: "",
4665
- labels: deriveLabelsFromTitle(options.title),
4666
- priority: { id: priorityId }
4667
- }
4668
- };
4669
- const response = await fetch(`${FEEDBACK_ENDPOINT}/issue/`, {
4670
- method: "POST",
4671
- headers: {
4672
- "Content-Type": "application/json",
4673
- "Accept-Encoding": "gzip, deflate",
4674
- deviceId: options.deviceId
4675
- },
4676
- body: JSON.stringify(body),
4677
- signal: AbortSignal.timeout(DEFAULT_FETCH_TIMEOUT_MS)
4678
- });
4679
- const text = await response.text();
4680
- if (!response.ok) {
4681
- if (response.status === 429) {
4682
- throw new Error("Too many feedback submissions. Please wait and try again later.");
4683
- }
4684
- throw new Error(`Failed to create feedback issue: ${text}`);
4685
- }
4686
- const [parseError, result] = catchError(() => JSON.parse(text));
4687
- if (parseError || !result?.key) {
4688
- throw new Error(`Unexpected response from feedback service: ${text}`);
4689
- }
4690
- return { key: result.key, sig: result.sig ?? "" };
4691
- }
4692
- async function uploadAttachment(issueId, signature, deviceId, filePath) {
4693
- const fs = getFileSystem();
4694
- const fileBuffer = await fs.readFile(filePath);
4695
- if (!fileBuffer) {
4696
- throw new Error(`Could not read attachment: "${fs.path.basename(filePath)}"`);
4697
- }
4698
- const fileName = fs.path.basename(filePath);
4699
- const formData = new FormData;
4700
- formData.append("file", new Blob([new Uint8Array(fileBuffer)]), fileName);
4701
- const response = await fetch(`${FEEDBACK_ENDPOINT}/issue/${issueId}/attachments`, {
4702
- method: "POST",
4703
- headers: {
4704
- "X-SIG": signature,
4705
- deviceId,
4706
- "Accept-Encoding": "gzip, deflate"
4707
- },
4708
- body: formData,
4709
- signal: AbortSignal.timeout(DEFAULT_FETCH_TIMEOUT_MS)
4710
- });
4711
- const text = await response.text();
4712
- if (!response.ok) {
4713
- throw new Error(`Failed to upload attachment "${fileName}": ${text}`);
4714
- }
4715
- }
4716
- async function validateAttachment(filePath) {
4717
- const MAX_FILE_SIZE = 10 * 1024 * 1024;
4718
- const fs = getFileSystem();
4719
- const stat = await fs.stat(filePath);
4720
- if (!stat) {
4721
- throw new Error(`Attachment not found: "${fs.path.basename(filePath)}"`);
4722
- }
4723
- if (stat.size > MAX_FILE_SIZE) {
4724
- throw new Error(`Attachment "${fs.path.basename(filePath)}" exceeds 10 MB limit (${Math.round(stat.size / 1024 / 1024)} MB).`);
4725
- }
4726
- }
4727
-
4728
- // src/services/feedbackPrompts.ts
4729
- function isExitPrompt(error) {
4730
- return error instanceof Error && error.name === "ExitPromptError";
4731
- }
4732
- function validateNonEmpty(value, field) {
4733
- return value.trim().length > 0 ? true : `${field} cannot be empty.`;
4734
- }
4735
- var INVALID_URL_MESSAGE = "Enter a valid URL (must be http or https).";
4736
- function validateUrl(value) {
4737
- const normalized = normalizeUrl(value);
4738
- if (normalized.length === 0) {
4739
- return INVALID_URL_MESSAGE;
4740
- }
4741
- const [parseError, parsed] = catchError(() => new URL(normalized));
4742
- if (parseError || !parsed) {
4743
- return INVALID_URL_MESSAGE;
4744
- }
4745
- return parsed.protocol === "http:" || parsed.protocol === "https:" ? true : INVALID_URL_MESSAGE;
4746
- }
4747
- async function promptSlackThread(existing) {
4748
- if (existing !== undefined) {
4749
- const normalized = normalizeUrl(existing);
4750
- return normalized.length > 0 ? normalized : undefined;
4751
- }
4752
- return askSlackThread();
4753
- }
4754
- async function askSlackThread(current) {
4755
- const hasThread = await dist_default({
4756
- message: "Is there a related Slack thread?",
4757
- default: current !== undefined
4758
- });
4759
- if (!hasThread) {
4760
- return;
4761
- }
4762
- const url = await dist_default2({
4763
- message: "Slack thread URL:",
4764
- default: current,
4765
- validate: validateUrl
4766
- });
4767
- return normalizeUrl(url);
4768
- }
4769
- function renderPreview(draft, context) {
4770
- const lines = [
4771
- "",
4772
- "Review your feedback before sending:",
4773
- ` Type: ${draft.type}`,
4774
- ` Priority: ${draft.priority}`,
4775
- ` Title: ${draft.title}`,
4776
- ` Description: ${draft.description}`
4777
- ];
4778
- if (context.email) {
4779
- lines.push(` Email: ${context.email}`);
4780
- }
4781
- if (draft.slackThreadUrl) {
4782
- lines.push(` Slack: ${draft.slackThreadUrl}`);
4783
- }
4784
- if (context.attachmentCount > 0) {
4785
- lines.push(` Attachments: ${context.attachmentCount}`);
4786
- }
4787
- lines.push("");
4788
- return lines.join(`
4789
- `);
4790
- }
4791
- async function editDraft(draft) {
4792
- const type = await dist_default3({
4793
- message: "Type:",
4794
- default: draft.type,
4795
- choices: VALID_TYPES.map((value) => ({ name: value, value }))
4796
- });
4797
- const priority = await dist_default3({
4798
- message: "Priority:",
4799
- default: draft.priority,
4800
- choices: VALID_PRIORITIES.map((value) => ({ name: value, value }))
4801
- });
4802
- const title = await dist_default2({
4803
- message: "Title:",
4804
- default: draft.title,
4805
- validate: (value) => validateNonEmpty(value, "Title")
4806
- });
4807
- const description = await dist_default2({
4808
- message: "Description:",
4809
- default: draft.description,
4810
- validate: (value) => validateNonEmpty(value, "Description")
4811
- });
4812
- const slackThreadUrl = await askSlackThread(draft.slackThreadUrl);
4813
- return {
4814
- type,
4815
- priority,
4816
- title: title.trim(),
4817
- description: description.trim(),
4818
- slackThreadUrl
4819
- };
4820
- }
4821
- async function confirmFeedback(initial, context, print) {
4822
- let draft = initial;
4823
- try {
4824
- while (true) {
4825
- print(renderPreview(draft, context));
4826
- const action = await dist_default3({
4827
- message: "What would you like to do?",
4828
- choices: [
4829
- { name: "Send feedback", value: "send" },
4830
- { name: "Edit details", value: "edit" },
4831
- { name: "Cancel", value: "cancel" }
4832
- ]
4833
- });
4834
- if (action === "send") {
4835
- return { action: "send", draft };
4836
- }
4837
- if (action === "cancel") {
4838
- return { action: "cancel" };
4839
- }
4840
- draft = await editDraft(draft);
4841
- }
4842
- } catch (error) {
4843
- if (isExitPrompt(error)) {
4844
- return { action: "cancel" };
4845
- }
4846
- throw error;
4847
- }
4848
- }
4849
-
4850
2557
  // src/commands/send-feedback.ts
4851
2558
  var MAX_ATTACHMENTS = 10;
4852
2559
  var FEEDBACK_SEND_EXAMPLES = [
@@ -4892,6 +2599,7 @@ async function validateSendInputs(options, attachments) {
4892
2599
  Instructions: `--priority must be one of: ${VALID_PRIORITIES.join(", ")}`
4893
2600
  };
4894
2601
  }
2602
+ const { validateUrl } = await import("./feedbackPrompts-t1enxv1x.js");
4895
2603
  if (options.slackThread !== undefined && validateUrl(options.slackThread) !== true) {
4896
2604
  return {
4897
2605
  Result: RESULTS.ValidationError,
@@ -4906,7 +2614,7 @@ async function validateSendInputs(options, attachments) {
4906
2614
  Instructions: `Maximum ${MAX_ATTACHMENTS} attachments allowed.`
4907
2615
  };
4908
2616
  }
4909
- const fs = getFileSystem();
2617
+ const fs = getFileSystem2();
4910
2618
  for (const filePath of attachments) {
4911
2619
  if (!await fs.exists(filePath)) {
4912
2620
  return {
@@ -4939,6 +2647,7 @@ async function uploadAttachments(key, sig, deviceId, attachments) {
4939
2647
  return uploaded;
4940
2648
  }
4941
2649
  async function reviewFeedback(draft, email, attachmentCount, context) {
2650
+ const { confirmFeedback, isExitPrompt, promptSlackThread } = await import("./feedbackPrompts-t1enxv1x.js");
4942
2651
  const [promptError, slackThreadUrl] = await catchError(promptSlackThread(draft.slackThreadUrl));
4943
2652
  if (promptError) {
4944
2653
  if (isExitPrompt(promptError)) {
@@ -4950,7 +2659,7 @@ async function reviewFeedback(draft, email, attachmentCount, context) {
4950
2659
  return result.action === "send" ? result.draft : undefined;
4951
2660
  }
4952
2661
  var STDIN_READ_TIMEOUT_MS = 1e4;
4953
- var MAX_DESCRIPTION_BYTES = 32 * 1024;
2662
+ var MAX_DESCRIPTION_BYTES = 32768;
4954
2663
  function validationError(message, instructions) {
4955
2664
  return {
4956
2665
  Result: RESULTS.ValidationError,
@@ -4984,7 +2693,7 @@ async function readRawDescription(options) {
4984
2693
  };
4985
2694
  }
4986
2695
  async function readDescriptionFile(filePath) {
4987
- const fs = getFileSystem();
2696
+ const fs = getFileSystem2();
4988
2697
  if (!await fs.exists(filePath)) {
4989
2698
  return {
4990
2699
  error: validationError(`Description file not found: "${filePath}"`, "Check the file path and try again.")
@@ -5020,10 +2729,11 @@ async function resolveDescription(options) {
5020
2729
  function registerFeedbackCommand(program, context) {
5021
2730
  const feedback = program.command("feedback").description("Send bug reports and improvement suggestions");
5022
2731
  feedback.command("send").description("Send feedback (bug report or improvement suggestion) to the UiPath team. Provide the description body via exactly one of --description, --description-file, or stdin.").requiredOption("--type <type>", "Feedback type: bug or improvement").requiredOption("--title <title>", "Issue title / summary").option("--description <text>", "Detailed description or steps to reproduce (single-line safe; for large multi-line bodies use --description-file or stdin)").option("--description-file <path>", "Read the description body from a file. Shell-safe for large multi-line markdown — required on Windows PowerShell, where inlining --description mangles the value").option("--priority <priority>", "Priority: critical, normal, or minor (default: normal)", "normal").option("--email <email>", "Contact email address").option("--attachment <paths...>", "File(s) to attach (max 10, max 10MB each)").option("--slack-thread <url>", "Link to a related Slack discussion to include in the ticket").examples(FEEDBACK_SEND_EXAMPLES).trackedAction(context, async (options) => {
2732
+ const { buildEnvironmentString, getAuthContext } = await import("./environmentInfo-fn0za9jw.js");
5023
2733
  const attachments = options.attachment ?? [];
5024
- const validationError2 = await validateSendInputs(options, attachments);
5025
- if (validationError2) {
5026
- OutputFormatter.error(validationError2);
2734
+ const validationError = await validateSendInputs(options, attachments);
2735
+ if (validationError) {
2736
+ OutputFormatter.error(validationError);
5027
2737
  return;
5028
2738
  }
5029
2739
  const resolvedDescription = await resolveDescription(options);
@@ -5185,10 +2895,12 @@ var SKILLS_SHOW_EXAMPLES = [
5185
2895
  }
5186
2896
  ];
5187
2897
  function getRootDir(options) {
5188
- const fs = getFileSystem();
2898
+ const fs = getFileSystem2();
5189
2899
  return options.local ? fs.env.cwd() : fs.env.homedir();
5190
2900
  }
5191
2901
  async function resolveCatalog(options) {
2902
+ const { getAvailableSkills, getContentStoreForRead, resolveSkillSource } = await import("./contentStore-c51xqdn2.js");
2903
+ const { buildSkillCatalog } = await import("./skillCatalog-fvw4wgw1.js");
5192
2904
  const rootDir = getRootDir(options);
5193
2905
  const source = resolveSkillSource(options.repo, options.branch);
5194
2906
  const storePath = await getContentStoreForRead(rootDir, source);
@@ -5204,7 +2916,7 @@ async function resolveCatalog(options) {
5204
2916
  return { rootDir, storePath, skills, shadowed, catalog };
5205
2917
  }
5206
2918
  function skillFilePath(skill) {
5207
- const fs = getFileSystem();
2919
+ const fs = getFileSystem2();
5208
2920
  return fs.path.join(skill.skillDir, "SKILL.md");
5209
2921
  }
5210
2922
  function enrichEntry(entry, discovered) {
@@ -5274,6 +2986,7 @@ function registerCatalogCommands(skillsCommand) {
5274
2986
  const resolved = await loadCatalogOrReport(options);
5275
2987
  if (!resolved)
5276
2988
  return;
2989
+ const { searchSkillCatalog } = await import("./skillCatalog-fvw4wgw1.js");
5277
2990
  const skills = searchSkillCatalog(resolved.catalog, query).slice(0, limit);
5278
2991
  OutputFormatter.success({
5279
2992
  Result: RESULTS.Success,
@@ -5377,6 +3090,7 @@ function registerInstallCommand(skillsCommand) {
5377
3090
  skillsCommand.command("install").description(`Download UiPath skills from the configured npm registry and install
5378
3091
  ` + `them for your coding agents. Pass --repo to install from another
5379
3092
  ` + "GitHub/git repository or a local directory instead.").option("--agent <agent>", `Target agent: ${ALL_AGENTS.join(", ")}`).option("--skip-if-no-agent", "Exit successfully without installing when no supported agent is detected").option("--local", "Install to current project instead of globally").option("--path <dir>", "Install to a specific project directory (implies --local)").option("--repo <url>", "Install from another skills repo (GitHub owner/repo, https/git URL, or a local directory like ./skills). Defaults to the UiPath skills repository.").option("--branch <name>", "Branch to fetch from --repo (defaults to the repo's default branch)").option("--force", "Reinstall from a clean state (resets the Claude Code marketplace registration and plugin cache)").examples(SKILLS_INSTALL_EXAMPLES).trackedAction(processContext, async (options) => {
3093
+ const { resolveSkillsContext, runAgentInstalls, SkillsError } = await import("./skillsService-20es18vs.js");
5380
3094
  const [contextError, resolved] = await catchError(resolveSkillsContext(options, "install"));
5381
3095
  if (contextError || !resolved) {
5382
3096
  if (contextError) {
@@ -5493,6 +3207,7 @@ async function resolveAgents(options, isLocal, isDefaultSource) {
5493
3207
  processContext.exit(1);
5494
3208
  return HANDLED;
5495
3209
  }
3210
+ const { promptAgentSelection } = await import("./prompt-hxbzt92e.js");
5496
3211
  const [agentErr, selected] = await catchError(promptAgentSelection("uninstall", isLocal));
5497
3212
  if (agentErr) {
5498
3213
  if (agentErr instanceof Error && agentErr.name === "ExitPromptError") {
@@ -5504,6 +3219,7 @@ async function resolveAgents(options, isLocal, isDefaultSource) {
5504
3219
  return selected;
5505
3220
  }
5506
3221
  async function readSkillNames(storePath) {
3222
+ const { readManifest } = await import("./contentStore-c51xqdn2.js");
5507
3223
  const [manifestErr, manifest] = await catchError(readManifest(storePath));
5508
3224
  if (manifestErr || !manifest) {
5509
3225
  OutputFormatter.error({
@@ -5557,6 +3273,7 @@ async function uninstallForAgent(targetAgent, ctx, uninstalled) {
5557
3273
  }
5558
3274
  uninstalled.push(`${targetAgent}:${name}`);
5559
3275
  }
3276
+ const { readExtraFiles } = await import("./contentStore-c51xqdn2.js");
5560
3277
  const [, ownedExtra] = await catchError(readExtraFiles(storePath, targetAgent));
5561
3278
  const [extraError] = await catchError(uninstallExtraFolders(skillsDir, ownedExtra ?? []));
5562
3279
  if (extraError) {
@@ -5568,6 +3285,7 @@ async function uninstallForAgent(targetAgent, ctx, uninstalled) {
5568
3285
  return HANDLED;
5569
3286
  }
5570
3287
  if (isDefaultSource) {
3288
+ const { removeSkillCatalog } = await import("./skillCatalog-fvw4wgw1.js");
5571
3289
  const [catalogError] = await catchError(removeSkillCatalog(skillsDir));
5572
3290
  if (catalogError) {
5573
3291
  OutputFormatter.error({
@@ -5583,11 +3301,13 @@ async function uninstallForAgent(targetAgent, ctx, uninstalled) {
5583
3301
  }
5584
3302
  function registerUninstallCommand(skillsCommand) {
5585
3303
  skillsCommand.command("uninstall").description("Remove previously installed skills from agent configurations.").option("--agent <agent>", `Target agent: ${ALL_AGENTS.join(", ")}`).option("--local", "Uninstall from current project instead of globally").option("--path <dir>", "Uninstall from a specific project directory (implies --local)").option("--repo <url>", "Uninstall skills previously installed from another repo. Defaults to the UiPath skills repository.").option("--branch <name>", "Branch that was used with --repo").examples(SKILLS_UNINSTALL_EXAMPLES).trackedAction(processContext, async (options) => {
3304
+ const { removeFromManifest, resolveSkillSource } = await import("./contentStore-c51xqdn2.js");
3305
+ const { resolveRootDir } = await import("./skillsService-20es18vs.js");
5586
3306
  const root = await resolveRootDir(options);
5587
3307
  if (!root)
5588
3308
  return;
5589
3309
  const { isLocal, rootDir } = root;
5590
- const fs = getFileSystem();
3310
+ const fs = getFileSystem2();
5591
3311
  const source = resolveSkillSource(options.repo, options.branch);
5592
3312
  const storePath = fs.path.join(rootDir, source.storeName);
5593
3313
  const agents = await resolveAgents(options, isLocal, source.isDefault);
@@ -5665,6 +3385,9 @@ var SKILLS_UPDATE_EXAMPLES = [
5665
3385
  ];
5666
3386
  function registerUpdateCommand(skillsCommand) {
5667
3387
  skillsCommand.command("update").description("Re-fetch UiPath skills from the configured npm registry and reinstall the latest patch matching the target line (the core.version pin when set, else this CLI's version line).").option("--agent <agent>", `Target agent: ${ALL_AGENTS.join(", ")}`).option("--local", "Update in current project instead of globally").option("--path <dir>", "Update skills in a specific project directory (implies --local)").option("--repo <url>", "Update skills previously installed from another repo. Defaults to the UiPath skills repository.").option("--branch <name>", "Branch to fetch from --repo").option("--force", "Reinstall from a clean state (resets the Claude Code marketplace registration and plugin cache)").examples(SKILLS_UPDATE_EXAMPLES).trackedAction(processContext, async (options) => {
3388
+ const { runSkillsUpdate } = await import("./updateService.skills-4t1s7z45.js");
3389
+ const { resolveSkillSource } = await import("./contentStore-c51xqdn2.js");
3390
+ const { resolveSkillsTargetVersion } = await import("./skillsService-20es18vs.js");
5668
3391
  const local = options.local === true;
5669
3392
  const [err, report] = await catchError((async () => {
5670
3393
  const source = resolveSkillSource(options.repo, options.branch);
@@ -5779,7 +3502,7 @@ var TOOLS_INSTALL_EXAMPLES = [
5779
3502
  }
5780
3503
  ];
5781
3504
  function registerInstallCommand2(toolsCommand, _context, state) {
5782
- const { resolveInstallPath, getCliVersionPrefix: getCliVersionPrefix2 } = state;
3505
+ const { resolveInstallPath, getCliVersionPrefix } = state;
5783
3506
  toolsCommand.command("install").description("Install a tool from registry").argument("<package-name>", "Name of the package to install (optionally with @version)").examples(TOOLS_INSTALL_EXAMPLES).trackedAction(processContext, async (packageArg) => {
5784
3507
  const { name: rawName, version: explicitVersion } = parsePackageSpec(packageArg);
5785
3508
  if (explicitVersion && !isValidSemver(explicitVersion)) {
@@ -5807,7 +3530,7 @@ function registerInstallCommand2(toolsCommand, _context, state) {
5807
3530
  if (explicitVersion) {
5808
3531
  packageSpec = `${packageName}@${explicitVersion}`;
5809
3532
  } else {
5810
- const cliPrefix = getCliVersionPrefix2();
3533
+ const cliPrefix = getCliVersionPrefix();
5811
3534
  const channel = resolveRuntimeChannel();
5812
3535
  const candidate = await toolService.resolveInstallCandidate(packageName, cliPrefix, channel, (failure) => registryFailures.push(failure));
5813
3536
  if (!candidate) {
@@ -5907,7 +3630,7 @@ var TOOLS_SEARCH_EXAMPLES = [
5907
3630
  Data: [
5908
3631
  {
5909
3632
  name: "@uipath/orchestrator-tool",
5910
- latestVersion: "1.2.3",
3633
+ version: "1.2.3",
5911
3634
  description: "Manage UiPath Orchestrator resources from the CLI",
5912
3635
  availableVersions: ["1.2.3", "1.2.2", "1.2.1"]
5913
3636
  }
@@ -5919,6 +3642,17 @@ var TOOLS_SEARCH_EFFECTIVE_LIMIT = Number.MAX_SAFE_INTEGER;
5919
3642
  function registerSearchCommand(toolsCommand, _context) {
5920
3643
  toolsCommand.command("search").description("Search for tools in the configured registry").argument("[query]", "Search query (name or keyword)").examples(TOOLS_SEARCH_EXAMPLES).trackedAction(processContext, async (query) => {
5921
3644
  const [error, results] = await catchError(toolService.search(query));
3645
+ if (isRegistryTlsError(error)) {
3646
+ OutputFormatter.error({
3647
+ Result: RESULTS.Failure,
3648
+ Message: `Tool search failed: the registry's TLS certificate is not trusted (${error.code}).`,
3649
+ Instructions: error.instructions,
3650
+ ErrorCode: "network_error",
3651
+ Retry: "RetryWillNotFix"
3652
+ });
3653
+ processContext.exit(1);
3654
+ return;
3655
+ }
5922
3656
  if (error) {
5923
3657
  OutputFormatter.error({
5924
3658
  Result: RESULTS.Failure,
@@ -6081,7 +3815,7 @@ async function startSpinner(text) {
6081
3815
  if (!getOutputSink().capabilities.isInteractive) {
6082
3816
  return;
6083
3817
  }
6084
- const { default: ora } = await import("./index-m5nwse9v.js");
3818
+ const { default: ora } = await import("./index-cj4v0jct.js");
6085
3819
  return ora({ text }).start();
6086
3820
  }
6087
3821
 
@@ -6133,6 +3867,7 @@ function registerUpdateCommand2(toolsCommand, _context, state) {
6133
3867
  });
6134
3868
  return;
6135
3869
  }
3870
+ const { runToolsUpdate, TOOLS_UPDATE_PHASES } = await import("./updateService.tools-f7tr6kc6.js");
6136
3871
  const spinner = await startSpinner("Updating tools…");
6137
3872
  let report;
6138
3873
  try {
@@ -6331,7 +4066,7 @@ function modelFamily(resolvedModel) {
6331
4066
  return "other";
6332
4067
  }
6333
4068
  async function readPluginSkillsVersion() {
6334
- const fs = getFileSystem();
4069
+ const fs = getFileSystem2();
6335
4070
  const root = fs.env.getenv("CLAUDE_PLUGIN_ROOT");
6336
4071
  if (!root) {
6337
4072
  return "";
@@ -6705,6 +4440,7 @@ function registerUpdateCommand3(program, _context, state) {
6705
4440
  cli: raw.cliCheck !== false
6706
4441
  };
6707
4442
  const [err, report] = await catchError((async () => {
4443
+ const { runUpdate } = await import("./updateService-pq7pkd42.js");
6708
4444
  const isDev = await isDevMode();
6709
4445
  const [locationError, location] = await catchError(state.resolveInstallPath());
6710
4446
  if (locationError && !(locationError instanceof InstallRefusedError)) {
@@ -6782,7 +4518,7 @@ function formatFailureStderr(report, target) {
6782
4518
  }
6783
4519
 
6784
4520
  // src/commands/user.ts
6785
- function instructionsForStatusError2(_) {
4521
+ function instructionsForStatusError(_) {
6786
4522
  return "Failed to determine login status. Login again by running 'uip login' to authenticate.";
6787
4523
  }
6788
4524
  var USER_EXAMPLES = [
@@ -6804,12 +4540,12 @@ var USER_EXAMPLES = [
6804
4540
  ];
6805
4541
  function registerUserCommand(program, context) {
6806
4542
  program.command("user").description("Show information about the currently logged-in user").examples(USER_EXAMPLES).trackedAction(context, async () => {
6807
- const [statusError, status] = await catchError(getLoginStatusAsync());
4543
+ const [statusError, status] = await catchError(getLoginStatusAsync2());
6808
4544
  if (statusError) {
6809
4545
  OutputFormatter.error({
6810
4546
  Result: RESULTS.ConfigError,
6811
4547
  Message: statusError.message,
6812
- Instructions: instructionsForStatusError2(statusError)
4548
+ Instructions: instructionsForStatusError(statusError)
6813
4549
  });
6814
4550
  context.exit(1);
6815
4551
  return;
@@ -6818,18 +4554,18 @@ function registerUserCommand(program, context) {
6818
4554
  OutputFormatter.error({
6819
4555
  Result: RESULTS.AuthenticationError,
6820
4556
  Message: "Not logged in",
6821
- Instructions: instructionsForStatusError2({})
4557
+ Instructions: instructionsForStatusError({})
6822
4558
  });
6823
4559
  context.exit(2);
6824
4560
  return;
6825
4561
  }
6826
4562
  const accessToken = status.accessToken ?? "";
6827
- const [parseError, claims] = await catchError(Promise.resolve().then(() => parseJWT(accessToken)));
4563
+ const [parseError, claims] = await catchError(Promise.resolve().then(() => parseJWT2(accessToken)));
6828
4564
  if (parseError) {
6829
4565
  OutputFormatter.error({
6830
4566
  Result: RESULTS.Failure,
6831
4567
  Message: "Failed to parse access token",
6832
- Instructions: instructionsForStatusError2(parseError)
4568
+ Instructions: instructionsForStatusError(parseError)
6833
4569
  });
6834
4570
  context.exit(1);
6835
4571
  return;
@@ -6853,14 +4589,14 @@ function registerUserCommand(program, context) {
6853
4589
  }
6854
4590
 
6855
4591
  // src/services/installPath.ts
6856
- function createInstallPathResolver(toolsDir, isBrowser2) {
4592
+ function createInstallPathResolver(toolsDir, isBrowser) {
6857
4593
  return async (packageName) => {
6858
- if (isBrowser2) {
4594
+ if (isBrowser) {
6859
4595
  const path = packageName ? `/tools/${packageName.replace(/[/@]/g, "_")}` : "/tools";
6860
4596
  return { path, global: false };
6861
4597
  }
6862
- const { getFileSystem: getFileSystem2 } = await import("./index-ngs0a2he.js");
6863
- const fsLocal = getFileSystem2();
4598
+ const { getFileSystem } = await import("./index-21kns9qg.js");
4599
+ const fsLocal = getFileSystem();
6864
4600
  const { dirname: dirnameFn, join: joinFn } = fsLocal.path;
6865
4601
  const declaration = await getEnvToolsDirsDeclaration();
6866
4602
  if (declaration) {
@@ -6936,7 +4672,7 @@ var DISABLE_VERSION_SYNC_ENV = "UIPATH_CLI_DISABLE_VERSION_SYNC";
6936
4672
  var DISABLE_AUTOINSTALL_ENV = "UIPATH_CLI_DISABLE_AUTOINSTALL";
6937
4673
  var DISABLE_TOOL_LINE_CHECK_ENV = "UIPATH_CLI_DISABLE_TOOL_LINE_CHECK";
6938
4674
  function isTruthyEnv(name) {
6939
- const value = getFileSystem().env.getenv(name);
4675
+ const value = getFileSystem2().env.getenv(name);
6940
4676
  if (!value)
6941
4677
  return false;
6942
4678
  const v = value.trim().toLowerCase();
@@ -6955,7 +4691,7 @@ function backgroundUpdateSkipReason(argv) {
6955
4691
  if (isAutoInstallDisabled()) {
6956
4692
  return `${DISABLE_AUTOINSTALL_ENV} is set`;
6957
4693
  }
6958
- if (isEnvAuthEnabled()) {
4694
+ if (isEnvAuthEnabled2()) {
6959
4695
  return "env-var auth (CI/headless)";
6960
4696
  }
6961
4697
  if (isHelpOrVersionInvocation(argv)) {
@@ -6966,17 +4702,17 @@ function backgroundUpdateSkipReason(argv) {
6966
4702
 
6967
4703
  // src/services/toolFreshness.ts
6968
4704
  class ToolUpdateCheckError extends InstallRefusedError {
6969
- constructor(message) {
6970
- super(message, TOOL_CHECK_INSTRUCTIONS);
4705
+ constructor(message, cause) {
4706
+ super(message, isRegistryTlsError(cause) ? cause.instructions : TOOL_CHECK_INSTRUCTIONS, isRegistryTlsError(cause) ? { errorCode: "network_error", retry: "RetryWillNotFix" } : undefined);
6971
4707
  this.name = "ToolUpdateCheckError";
6972
4708
  }
6973
4709
  }
6974
4710
  var TOOL_CHECK_INSTRUCTIONS = "Check your connection and re-run the command — the check runs again on the next attempt. " + `To skip the daily tool check, set ${DISABLE_VERSION_SYNC_ENV}=1, ` + "or freeze versions with 'uip config set version <major.minor.patch>'.";
6975
4711
  function toolLookupFailedError(toolName, cause) {
6976
- return new ToolUpdateCheckError(`The daily update check for '${toolName}' failed: ${cause.message}`);
4712
+ return new ToolUpdateCheckError(`The daily update check for '${toolName}' failed: ${cause.message}`, cause);
6977
4713
  }
6978
4714
  function toolInstallFailedError(toolName, packageSpec, cause) {
6979
- return new ToolUpdateCheckError(`The daily update check for '${toolName}' could not install ${packageSpec}: ${cause.message}`);
4715
+ return new ToolUpdateCheckError(`The daily update check for '${toolName}' could not install ${packageSpec}: ${cause.message}`, cause);
6980
4716
  }
6981
4717
  async function resolveFreshnessGate() {
6982
4718
  if (await isDevMode()) {
@@ -6994,8 +4730,8 @@ async function isToolCheckedToday(toolName) {
6994
4730
  return state.toolUpdateDates?.[toolName] === todayLocal();
6995
4731
  }
6996
4732
  async function acquireToolCheckLock(toolName) {
6997
- const { getFileSystemAsync: getFileSystemAsync2 } = await import("./index-ngs0a2he.js");
6998
- const fs = await getFileSystemAsync2();
4733
+ const { getFileSystemAsync } = await import("./index-21kns9qg.js");
4734
+ const fs = await getFileSystemAsync();
6999
4735
  if (typeof fs.acquireLock !== "function") {
7000
4736
  return { kind: "unavailable" };
7001
4737
  }
@@ -7413,12 +5149,12 @@ async function resolveUpdateLocation(state, context) {
7413
5149
  return location;
7414
5150
  }
7415
5151
  async function runUpdateEngine(state, location, context, target) {
7416
- const { runUpdate: runUpdate2 } = await import("./updateService-22p6d8dm.js");
5152
+ const { runUpdate } = await import("./updateService-pq7pkd42.js");
7417
5153
  const spinner = await startSpinner(formatUpdateStartMessage(target));
7418
5154
  if (!spinner) {
7419
5155
  writeSyncStatus(context, formatUpdateStartMessage(target));
7420
5156
  }
7421
- const [updErr, report] = await catchError(runUpdate2({
5157
+ const [updErr, report] = await catchError(runUpdate({
7422
5158
  dryRun: false,
7423
5159
  channel: resolveUpdateChannel(),
7424
5160
  sections: { tools: false, skills: true, cli: true },
@@ -7689,7 +5425,7 @@ async function resolveToolsDirectories(context) {
7689
5425
  return { toolsDirs: ["/tools"], toolsDir: "/tools" };
7690
5426
  }
7691
5427
  const currentFilePath = fileURLToPath(import.meta.url);
7692
- const fs = getFileSystem();
5428
+ const fs = getFileSystem2();
7693
5429
  const toolsDirs = await resolveToolsDirs(currentFilePath, fs.env.cwd());
7694
5430
  const toolsDir = toolsDirs[0];
7695
5431
  if (toolsDirs.length > 0) {
@@ -7705,9 +5441,9 @@ async function resolveToolsDirectories(context) {
7705
5441
  if (isInstalledPackage) {
7706
5442
  const execDir = dirname(process.execPath);
7707
5443
  const packageDir = dirname(execDir);
7708
- const fallbackDir2 = dirname(packageDir);
7709
- logger.debug(`Fallback (installed package): ${fallbackDir2}`);
7710
- return { toolsDirs: [fallbackDir2], toolsDir: fallbackDir2 };
5444
+ const fallbackDir = dirname(packageDir);
5445
+ logger.debug(`Fallback (installed package): ${fallbackDir}`);
5446
+ return { toolsDirs: [fallbackDir], toolsDir: fallbackDir };
7711
5447
  }
7712
5448
  const fallbackDir = join(dirname(currentFilePath), "..");
7713
5449
  logger.debug(`Fallback (development mode): ${fallbackDir}`);
@@ -7726,7 +5462,7 @@ async function buildNodeProgram(context) {
7726
5462
  if (shouldPopulateTelemetryInstallContext(context.args)) {
7727
5463
  await populateTelemetryInstallContext();
7728
5464
  }
7729
- const { setActiveAuthProfile, setAuthFileConfig } = await import("./index-7tshyfxx.js");
5465
+ const { setActiveAuthProfile, setAuthFileConfig } = await import("./index-y7d0cth0.js");
7730
5466
  setActiveAuthProfile(profile);
7731
5467
  const [configErr, config] = await catchError(loadConfigAsync());
7732
5468
  if (configErr) {
@@ -7803,7 +5539,7 @@ async function buildNodeProgram(context) {
7803
5539
  return { program, cleanedArgs, updateState, discoveredTools };
7804
5540
  }
7805
5541
  async function runNode(context) {
7806
- return runCliInvocation(() => runNodeInvocation(withRecordedExit(context)));
5542
+ return runCliInvocation(() => runNodeInvocation(context));
7807
5543
  }
7808
5544
  async function runNodeInvocation(context) {
7809
5545
  const built = await buildNodeProgram(context);
@@ -7831,4 +5567,4 @@ async function runNodeInvocation(context) {
7831
5567
 
7832
5568
  export { runNode };
7833
5569
 
7834
- //# debugId=5D6737228DB9A33E64756E2164756E21
5570
+ //# debugId=E0EA5C65D5A997F064756E2164756E21