@uipath/conversational-tool 1.205.0-preview.284 → 1.206.0-preview.282

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.
@@ -1,8 +1,9 @@
1
1
  import {
2
+ __toESM,
2
3
  __commonJS,
3
- __require,
4
- __toESM
5
- } from "./tool-1yh8g550.js";
4
+ __exportCjs,
5
+ __require
6
+ } from "./tool-6an893wm.js";
6
7
 
7
8
  // ../../node_modules/commander/lib/error.js
8
9
  var require_error = __commonJS(function(exports) {
@@ -124,7 +125,7 @@ var require_help = __commonJS(function(exports) {
124
125
  this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
125
126
  }
126
127
  visibleCommands(cmd) {
127
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
128
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
128
129
  const helpCommand = cmd._getHelpCommand();
129
130
  if (helpCommand && !helpCommand._hidden) {
130
131
  visibleCommands.push(helpCommand);
@@ -604,8 +605,8 @@ var require_option = __commonJS(function(exports) {
604
605
  }
605
606
  }
606
607
  function camelcase(str) {
607
- return str.split("-").reduce((str2, word) => {
608
- return str2 + word[0].toUpperCase() + word.slice(1);
608
+ return str.split("-").reduce((str, word) => {
609
+ return str + word[0].toUpperCase() + word.slice(1);
609
610
  });
610
611
  }
611
612
  function splitOptionFlags(flags) {
@@ -1176,44 +1177,44 @@ Expecting one of '${allowedValues.join("', '")}'`);
1176
1177
  });
1177
1178
  return source;
1178
1179
  }
1179
- _prepareUserArgs(argv, parseOptions) {
1180
- if (argv !== undefined && !Array.isArray(argv)) {
1180
+ _prepareUserArgs(argv2, parseOptions) {
1181
+ if (argv2 !== undefined && !Array.isArray(argv2)) {
1181
1182
  throw new Error("first parameter to parse must be array or undefined");
1182
1183
  }
1183
1184
  parseOptions = parseOptions || {};
1184
- if (argv === undefined && parseOptions.from === undefined) {
1185
+ if (argv2 === undefined && parseOptions.from === undefined) {
1185
1186
  if (process2.versions?.electron) {
1186
1187
  parseOptions.from = "electron";
1187
1188
  }
1188
- const execArgv = process2.execArgv ?? [];
1189
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1189
+ const execArgv2 = process2.execArgv ?? [];
1190
+ if (execArgv2.includes("-e") || execArgv2.includes("--eval") || execArgv2.includes("-p") || execArgv2.includes("--print")) {
1190
1191
  parseOptions.from = "eval";
1191
1192
  }
1192
1193
  }
1193
- if (argv === undefined) {
1194
- argv = process2.argv;
1194
+ if (argv2 === undefined) {
1195
+ argv2 = process2.argv;
1195
1196
  }
1196
- this.rawArgs = argv.slice();
1197
+ this.rawArgs = argv2.slice();
1197
1198
  let userArgs;
1198
1199
  switch (parseOptions.from) {
1199
1200
  case undefined:
1200
1201
  case "node":
1201
- this._scriptPath = argv[1];
1202
- userArgs = argv.slice(2);
1202
+ this._scriptPath = argv2[1];
1203
+ userArgs = argv2.slice(2);
1203
1204
  break;
1204
1205
  case "electron":
1205
1206
  if (process2.defaultApp) {
1206
- this._scriptPath = argv[1];
1207
- userArgs = argv.slice(2);
1207
+ this._scriptPath = argv2[1];
1208
+ userArgs = argv2.slice(2);
1208
1209
  } else {
1209
- userArgs = argv.slice(1);
1210
+ userArgs = argv2.slice(1);
1210
1211
  }
1211
1212
  break;
1212
1213
  case "user":
1213
- userArgs = argv.slice(0);
1214
+ userArgs = argv2.slice(0);
1214
1215
  break;
1215
1216
  case "eval":
1216
- userArgs = argv.slice(1);
1217
+ userArgs = argv2.slice(1);
1217
1218
  break;
1218
1219
  default:
1219
1220
  throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
@@ -1736,18 +1737,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
1736
1737
  this.error(message, { code: "commander.missingMandatoryOptionValue" });
1737
1738
  }
1738
1739
  _conflictingOption(option, conflictingOption) {
1739
- const findBestOptionFromValue = (option2) => {
1740
- const optionKey = option2.attributeName();
1740
+ const findBestOptionFromValue = (option) => {
1741
+ const optionKey = option.attributeName();
1741
1742
  const optionValue = this.getOptionValue(optionKey);
1742
1743
  const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1743
1744
  const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1744
1745
  if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1745
1746
  return negativeOption;
1746
1747
  }
1747
- return positiveOption || option2;
1748
+ return positiveOption || option;
1748
1749
  };
1749
- const getErrorMessage = (option2) => {
1750
- const bestOption = findBestOptionFromValue(option2);
1750
+ const getErrorMessage = (option) => {
1751
+ const bestOption = findBestOptionFromValue(option);
1751
1752
  const optionKey = bestOption.attributeName();
1752
1753
  const source = this.getOptionValueSource(optionKey);
1753
1754
  if (source === "env") {
@@ -1901,10 +1902,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
1901
1902
  this._name = path.basename(filename, path.extname(filename));
1902
1903
  return this;
1903
1904
  }
1904
- executableDir(path2) {
1905
- if (path2 === undefined)
1905
+ executableDir(path) {
1906
+ if (path === undefined)
1906
1907
  return this._executableDir;
1907
- this._executableDir = path2;
1908
+ this._executableDir = path;
1908
1909
  return this;
1909
1910
  }
1910
1911
  helpInformation(contextOptions) {
@@ -2001,11 +2002,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2001
2002
  }
2002
2003
  help(contextOptions) {
2003
2004
  this.outputHelp(contextOptions);
2004
- let exitCode = Number(process2.exitCode ?? 0);
2005
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2006
- exitCode = 1;
2005
+ let exitCode2 = Number(process2.exitCode ?? 0);
2006
+ if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2007
+ exitCode2 = 1;
2007
2008
  }
2008
- this._exit(exitCode, "commander.help", "(outputHelp)");
2009
+ this._exit(exitCode2, "commander.help", "(outputHelp)");
2009
2010
  }
2010
2011
  addHelpText(position, text) {
2011
2012
  const allowedValues = ["beforeAll", "before", "after", "afterAll"];
@@ -2076,32 +2077,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
2076
2077
  exports.Command = Command;
2077
2078
  exports.useColor = useColor;
2078
2079
  });
2079
-
2080
- // ../../node_modules/commander/index.js
2081
- var require_commander = __commonJS(function(exports) {
2082
- var { Argument } = require_argument();
2083
- var { Command } = require_command();
2084
- var { CommanderError, InvalidArgumentError } = require_error();
2085
- var { Help } = require_help();
2086
- var { Option } = require_option();
2087
- exports.program = new Command;
2088
- exports.createCommand = (name) => new Command(name);
2089
- exports.createOption = (flags, description) => new Option(flags, description);
2090
- exports.createArgument = (name, description) => new Argument(name, description);
2091
- exports.Command = Command;
2092
- exports.Option = Option;
2093
- exports.Argument = Argument;
2094
- exports.Help = Help;
2095
- exports.CommanderError = CommanderError;
2096
- exports.InvalidArgumentError = InvalidArgumentError;
2097
- exports.InvalidOptionArgumentError = InvalidArgumentError;
2098
- });
2099
2080
  // package.json
2100
2081
  var package_default = {
2101
2082
  name: "@uipath/conversational-tool",
2102
2083
  author: "UiPath",
2103
2084
  license: "SEE LICENSE IN LICENSE.txt",
2104
- version: "1.205.0-preview.284",
2085
+ version: "1.206.0-preview.282",
2105
2086
  description: "Handle conversations with deployed UiPath conversational processes.",
2106
2087
  publishConfig: {
2107
2088
  registry: "https://npm.pkg.github.com/"
@@ -2119,6 +2100,7 @@ var package_default = {
2119
2100
  ],
2120
2101
  scripts: {
2121
2102
  build: "bun ../../tools/build-tool.ts",
2103
+ typecheck: "tsc --noEmit",
2122
2104
  package: "bun run build && bun pm pack",
2123
2105
  test: "vitest run",
2124
2106
  "test:coverage": "vitest run --coverage",
@@ -2136,58 +2118,6 @@ var package_default = {
2136
2118
  }
2137
2119
  };
2138
2120
 
2139
- // ../../node_modules/commander/esm.mjs
2140
- var import__ = __toESM(require_commander(), 1);
2141
- var {
2142
- program,
2143
- createCommand,
2144
- createArgument,
2145
- createOption,
2146
- CommanderError,
2147
- InvalidArgumentError,
2148
- InvalidOptionArgumentError,
2149
- Command,
2150
- Argument,
2151
- Option,
2152
- Help
2153
- } = import__.default;
2154
-
2155
- // ../common/src/singleton.ts
2156
- var PREFIX = "@uipath/common/";
2157
- var _g = globalThis;
2158
- function singleton(ctorOrName) {
2159
- const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
2160
- const key = Symbol.for(PREFIX + name);
2161
- return {
2162
- get(fallback) {
2163
- return _g[key] ?? fallback;
2164
- },
2165
- set(value) {
2166
- _g[key] = value;
2167
- },
2168
- clear() {
2169
- delete _g[key];
2170
- },
2171
- getOrInit(factory, guard) {
2172
- const existing = _g[key];
2173
- if (existing != null && typeof existing === "object") {
2174
- if (!guard || guard(existing)) {
2175
- return existing;
2176
- }
2177
- }
2178
- const instance = factory();
2179
- _g[key] = instance;
2180
- return instance;
2181
- }
2182
- };
2183
- }
2184
-
2185
- // ../common/src/telemetry/global-telemetry-properties.ts
2186
- var telemetryPropsSlot = singleton("TelemetryDefaultProps");
2187
- function getGlobalTelemetryProperties() {
2188
- return telemetryPropsSlot.get();
2189
- }
2190
-
2191
2121
  // ../common/src/telemetry/telemetry-dimensions.ts
2192
2122
  var BaseDimensions = {
2193
2123
  ApplicationName: "ApplicationName",
@@ -2223,6 +2153,21 @@ var CommandDimensions = {
2223
2153
  ProductArea: "ProductArea",
2224
2154
  Mode: "Mode"
2225
2155
  };
2156
+ var ProjectDimensions = {
2157
+ ProjectKey: "ProjectKey",
2158
+ ProjectType: "ProjectType",
2159
+ ProjectIdentityStatus: "ProjectIdentityStatus",
2160
+ SolutionKey: "SolutionKey",
2161
+ SolutionProjectKey: "SolutionProjectKey",
2162
+ SolutionIdentityStatus: "SolutionIdentityStatus",
2163
+ PreviousSolutionKey: "PreviousSolutionKey"
2164
+ };
2165
+ var GUID_KEY_DIMENSIONS = new Set([
2166
+ ProjectDimensions.ProjectKey,
2167
+ ProjectDimensions.SolutionKey,
2168
+ ProjectDimensions.SolutionProjectKey,
2169
+ ProjectDimensions.PreviousSolutionKey
2170
+ ]);
2226
2171
  var ShipDimensions = {
2227
2172
  ShipKind: "ShipKind",
2228
2173
  Target: "Target",
@@ -2291,6 +2236,7 @@ var RESERVED_DIMENSION_NAMES = new Set([
2291
2236
  ...Object.values(BaseDimensions),
2292
2237
  ...Object.values(CommandDimensions),
2293
2238
  ...Object.values(ShipDimensions),
2239
+ ...Object.values(ProjectDimensions),
2294
2240
  ...Object.values(ErrorDimensions),
2295
2241
  ...Object.values(AuthDimensions),
2296
2242
  ...Object.values(SkillsDimensions),
@@ -2316,7 +2262,8 @@ var CURATED_DIMENSIONS = new Set([
2316
2262
  BaseDimensions.SessionIdSource,
2317
2263
  BaseDimensions.SessionId,
2318
2264
  ...Object.values(CommandDimensions),
2319
- ...Object.values(ShipDimensions)
2265
+ ...Object.values(ShipDimensions),
2266
+ ...Object.values(ProjectDimensions)
2320
2267
  ]);
2321
2268
  function lowercaseIdDimensionValues(properties) {
2322
2269
  let changed = false;
@@ -2337,837 +2284,721 @@ function lowercaseIdDimensionValues(properties) {
2337
2284
  return changed ? result : properties;
2338
2285
  }
2339
2286
 
2340
- // ../common/src/sdk-user-agent.ts
2341
- var USER_AGENT_HEADER = "User-Agent";
2342
- var AGENT_PROPERTY = BaseDimensions.Agent;
2343
- var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
2344
- function splitUserAgentTokens(value) {
2345
- return value?.trim().split(/\s+/).filter(Boolean) ?? [];
2287
+ // ../common/src/telemetry/project-identity.ts
2288
+ function projectKey(id) {
2289
+ if (typeof id !== "string")
2290
+ return;
2291
+ const key = id.trim().toLowerCase().replaceAll("-", "");
2292
+ return /^[0-9a-f]{32}$/.test(key) ? key : undefined;
2346
2293
  }
2347
- function appendUserAgentToken(value, userAgent) {
2348
- const tokens = splitUserAgentTokens(value);
2349
- const seen = new Set(tokens);
2350
- for (const token of splitUserAgentTokens(userAgent)) {
2351
- if (!seen.has(token)) {
2352
- tokens.push(token);
2353
- seen.add(token);
2354
- }
2294
+ function projectIdentityProperties(identity) {
2295
+ const key = identity.id ? projectKey(identity.id) : undefined;
2296
+ return {
2297
+ [ProjectDimensions.ProjectIdentityStatus]: identity.status === "resolved" && !key ? "invalid" : identity.status,
2298
+ [ProjectDimensions.ProjectType]: identity.projectType,
2299
+ ...identity.status === "resolved" && key ? {
2300
+ [ProjectDimensions.ProjectKey]: key
2301
+ } : {}
2302
+ };
2303
+ }
2304
+ var PROJECT_IDENTITY_LOOKUP_BUDGET_MS = 1000;
2305
+ async function withinProjectIdentityBudget(work, onTimeout) {
2306
+ work.catch(() => {
2307
+ return;
2308
+ });
2309
+ let timer;
2310
+ const expired = new Promise((resolve) => {
2311
+ timer = setTimeout(() => {
2312
+ onTimeout?.();
2313
+ resolve(undefined);
2314
+ }, PROJECT_IDENTITY_LOOKUP_BUDGET_MS);
2315
+ });
2316
+ try {
2317
+ return await Promise.race([work, expired]);
2318
+ } finally {
2319
+ clearTimeout(timer);
2355
2320
  }
2356
- return tokens.join(" ");
2357
2321
  }
2358
- function getEffectiveUserAgent(userAgent) {
2359
- return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
2322
+
2323
+ // ../common/src/telemetry/pseudonymize.ts
2324
+ var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
2325
+ var PSEUDONYM_HEX_LENGTH = 32;
2326
+ var SHA256_K = new Uint32Array([
2327
+ 1116352408,
2328
+ 1899447441,
2329
+ 3049323471,
2330
+ 3921009573,
2331
+ 961987163,
2332
+ 1508970993,
2333
+ 2453635748,
2334
+ 2870763221,
2335
+ 3624381080,
2336
+ 310598401,
2337
+ 607225278,
2338
+ 1426881987,
2339
+ 1925078388,
2340
+ 2162078206,
2341
+ 2614888103,
2342
+ 3248222580,
2343
+ 3835390401,
2344
+ 4022224774,
2345
+ 264347078,
2346
+ 604807628,
2347
+ 770255983,
2348
+ 1249150122,
2349
+ 1555081692,
2350
+ 1996064986,
2351
+ 2554220882,
2352
+ 2821834349,
2353
+ 2952996808,
2354
+ 3210313671,
2355
+ 3336571891,
2356
+ 3584528711,
2357
+ 113926993,
2358
+ 338241895,
2359
+ 666307205,
2360
+ 773529912,
2361
+ 1294757372,
2362
+ 1396182291,
2363
+ 1695183700,
2364
+ 1986661051,
2365
+ 2177026350,
2366
+ 2456956037,
2367
+ 2730485921,
2368
+ 2820302411,
2369
+ 3259730800,
2370
+ 3345764771,
2371
+ 3516065817,
2372
+ 3600352804,
2373
+ 4094571909,
2374
+ 275423344,
2375
+ 430227734,
2376
+ 506948616,
2377
+ 659060556,
2378
+ 883997877,
2379
+ 958139571,
2380
+ 1322822218,
2381
+ 1537002063,
2382
+ 1747873779,
2383
+ 1955562222,
2384
+ 2024104815,
2385
+ 2227730452,
2386
+ 2361852424,
2387
+ 2428436474,
2388
+ 2756734187,
2389
+ 3204031479,
2390
+ 3329325298
2391
+ ]);
2392
+ var SHA256_INITIAL_STATE = new Uint32Array([
2393
+ 1779033703,
2394
+ 3144134277,
2395
+ 1013904242,
2396
+ 2773480762,
2397
+ 1359893119,
2398
+ 2600822924,
2399
+ 528734635,
2400
+ 1541459225
2401
+ ]);
2402
+ function rotr(value, bits) {
2403
+ return (value >>> bits | value << 32 - bits) >>> 0;
2360
2404
  }
2361
- function getHeaderName(headers, headerName) {
2362
- return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
2405
+ function sha256Hex(input) {
2406
+ const bytes = new TextEncoder().encode(input);
2407
+ const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
2408
+ const buffer = new Uint8Array(paddedLength);
2409
+ buffer.set(bytes);
2410
+ buffer[bytes.length] = 128;
2411
+ const view = new DataView(buffer.buffer);
2412
+ const bitLength = bytes.length * 8;
2413
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
2414
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
2415
+ const state = SHA256_INITIAL_STATE.slice();
2416
+ const schedule = new Uint32Array(64);
2417
+ for (let offset = 0;offset < paddedLength; offset += 64) {
2418
+ for (let i = 0;i < 16; i++) {
2419
+ schedule[i] = view.getUint32(offset + i * 4);
2420
+ }
2421
+ for (let i = 16;i < 64; i++) {
2422
+ const x = schedule[i - 15];
2423
+ const y = schedule[i - 2];
2424
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
2425
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
2426
+ schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
2427
+ }
2428
+ let a = state[0];
2429
+ let b = state[1];
2430
+ let c = state[2];
2431
+ let d = state[3];
2432
+ let e = state[4];
2433
+ let f = state[5];
2434
+ let g = state[6];
2435
+ let h = state[7];
2436
+ for (let i = 0;i < 64; i++) {
2437
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
2438
+ const ch = (e & f ^ ~e & g) >>> 0;
2439
+ const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
2440
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
2441
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
2442
+ const temp2 = s0 + maj >>> 0;
2443
+ h = g;
2444
+ g = f;
2445
+ f = e;
2446
+ e = d + temp1 >>> 0;
2447
+ d = c;
2448
+ c = b;
2449
+ b = a;
2450
+ a = temp1 + temp2 >>> 0;
2451
+ }
2452
+ state[0] = state[0] + a >>> 0;
2453
+ state[1] = state[1] + b >>> 0;
2454
+ state[2] = state[2] + c >>> 0;
2455
+ state[3] = state[3] + d >>> 0;
2456
+ state[4] = state[4] + e >>> 0;
2457
+ state[5] = state[5] + f >>> 0;
2458
+ state[6] = state[6] + g >>> 0;
2459
+ state[7] = state[7] + h >>> 0;
2460
+ }
2461
+ let hex = "";
2462
+ for (const word of state) {
2463
+ hex += word.toString(16).padStart(8, "0");
2464
+ }
2465
+ return hex;
2363
2466
  }
2364
- function getSdkUserAgentToken(pkg) {
2365
- const packageName = pkg.name.replace(/^@uipath\//, "");
2366
- return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
2467
+ function resolveSha256Hex() {
2468
+ try {
2469
+ const nodeCrypto = __require("node:crypto");
2470
+ const createHash = nodeCrypto?.createHash;
2471
+ if (typeof createHash !== "function") {
2472
+ return sha256Hex;
2473
+ }
2474
+ const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
2475
+ return native("abc") === sha256Hex("abc") ? native : sha256Hex;
2476
+ } catch {
2477
+ return sha256Hex;
2478
+ }
2367
2479
  }
2368
- function addSdkUserAgentHeader(headers, userAgent) {
2369
- const result = { ...headers ?? {} };
2370
- const headerName = getHeaderName(result, USER_AGENT_HEADER);
2371
- result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
2372
- return result;
2480
+ var cachedSha256Hex;
2481
+ function digest(input) {
2482
+ cachedSha256Hex ??= resolveSha256Hex();
2483
+ return cachedSha256Hex(input);
2484
+ }
2485
+ function pseudonymize(input) {
2486
+ return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
2373
2487
  }
2374
2488
 
2375
- // ../filesystem/src/node.ts
2376
- import { randomUUID } from "node:crypto";
2377
- import { existsSync } from "node:fs";
2378
- import * as fs from "node:fs/promises";
2379
- import * as os from "node:os";
2380
- import * as path from "node:path";
2381
- var LOCK_HEARTBEAT_MS = 5000;
2382
- var LOCK_STALE_MS = 15000;
2383
- var LOCK_MAX_WAIT_MS = 20000;
2384
- var LOCK_MAX_HOLD_MS = 60000;
2385
- var LOCK_RETRY_MIN_MS = 100;
2386
- var LOCK_RETRY_JITTER_MS = 200;
2387
-
2388
- class NodeFileSystem {
2389
- path = {
2390
- join: path.join,
2391
- resolve: path.resolve,
2392
- relative: path.relative,
2393
- dirname: path.dirname,
2394
- isAbsolute: path.isAbsolute,
2395
- basename: path.basename
2396
- };
2397
- env = {
2398
- cwd: process.cwd,
2399
- homedir: os.homedir,
2400
- tmpdir: os.tmpdir,
2401
- getenv: (key) => process.env[key]
2402
- };
2403
- utils = {
2404
- open: async (url) => {
2405
- const { default: open } = await import("./index-h8cph72k.js");
2406
- await open(url);
2489
+ // ../common/src/singleton.ts
2490
+ var PREFIX = "@uipath/common/";
2491
+ var _g = globalThis;
2492
+ function singleton(ctorOrName) {
2493
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
2494
+ const key = Symbol.for(PREFIX + name);
2495
+ return {
2496
+ get(fallback) {
2497
+ return _g[key] ?? fallback;
2498
+ },
2499
+ set(value) {
2500
+ _g[key] = value;
2501
+ },
2502
+ clear() {
2503
+ delete _g[key];
2504
+ },
2505
+ getOrInit(factory, guard) {
2506
+ const existing = _g[key];
2507
+ if (existing != null && typeof existing === "object") {
2508
+ if (!guard || guard(existing)) {
2509
+ return existing;
2510
+ }
2511
+ }
2512
+ const instance = factory();
2513
+ _g[key] = instance;
2514
+ return instance;
2407
2515
  }
2408
2516
  };
2409
- async readFile(path2, options) {
2410
- try {
2411
- if (options) {
2412
- return await fs.readFile(path2, "utf-8");
2517
+ }
2518
+
2519
+ // ../common/src/telemetry/supplied-values.ts
2520
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
2521
+ function activeEntries() {
2522
+ const existing = suppliedValuesSlot.get();
2523
+ return Array.isArray(existing) ? existing : [];
2524
+ }
2525
+ var MIN_SCRUBBABLE_LENGTH = 4;
2526
+ function recordSuppliedArgumentValues(values) {
2527
+ const flat = [];
2528
+ const push = (value) => {
2529
+ if (Array.isArray(value)) {
2530
+ for (const item of value) {
2531
+ push(item);
2413
2532
  }
2414
- return await fs.readFile(path2);
2415
- } catch (error) {
2416
- if (this.isEnoent(error))
2417
- return null;
2418
- throw error;
2419
- }
2420
- }
2421
- async writeFile(filePath, data) {
2422
- const dir = path.dirname(filePath);
2423
- if (dir) {
2424
- await fs.mkdir(dir, { recursive: true });
2533
+ return;
2425
2534
  }
2426
- await fs.writeFile(filePath, data);
2427
- }
2428
- async appendFile(filePath, data) {
2429
- const dir = path.dirname(filePath);
2430
- if (dir) {
2431
- await fs.mkdir(dir, { recursive: true });
2535
+ if (typeof value === "string" && value.length >= MIN_SCRUBBABLE_LENGTH) {
2536
+ flat.push(value);
2432
2537
  }
2433
- await fs.appendFile(filePath, data);
2434
- }
2435
- async readdir(dirPath) {
2436
- try {
2437
- return await fs.readdir(dirPath);
2438
- } catch (error) {
2439
- if (this.isEnoent(error))
2440
- return [];
2441
- throw error;
2538
+ };
2539
+ push(values);
2540
+ const entry = { values: flat };
2541
+ suppliedValuesSlot.set([...activeEntries(), entry]);
2542
+ return entry;
2543
+ }
2544
+ function releaseSuppliedArgumentValues(entry) {
2545
+ suppliedValuesSlot.set(activeEntries().filter((held) => held !== entry));
2546
+ }
2547
+ function getSuppliedArgumentValues() {
2548
+ const all = new Set;
2549
+ for (const entry of activeEntries()) {
2550
+ for (const value of entry.values) {
2551
+ all.add(value);
2442
2552
  }
2443
2553
  }
2444
- async stat(filePath) {
2445
- try {
2446
- const stats = await fs.stat(filePath);
2447
- return {
2448
- isFile: () => stats.isFile(),
2449
- isDirectory: () => stats.isDirectory(),
2450
- size: stats.size,
2451
- mtimeMs: stats.mtimeMs
2452
- };
2453
- } catch (error) {
2454
- if (this.isEnoent(error))
2455
- return null;
2456
- throw error;
2554
+ return [...all].sort((a, b) => b.length - a.length);
2555
+ }
2556
+
2557
+ // ../common/src/telemetry/pii-redactor.ts
2558
+ var REDACTED = "[REDACTED]";
2559
+ var MAX_VALUE_LENGTH = 280;
2560
+ var MAX_STACK_LENGTH = 4096;
2561
+ var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
2562
+ function truncate(value, maxLength) {
2563
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
2564
+ }
2565
+ var SENSITIVE_NAME_TOKENS = new Set([
2566
+ "token",
2567
+ "tokens",
2568
+ "secret",
2569
+ "secrets",
2570
+ "password",
2571
+ "passwords",
2572
+ "pwd",
2573
+ "credential",
2574
+ "credentials",
2575
+ "auth",
2576
+ "authentication",
2577
+ "authorization",
2578
+ "authority",
2579
+ "cert",
2580
+ "certificate",
2581
+ "certificates"
2582
+ ]);
2583
+ var SENSITIVE_KEY_PREFIXES = new Set([
2584
+ "api",
2585
+ "access",
2586
+ "client",
2587
+ "private",
2588
+ "public",
2589
+ "signing",
2590
+ "encryption",
2591
+ "session",
2592
+ "master",
2593
+ "shared",
2594
+ "root",
2595
+ "ssh",
2596
+ "rsa",
2597
+ "aes",
2598
+ "hmac",
2599
+ "oauth"
2600
+ ]);
2601
+ var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
2602
+ var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
2603
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
2604
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
2605
+ var PADDED_BASE64_PATTERN = /(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
2606
+ var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
2607
+ var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
2608
+ var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
2609
+ var HOST_PORT_PATTERN = /(?<![/@.\w-])(?!\d+\.\d+\.\d+\.\d+:)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+:\d{1,5}\b/g;
2610
+ var SOURCE_FILE_EXTENSIONS = new Set([
2611
+ "ts",
2612
+ "tsx",
2613
+ "js",
2614
+ "jsx",
2615
+ "mjs",
2616
+ "cjs",
2617
+ "cts",
2618
+ "mts",
2619
+ "py",
2620
+ "cs",
2621
+ "java",
2622
+ "go",
2623
+ "rs",
2624
+ "rb",
2625
+ "php",
2626
+ "sh",
2627
+ "ps1",
2628
+ "json",
2629
+ "jsonc",
2630
+ "yaml",
2631
+ "yml",
2632
+ "xml",
2633
+ "xaml",
2634
+ "md",
2635
+ "txt",
2636
+ "log",
2637
+ "css",
2638
+ "html",
2639
+ "htm",
2640
+ "csproj",
2641
+ "nuspec",
2642
+ "sql"
2643
+ ]);
2644
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
2645
+ var QUOTED_LITERAL_MAX_SPAN = 200;
2646
+ var QUOTED_LITERAL_PATTERN = new RegExp([
2647
+ `(?<![A-Za-z0-9])'(?:[^\\
2648
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
2649
+ `(?<![A-Za-z0-9])"(?:[^\\
2650
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
2651
+ ].join("|"), "g");
2652
+ var JSON_BODY_PATTERN = /[{[][^{}[\]:,]*[:,][^{}[\]]*[\]}]/g;
2653
+ var COLLAPSED_BODY = "{…}";
2654
+ var COLLAPSED_BODY_MARKER = "\x01body\x01";
2655
+ var MAX_BODY_NESTING = 8;
2656
+ function collapseJsonBodies(text) {
2657
+ let out = text;
2658
+ for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
2659
+ const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
2660
+ if (next === out) {
2661
+ break;
2457
2662
  }
2663
+ out = next;
2458
2664
  }
2459
- async exists(filePath) {
2460
- return existsSync(filePath);
2461
- }
2462
- async mkdir(dirPath) {
2463
- await fs.mkdir(dirPath, { recursive: true });
2665
+ return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
2666
+ }
2667
+ var TRAILING_PROSE_PUNCT = `.,;:!?)]}>'"`;
2668
+ function peelTrailingPunctuation(match) {
2669
+ let end = match.length;
2670
+ while (end > 0 && TRAILING_PROSE_PUNCT.includes(match[end - 1])) {
2671
+ end -= 1;
2464
2672
  }
2465
- async acquireLock(lockPath) {
2466
- const canonicalPath = await this.canonicalizeLockTarget(lockPath);
2467
- const lockFile = `${canonicalPath}.lock`;
2468
- const ownerId = randomUUID();
2469
- const start = Date.now();
2470
- while (true) {
2471
- try {
2472
- await fs.writeFile(lockFile, ownerId, { flag: "wx" });
2473
- return this.createLockRelease(lockFile, ownerId);
2474
- } catch (error) {
2475
- if (!this.hasErrnoCode(error, "EEXIST")) {
2476
- throw error;
2477
- }
2478
- const stats = await fs.stat(lockFile).catch(() => null);
2479
- if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
2480
- const reclaimed = await fs.rm(lockFile, { force: true }).then(() => true).catch(() => false);
2481
- if (reclaimed)
2482
- continue;
2483
- }
2484
- if (Date.now() - start > LOCK_MAX_WAIT_MS) {
2485
- throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
2486
- }
2487
- await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
2488
- }
2489
- }
2490
- }
2491
- async canonicalizeLockTarget(lockPath) {
2492
- const absolute = path.resolve(lockPath);
2493
- const fullReal = await fs.realpath(absolute).catch(() => null);
2494
- if (fullReal)
2495
- return fullReal;
2496
- const parent = path.dirname(absolute);
2497
- const base = path.basename(absolute);
2498
- const canonicalParent = await fs.realpath(parent).catch(() => parent);
2499
- return path.join(canonicalParent, base);
2673
+ return [match.slice(0, end), match.slice(end)];
2674
+ }
2675
+ function redactUrl(raw) {
2676
+ try {
2677
+ const url = new URL(raw);
2678
+ return `${url.protocol}//${url.host}`;
2679
+ } catch {
2680
+ return `url#${pseudonymize(raw)}`;
2500
2681
  }
2501
- createLockRelease(lockFile, ownerId) {
2502
- const heartbeatStart = Date.now();
2503
- let heartbeatTimer;
2504
- let stopped = false;
2505
- const stopHeartbeat = () => {
2506
- stopped = true;
2507
- if (heartbeatTimer)
2508
- clearTimeout(heartbeatTimer);
2509
- };
2510
- const scheduleNextHeartbeat = () => {
2511
- if (stopped)
2512
- return;
2513
- if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
2514
- stopped = true;
2515
- return;
2516
- }
2517
- heartbeatTimer = setTimeout(() => {
2518
- runHeartbeat();
2519
- }, LOCK_HEARTBEAT_MS);
2520
- heartbeatTimer.unref?.();
2521
- };
2522
- const runHeartbeat = async () => {
2523
- if (stopped)
2524
- return;
2525
- const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2526
- if (stopped)
2527
- return;
2528
- if (current !== ownerId) {
2529
- stopped = true;
2530
- return;
2531
- }
2532
- const now = Date.now() / 1000;
2533
- await fs.utimes(lockFile, now, now).catch(() => {});
2534
- scheduleNextHeartbeat();
2535
- };
2536
- scheduleNextHeartbeat();
2537
- let released = false;
2538
- return async () => {
2539
- if (released)
2540
- return;
2541
- released = true;
2542
- stopHeartbeat();
2543
- const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2544
- if (current === ownerId) {
2545
- await fs.rm(lockFile, { force: true });
2546
- }
2547
- };
2682
+ }
2683
+ function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
2684
+ let out = truncate(value, MAX_SCAN_LENGTH);
2685
+ out = out.replace(JWT_PATTERN, () => REDACTED);
2686
+ out = out.replace(URL_PATTERN, (match) => {
2687
+ const [core, trailing] = peelTrailingPunctuation(match);
2688
+ return `${redactUrl(core)}${trailing}`;
2689
+ });
2690
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
2691
+ out = out.replace(UNC_PATH_PATTERN, (_match, before, path) => {
2692
+ const [core, trailing] = peelTrailingPunctuation(path);
2693
+ return `${before}unc#${pseudonymize(core)}${trailing}`;
2694
+ });
2695
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
2696
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
2697
+ out = out.replace(HOST_PORT_PATTERN, (match) => {
2698
+ const split = match.lastIndexOf(":");
2699
+ const host = match.slice(0, split);
2700
+ const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
2701
+ if (SOURCE_FILE_EXTENSIONS.has(extension)) {
2702
+ return match;
2703
+ }
2704
+ return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
2705
+ });
2706
+ out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
2707
+ out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
2708
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
2709
+ return truncate(out, maxLength);
2710
+ }
2711
+ function redactSpanName(name) {
2712
+ return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
2713
+ }
2714
+ var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
2715
+ function redactHttpDependencyName(name) {
2716
+ const parts = HTTP_DEPENDENCY_NAME.exec(name);
2717
+ if (!parts) {
2718
+ return redactMessage(name);
2548
2719
  }
2549
- async rm(filePath) {
2550
- await fs.rm(filePath, { recursive: true, force: true });
2720
+ return `${parts[1]} ${redactMessage(parts[2])}`;
2721
+ }
2722
+ function redactMessage(value) {
2723
+ let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
2724
+ for (const supplied of getSuppliedArgumentValues()) {
2725
+ out = out.split(supplied).join(REDACTED);
2551
2726
  }
2552
- async rename(oldPath, newPath) {
2553
- await fs.rename(oldPath, newPath);
2727
+ return redactValueDetectors(out);
2728
+ }
2729
+ var MESSAGE_NAMES = new Set([
2730
+ "message",
2731
+ "errormessage",
2732
+ "errmessage",
2733
+ "error_message",
2734
+ "msg",
2735
+ "detail",
2736
+ "details",
2737
+ "reason",
2738
+ "instructions",
2739
+ "warning"
2740
+ ]);
2741
+ function isFreeFormValue(name, value) {
2742
+ return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
2743
+ }
2744
+ function redactError(error) {
2745
+ const safe = new Error(redactMessage(error.message ?? ""));
2746
+ safe.name = error.name;
2747
+ safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
2748
+ return safe;
2749
+ }
2750
+ function redactStack(stack) {
2751
+ const bounded = truncate(stack, MAX_STACK_LENGTH);
2752
+ const firstBreak = bounded.indexOf(`
2753
+ `);
2754
+ if (firstBreak === -1) {
2755
+ return redactMessage(bounded);
2554
2756
  }
2555
- async isSymbolicLink(filePath) {
2556
- try {
2557
- return (await fs.lstat(filePath)).isSymbolicLink();
2558
- } catch (error) {
2559
- if (this.isEnoent(error) || this.hasErrnoCode(error, "ENOTDIR")) {
2560
- return false;
2757
+ return `${redactMessage(bounded.slice(0, firstBreak))}
2758
+ ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
2759
+ }
2760
+ function nameTokens(name) {
2761
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s._-]+/).map((t) => t.toLowerCase()).filter(Boolean);
2762
+ }
2763
+ function isSensitiveName(name) {
2764
+ const tokens = nameTokens(name);
2765
+ for (let i = 0;i < tokens.length; i++) {
2766
+ const token = tokens[i];
2767
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
2768
+ return true;
2769
+ }
2770
+ if (token === "key" || token === "keys") {
2771
+ const prev = tokens[i - 1];
2772
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
2773
+ return true;
2561
2774
  }
2562
- throw error;
2563
2775
  }
2564
2776
  }
2565
- async realpath(filePath) {
2566
- try {
2567
- return await fs.realpath(filePath);
2568
- } catch (error) {
2569
- if (this.isEnoent(error))
2570
- return filePath;
2571
- throw error;
2572
- }
2777
+ return false;
2778
+ }
2779
+ function redactProperty(name, value) {
2780
+ if (value === undefined || value === null) {
2781
+ return;
2573
2782
  }
2574
- async getTempDir() {
2575
- return await fs.mkdtemp(path.join(os.tmpdir(), "uipath-fs-"));
2783
+ if (isSensitiveName(name)) {
2784
+ return REDACTED;
2576
2785
  }
2577
- async copyDirectory(sourcePath, destPath) {
2578
- const sourceStats = await this.stat(sourcePath);
2579
- if (!sourceStats) {
2580
- throw new Error(`Source directory does not exist: ${sourcePath}`);
2581
- }
2582
- if (!sourceStats.isDirectory()) {
2583
- throw new Error(`Source path is not a directory: ${sourcePath}`);
2584
- }
2585
- await this.mkdir(destPath);
2586
- const entries = await this.readdir(sourcePath);
2587
- for (const entry of entries) {
2588
- const srcEntry = path.join(sourcePath, entry);
2589
- const destEntry = path.join(destPath, entry);
2590
- const entryStats = await this.stat(srcEntry);
2591
- if (!entryStats)
2592
- continue;
2593
- if (entryStats.isDirectory()) {
2594
- await this.copyDirectory(srcEntry, destEntry);
2595
- } else if (entryStats.isFile()) {
2596
- const content = await this.readFile(srcEntry);
2597
- if (content !== null) {
2598
- await this.writeFile(destEntry, content);
2599
- }
2600
- }
2601
- }
2786
+ if (GUID_KEY_DIMENSIONS.has(name))
2787
+ return projectKey(value);
2788
+ if (typeof value === "boolean" || typeof value === "number") {
2789
+ return value;
2602
2790
  }
2603
- isEnoent(error) {
2604
- return this.hasErrnoCode(error, "ENOENT");
2791
+ if (typeof value !== "string") {
2792
+ return "[OBJECT]";
2605
2793
  }
2606
- hasErrnoCode(error, code) {
2607
- return typeof error === "object" && error !== null && "code" in error && error.code === code;
2794
+ return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
2795
+ }
2796
+ function redactProperties(properties) {
2797
+ const out = {};
2798
+ for (const [name, value] of Object.entries(properties)) {
2799
+ const redacted = redactProperty(name, value);
2800
+ if (redacted !== undefined) {
2801
+ out[name] = redacted;
2802
+ }
2608
2803
  }
2804
+ return out;
2609
2805
  }
2610
2806
 
2611
- // ../filesystem/src/index.ts
2612
- var fsInstance = new NodeFileSystem;
2613
- var getFileSystem = () => fsInstance;
2614
-
2615
- // ../common/src/telemetry/pseudonymize.ts
2616
- var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
2617
- var PSEUDONYM_HEX_LENGTH = 32;
2618
- var SHA256_K = new Uint32Array([
2619
- 1116352408,
2620
- 1899447441,
2621
- 3049323471,
2622
- 3921009573,
2623
- 961987163,
2624
- 1508970993,
2625
- 2453635748,
2626
- 2870763221,
2627
- 3624381080,
2628
- 310598401,
2629
- 607225278,
2630
- 1426881987,
2631
- 1925078388,
2632
- 2162078206,
2633
- 2614888103,
2634
- 3248222580,
2635
- 3835390401,
2636
- 4022224774,
2637
- 264347078,
2638
- 604807628,
2639
- 770255983,
2640
- 1249150122,
2641
- 1555081692,
2642
- 1996064986,
2643
- 2554220882,
2644
- 2821834349,
2645
- 2952996808,
2646
- 3210313671,
2647
- 3336571891,
2648
- 3584528711,
2649
- 113926993,
2650
- 338241895,
2651
- 666307205,
2652
- 773529912,
2653
- 1294757372,
2654
- 1396182291,
2655
- 1695183700,
2656
- 1986661051,
2657
- 2177026350,
2658
- 2456956037,
2659
- 2730485921,
2660
- 2820302411,
2661
- 3259730800,
2662
- 3345764771,
2663
- 3516065817,
2664
- 3600352804,
2665
- 4094571909,
2666
- 275423344,
2667
- 430227734,
2668
- 506948616,
2669
- 659060556,
2670
- 883997877,
2671
- 958139571,
2672
- 1322822218,
2673
- 1537002063,
2674
- 1747873779,
2675
- 1955562222,
2676
- 2024104815,
2677
- 2227730452,
2678
- 2361852424,
2679
- 2428436474,
2680
- 2756734187,
2681
- 3204031479,
2682
- 3329325298
2683
- ]);
2684
- var SHA256_INITIAL_STATE = new Uint32Array([
2685
- 1779033703,
2686
- 3144134277,
2687
- 1013904242,
2688
- 2773480762,
2689
- 1359893119,
2690
- 2600822924,
2691
- 528734635,
2692
- 1541459225
2693
- ]);
2694
- function rotr(value, bits) {
2695
- return (value >>> bits | value << 32 - bits) >>> 0;
2807
+ // ../common/src/catch-error.ts
2808
+ var MAX_SERIALIZED_LENGTH = 500;
2809
+ var TRUNCATION_SUFFIX = "…(truncated)";
2810
+ var REDACTED2 = "[REDACTED]";
2811
+ function cap(text) {
2812
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
2696
2813
  }
2697
- function sha256Hex(input) {
2698
- const bytes = new TextEncoder().encode(input);
2699
- const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
2700
- const buffer = new Uint8Array(paddedLength);
2701
- buffer.set(bytes);
2702
- buffer[bytes.length] = 128;
2703
- const view = new DataView(buffer.buffer);
2704
- const bitLength = bytes.length * 8;
2705
- view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
2706
- view.setUint32(paddedLength - 4, bitLength >>> 0);
2707
- const state = SHA256_INITIAL_STATE.slice();
2708
- const schedule = new Uint32Array(64);
2709
- for (let offset = 0;offset < paddedLength; offset += 64) {
2710
- for (let i = 0;i < 16; i++) {
2711
- schedule[i] = view.getUint32(offset + i * 4);
2712
- }
2713
- for (let i = 16;i < 64; i++) {
2714
- const x = schedule[i - 15];
2715
- const y = schedule[i - 2];
2716
- const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
2717
- const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
2718
- schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
2719
- }
2720
- let a = state[0];
2721
- let b = state[1];
2722
- let c = state[2];
2723
- let d = state[3];
2724
- let e = state[4];
2725
- let f = state[5];
2726
- let g = state[6];
2727
- let h = state[7];
2728
- for (let i = 0;i < 64; i++) {
2729
- const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
2730
- const ch = (e & f ^ ~e & g) >>> 0;
2731
- const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
2732
- const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
2733
- const maj = (a & b ^ a & c ^ b & c) >>> 0;
2734
- const temp2 = s0 + maj >>> 0;
2735
- h = g;
2736
- g = f;
2737
- f = e;
2738
- e = d + temp1 >>> 0;
2739
- d = c;
2740
- c = b;
2741
- b = a;
2742
- a = temp1 + temp2 >>> 0;
2743
- }
2744
- state[0] = state[0] + a >>> 0;
2745
- state[1] = state[1] + b >>> 0;
2746
- state[2] = state[2] + c >>> 0;
2747
- state[3] = state[3] + d >>> 0;
2748
- state[4] = state[4] + e >>> 0;
2749
- state[5] = state[5] + f >>> 0;
2750
- state[6] = state[6] + g >>> 0;
2751
- state[7] = state[7] + h >>> 0;
2814
+ function omitSensitive(key, value) {
2815
+ return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
2816
+ }
2817
+ function describeThrownValue(value) {
2818
+ if (typeof value !== "object" || value === null) {
2819
+ return String(value);
2752
2820
  }
2753
- let hex = "";
2754
- for (const word of state) {
2755
- hex += word.toString(16).padStart(8, "0");
2821
+ let message;
2822
+ try {
2823
+ message = value.message;
2824
+ } catch {
2825
+ message = undefined;
2756
2826
  }
2757
- return hex;
2827
+ if (typeof message === "string" && message.length > 0) {
2828
+ return cap(message);
2829
+ }
2830
+ try {
2831
+ const json = JSON.stringify(value, omitSensitive);
2832
+ if (json !== undefined) {
2833
+ return cap(json);
2834
+ }
2835
+ } catch {}
2836
+ return String(value);
2758
2837
  }
2759
- function resolveSha256Hex() {
2838
+ function toError(error) {
2839
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
2840
+ }
2841
+ function isPromiseLike(value) {
2842
+ return value !== null && typeof value === "object" && typeof value.then === "function";
2843
+ }
2844
+ function catchError(fnOrPromise) {
2845
+ if (isPromiseLike(fnOrPromise)) {
2846
+ return settlePromiseLike(fnOrPromise);
2847
+ }
2760
2848
  try {
2761
- const nodeCrypto = __require("node:crypto");
2762
- const createHash = nodeCrypto?.createHash;
2763
- if (typeof createHash !== "function") {
2764
- return sha256Hex;
2849
+ const result = fnOrPromise();
2850
+ if (isPromiseLike(result)) {
2851
+ return settlePromiseLike(result);
2765
2852
  }
2766
- const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
2767
- return native("abc") === sha256Hex("abc") ? native : sha256Hex;
2768
- } catch {
2769
- return sha256Hex;
2853
+ return [undefined, result];
2854
+ } catch (error) {
2855
+ return [toError(error), undefined];
2770
2856
  }
2771
2857
  }
2772
- var cachedSha256Hex;
2773
- function digest(input) {
2774
- cachedSha256Hex ??= resolveSha256Hex();
2775
- return cachedSha256Hex(input);
2776
- }
2777
- function pseudonymize(input) {
2778
- return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
2858
+ function settlePromiseLike(thenable) {
2859
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
2779
2860
  }
2780
2861
 
2781
- // ../common/src/telemetry/supplied-values.ts
2782
- var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
2783
- function activeEntries() {
2784
- const existing = suppliedValuesSlot.get();
2785
- return Array.isArray(existing) ? existing : [];
2862
+ // ../common/src/error-codes.ts
2863
+ var CLI_ERROR_CODES = [
2864
+ "invalid_argument",
2865
+ "authentication_required",
2866
+ "permission_denied",
2867
+ "local_permission_denied",
2868
+ "not_found",
2869
+ "rate_limited",
2870
+ "network_error",
2871
+ "timeout",
2872
+ "server_error",
2873
+ "method_not_allowed",
2874
+ "not_supported",
2875
+ "configuration_error",
2876
+ "execution_failed",
2877
+ "unknown_error"
2878
+ ];
2879
+ var RETRY_HINTS = [
2880
+ "RetryWillNotFix",
2881
+ "RetryLater",
2882
+ "RetryAfter1Second",
2883
+ "RetryAfter10Seconds",
2884
+ "RetryAfter30Seconds",
2885
+ "RetryAfter60Seconds"
2886
+ ];
2887
+ var CLI_ERROR_CODE_VALUES = new Set(CLI_ERROR_CODES);
2888
+ var RETRY_HINT_VALUES = new Set(RETRY_HINTS);
2889
+ function isCliErrorCode(value) {
2890
+ return typeof value === "string" && CLI_ERROR_CODE_VALUES.has(value);
2786
2891
  }
2787
- var MIN_SCRUBBABLE_LENGTH = 4;
2788
- function recordSuppliedArgumentValues(values) {
2789
- const flat = [];
2790
- const push = (value) => {
2791
- if (Array.isArray(value)) {
2792
- for (const item of value) {
2793
- push(item);
2794
- }
2795
- return;
2796
- }
2797
- if (typeof value === "string" && value.length >= MIN_SCRUBBABLE_LENGTH) {
2798
- flat.push(value);
2799
- }
2800
- };
2801
- push(values);
2802
- const entry = { values: flat };
2803
- suppliedValuesSlot.set([...activeEntries(), entry]);
2804
- return entry;
2892
+ function isRetryHint(value) {
2893
+ return typeof value === "string" && RETRY_HINT_VALUES.has(value);
2805
2894
  }
2806
- function releaseSuppliedArgumentValues(entry) {
2807
- suppliedValuesSlot.set(activeEntries().filter((held) => held !== entry));
2895
+ function carriedErrorCode(error) {
2896
+ if (!error || typeof error !== "object")
2897
+ return;
2898
+ const code = error.errorCode;
2899
+ return isCliErrorCode(code) ? code : undefined;
2808
2900
  }
2809
- function getSuppliedArgumentValues() {
2810
- const all = new Set;
2811
- for (const entry of activeEntries()) {
2812
- for (const value of entry.values) {
2813
- all.add(value);
2814
- }
2901
+ function carriedRetry(error) {
2902
+ if (!error || typeof error !== "object")
2903
+ return;
2904
+ const retry = error.retry;
2905
+ return isRetryHint(retry) ? retry : undefined;
2906
+ }
2907
+ function defaultRetryForErrorCode(errorCode) {
2908
+ switch (errorCode) {
2909
+ case "network_error":
2910
+ case "rate_limited":
2911
+ case "server_error":
2912
+ case "timeout":
2913
+ return "RetryLater";
2914
+ default:
2915
+ return "RetryWillNotFix";
2815
2916
  }
2816
- return [...all].sort((a, b) => b.length - a.length);
2817
2917
  }
2818
2918
 
2819
- // ../common/src/telemetry/pii-redactor.ts
2820
- var REDACTED = "[REDACTED]";
2821
- var MAX_VALUE_LENGTH = 280;
2822
- var MAX_STACK_LENGTH = 4096;
2823
- var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
2824
- function truncate(value, maxLength) {
2825
- return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
2919
+ // ../common/src/error-graph.ts
2920
+ function* walkErrorGraph(error) {
2921
+ const queue = [error];
2922
+ const seen = new Set;
2923
+ for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
2924
+ const current = queue.shift();
2925
+ if (current === null || typeof current !== "object")
2926
+ continue;
2927
+ if (seen.has(current))
2928
+ continue;
2929
+ seen.add(current);
2930
+ const cur = current;
2931
+ yield cur;
2932
+ if (cur.cause !== undefined)
2933
+ queue.push(cur.cause);
2934
+ if (Array.isArray(cur.errors))
2935
+ queue.push(...cur.errors);
2936
+ }
2937
+ return;
2826
2938
  }
2827
- var SENSITIVE_NAME_TOKENS = new Set([
2828
- "token",
2829
- "tokens",
2830
- "secret",
2831
- "secrets",
2832
- "password",
2833
- "passwords",
2834
- "pwd",
2835
- "credential",
2836
- "credentials",
2837
- "auth",
2838
- "authentication",
2839
- "authorization",
2840
- "authority",
2841
- "cert",
2842
- "certificate",
2843
- "certificates"
2844
- ]);
2845
- var SENSITIVE_KEY_PREFIXES = new Set([
2846
- "api",
2847
- "access",
2848
- "client",
2849
- "private",
2850
- "public",
2851
- "signing",
2852
- "encryption",
2853
- "session",
2854
- "master",
2855
- "shared",
2856
- "root",
2857
- "ssh",
2858
- "rsa",
2859
- "aes",
2860
- "hmac",
2861
- "oauth"
2862
- ]);
2863
- var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
2864
- var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
2865
- var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
2866
- var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
2867
- var PADDED_BASE64_PATTERN = /(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
2868
- var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
2869
- var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
2870
- var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
2871
- var HOST_PORT_PATTERN = /(?<![/@.\w-])(?!\d+\.\d+\.\d+\.\d+:)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+:\d{1,5}\b/g;
2872
- var SOURCE_FILE_EXTENSIONS = new Set([
2873
- "ts",
2874
- "tsx",
2875
- "js",
2876
- "jsx",
2877
- "mjs",
2878
- "cjs",
2879
- "cts",
2880
- "mts",
2881
- "py",
2882
- "cs",
2883
- "java",
2884
- "go",
2885
- "rs",
2886
- "rb",
2887
- "php",
2888
- "sh",
2889
- "ps1",
2890
- "json",
2891
- "jsonc",
2892
- "yaml",
2893
- "yml",
2894
- "xml",
2895
- "xaml",
2896
- "md",
2897
- "txt",
2898
- "log",
2899
- "css",
2900
- "html",
2901
- "htm",
2902
- "csproj",
2903
- "nuspec",
2904
- "sql"
2905
- ]);
2906
- var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
2907
- var QUOTED_LITERAL_MAX_SPAN = 200;
2908
- var QUOTED_LITERAL_PATTERN = new RegExp([
2909
- `(?<![A-Za-z0-9])'(?:[^\\
2910
- ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
2911
- `(?<![A-Za-z0-9])"(?:[^\\
2912
- ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
2913
- ].join("|"), "g");
2914
- var JSON_BODY_PATTERN = /[{[][^{}[\]:,]*[:,][^{}[\]]*[\]}]/g;
2915
- var COLLAPSED_BODY = "{…}";
2916
- var COLLAPSED_BODY_MARKER = "\x01body\x01";
2917
- var MAX_BODY_NESTING = 8;
2918
- function collapseJsonBodies(text) {
2919
- let out = text;
2920
- for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
2921
- const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
2922
- if (next === out) {
2923
- break;
2939
+ function parseHttpStatusFromMessage(message) {
2940
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
2941
+ if (!match)
2942
+ return;
2943
+ const status = Number(match[1]);
2944
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
2945
+ }
2946
+ function findHttpStatusInGraph(error) {
2947
+ for (const node of walkErrorGraph(error)) {
2948
+ const response = node.response;
2949
+ const explicit = typeof node.status === "number" ? node.status : response?.status;
2950
+ if (typeof explicit === "number" && explicit >= 400 && explicit <= 599) {
2951
+ return explicit;
2952
+ }
2953
+ if (typeof node.message === "string") {
2954
+ const parsed = parseHttpStatusFromMessage(node.message);
2955
+ if (parsed !== undefined && parsed >= 400) {
2956
+ return parsed;
2957
+ }
2924
2958
  }
2925
- out = next;
2926
2959
  }
2927
- return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
2960
+ return;
2928
2961
  }
2929
- var TRAILING_PROSE_PUNCT = `.,;:!?)]}>'"`;
2930
- function peelTrailingPunctuation(match) {
2931
- let end = match.length;
2932
- while (end > 0 && TRAILING_PROSE_PUNCT.includes(match[end - 1])) {
2933
- end -= 1;
2962
+
2963
+ // ../common/src/http-status.ts
2964
+ function classifyHttpStatus(status) {
2965
+ if (status === undefined)
2966
+ return;
2967
+ if (status === 400 || status === 409 || status === 413 || status === 422) {
2968
+ return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
2934
2969
  }
2935
- return [match.slice(0, end), match.slice(end)];
2936
- }
2937
- function redactUrl(raw) {
2938
- try {
2939
- const url = new URL(raw);
2940
- return `${url.protocol}//${url.host}`;
2941
- } catch {
2942
- return `url#${pseudonymize(raw)}`;
2970
+ if (status === 401) {
2971
+ return {
2972
+ errorCode: "authentication_required",
2973
+ retry: "RetryWillNotFix"
2974
+ };
2943
2975
  }
2944
- }
2945
- function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
2946
- let out = truncate(value, MAX_SCAN_LENGTH);
2947
- out = out.replace(JWT_PATTERN, () => REDACTED);
2948
- out = out.replace(URL_PATTERN, (match) => {
2949
- const [core, trailing] = peelTrailingPunctuation(match);
2950
- return `${redactUrl(core)}${trailing}`;
2951
- });
2952
- out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
2953
- out = out.replace(UNC_PATH_PATTERN, (_match, before, path2) => {
2954
- const [core, trailing] = peelTrailingPunctuation(path2);
2955
- return `${before}unc#${pseudonymize(core)}${trailing}`;
2956
- });
2957
- out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
2958
- out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
2959
- out = out.replace(HOST_PORT_PATTERN, (match) => {
2960
- const split = match.lastIndexOf(":");
2961
- const host = match.slice(0, split);
2962
- const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
2963
- if (SOURCE_FILE_EXTENSIONS.has(extension)) {
2964
- return match;
2965
- }
2966
- return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
2967
- });
2968
- out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
2969
- out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
2970
- out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
2971
- return truncate(out, maxLength);
2972
- }
2973
- function redactSpanName(name) {
2974
- return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
2975
- }
2976
- var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
2977
- function redactHttpDependencyName(name) {
2978
- const parts = HTTP_DEPENDENCY_NAME.exec(name);
2979
- if (!parts) {
2980
- return redactMessage(name);
2976
+ if (status === 403) {
2977
+ return { errorCode: "permission_denied", retry: "RetryWillNotFix" };
2981
2978
  }
2982
- return `${parts[1]} ${redactMessage(parts[2])}`;
2983
- }
2984
- function redactMessage(value) {
2985
- let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
2986
- for (const supplied of getSuppliedArgumentValues()) {
2987
- out = out.split(supplied).join(REDACTED);
2979
+ if (status === 404) {
2980
+ return { errorCode: "not_found", retry: "RetryWillNotFix" };
2988
2981
  }
2989
- return redactValueDetectors(out);
2982
+ if (status === 405) {
2983
+ return { errorCode: "method_not_allowed", retry: "RetryWillNotFix" };
2984
+ }
2985
+ if (status === 408) {
2986
+ return { errorCode: "timeout", retry: "RetryLater" };
2987
+ }
2988
+ if (status === 429) {
2989
+ return { errorCode: "rate_limited", retry: "RetryLater" };
2990
+ }
2991
+ if (status >= 500 && status < 600) {
2992
+ return { errorCode: "server_error", retry: "RetryLater" };
2993
+ }
2994
+ return;
2990
2995
  }
2991
- var MESSAGE_NAMES = new Set([
2992
- "message",
2993
- "errormessage",
2994
- "errmessage",
2995
- "error_message",
2996
- "msg",
2997
- "detail",
2998
- "details",
2999
- "reason",
3000
- "instructions",
3001
- "warning"
3002
- ]);
3003
- function isFreeFormValue(name, value) {
3004
- return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
3005
- }
3006
- function redactError(error) {
3007
- const safe = new Error(redactMessage(error.message ?? ""));
3008
- safe.name = error.name;
3009
- safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
3010
- return safe;
3011
- }
3012
- function redactStack(stack) {
3013
- const bounded = truncate(stack, MAX_STACK_LENGTH);
3014
- const firstBreak = bounded.indexOf(`
3015
- `);
3016
- if (firstBreak === -1) {
3017
- return redactMessage(bounded);
3018
- }
3019
- return `${redactMessage(bounded.slice(0, firstBreak))}
3020
- ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
3021
- }
3022
- function nameTokens(name) {
3023
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s._-]+/).map((t) => t.toLowerCase()).filter(Boolean);
3024
- }
3025
- function isSensitiveName(name) {
3026
- const tokens = nameTokens(name);
3027
- for (let i = 0;i < tokens.length; i++) {
3028
- const token = tokens[i];
3029
- if (SENSITIVE_NAME_TOKENS.has(token)) {
3030
- return true;
3031
- }
3032
- if (token === "key" || token === "keys") {
3033
- const prev = tokens[i - 1];
3034
- if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
3035
- return true;
3036
- }
3037
- }
3038
- }
3039
- return false;
3040
- }
3041
- function redactProperty(name, value) {
3042
- if (value === undefined || value === null) {
3043
- return;
3044
- }
3045
- if (isSensitiveName(name)) {
3046
- return REDACTED;
3047
- }
3048
- if (typeof value === "boolean" || typeof value === "number") {
3049
- return value;
3050
- }
3051
- if (typeof value !== "string") {
3052
- return "[OBJECT]";
3053
- }
3054
- return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
3055
- }
3056
- function redactProperties(properties) {
3057
- const out = {};
3058
- for (const [name, value] of Object.entries(properties)) {
3059
- const redacted = redactProperty(name, value);
3060
- if (redacted !== undefined) {
3061
- out[name] = redacted;
3062
- }
3063
- }
3064
- return out;
3065
- }
3066
-
3067
- // ../common/src/catch-error.ts
3068
- var MAX_SERIALIZED_LENGTH = 500;
3069
- var TRUNCATION_SUFFIX = "…(truncated)";
3070
- var REDACTED2 = "[REDACTED]";
3071
- function cap(text) {
3072
- return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
3073
- }
3074
- function omitSensitive(key, value) {
3075
- return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
3076
- }
3077
- function describeThrownValue(value) {
3078
- if (typeof value !== "object" || value === null) {
3079
- return String(value);
3080
- }
3081
- let message;
3082
- try {
3083
- message = value.message;
3084
- } catch {
3085
- message = undefined;
3086
- }
3087
- if (typeof message === "string" && message.length > 0) {
3088
- return cap(message);
3089
- }
3090
- try {
3091
- const json = JSON.stringify(value, omitSensitive);
3092
- if (json !== undefined) {
3093
- return cap(json);
3094
- }
3095
- } catch {}
3096
- return String(value);
3097
- }
3098
- function toError(error) {
3099
- return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
3100
- }
3101
- function isPromiseLike(value) {
3102
- return value !== null && typeof value === "object" && typeof value.then === "function";
3103
- }
3104
- function catchError(fnOrPromise) {
3105
- if (isPromiseLike(fnOrPromise)) {
3106
- return settlePromiseLike(fnOrPromise);
3107
- }
3108
- try {
3109
- const result = fnOrPromise();
3110
- if (isPromiseLike(result)) {
3111
- return settlePromiseLike(result);
3112
- }
3113
- return [undefined, result];
3114
- } catch (error) {
3115
- return [toError(error), undefined];
3116
- }
3117
- }
3118
- function settlePromiseLike(thenable) {
3119
- return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
3120
- }
3121
-
3122
- // ../common/src/error-graph.ts
3123
- function* walkErrorGraph(error) {
3124
- const queue = [error];
3125
- const seen = new Set;
3126
- for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
3127
- const current = queue.shift();
3128
- if (current === null || typeof current !== "object")
3129
- continue;
3130
- if (seen.has(current))
3131
- continue;
3132
- seen.add(current);
3133
- const cur = current;
3134
- yield cur;
3135
- if (cur.cause !== undefined)
3136
- queue.push(cur.cause);
3137
- if (Array.isArray(cur.errors))
3138
- queue.push(...cur.errors);
3139
- }
3140
- return;
3141
- }
3142
- function parseHttpStatusFromMessage(message) {
3143
- const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
3144
- if (!match)
3145
- return;
3146
- const status = Number(match[1]);
3147
- return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
3148
- }
3149
- function findHttpStatusInGraph(error) {
3150
- for (const node of walkErrorGraph(error)) {
3151
- const response = node.response;
3152
- const explicit = typeof node.status === "number" ? node.status : response?.status;
3153
- if (typeof explicit === "number" && explicit >= 400 && explicit <= 599) {
3154
- return explicit;
3155
- }
3156
- if (typeof node.message === "string") {
3157
- const parsed = parseHttpStatusFromMessage(node.message);
3158
- if (parsed !== undefined && parsed >= 400) {
3159
- return parsed;
3160
- }
3161
- }
3162
- }
3163
- return;
3164
- }
3165
-
3166
- // ../common/src/local-permission-codes.ts
3167
- var LOCAL_PERMISSION_ERROR_CODES = new Set([
3168
- "EACCES",
3169
- "EPERM",
3170
- "EROFS"
2996
+
2997
+ // ../common/src/local-permission-codes.ts
2998
+ var LOCAL_PERMISSION_ERROR_CODES = new Set([
2999
+ "EACCES",
3000
+ "EPERM",
3001
+ "EROFS"
3171
3002
  ]);
3172
3003
 
3173
3004
  // ../common/src/error-handler.ts
@@ -3175,6 +3006,8 @@ var DEFAULT_401 = "Unauthorized (401). The session is missing or expired, or its
3175
3006
  var DEFAULT_403 = "Forbidden (403). The account lacks permission for this operation, or the token carries no scope for this API. Run `uip login status --detailed` to see the token's scopes.";
3176
3007
  var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
3177
3008
  var DEFAULT_413 = "Payload too large (413). The upload exceeded the server or CDN size limit. Reduce the package size — for example, exclude unused dependencies or remove large files from the project — and try again.";
3009
+ var CLOUDFLARE_BLOCK_403 = "Forbidden (403) by Cloudflare, in front of the service: the answer is a Cloudflare HTML page, not the service's JSON, so the service did not see the request and did not check the account's roles or the token's scopes. Cloudflare blocks a request when its content matches a firewall rule (text that looks like SQL or script code, for example) or when it comes from a network the firewall does not allow.";
3010
+ var CLOUDFLARE_BLOCK_403_INSTRUCTIONS = "If the request carries text that looks like code, change that text and try again. Otherwise send the time of the request and the Cloudflare Ray ID, when the message gives one, to the owner of the service or UiPath support.";
3178
3011
  var HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.";
3179
3012
  var NETWORK_ERROR_CODES = new Set([
3180
3013
  "ECONNREFUSED",
@@ -3200,8 +3033,8 @@ var TLS_ERROR_CODES = new Set([
3200
3033
  var TLS_INSTRUCTIONS = "The server's TLS certificate could not be verified. Most often a " + "corporate proxy/firewall re-signs HTTPS with a root CA that Node does " + "not trust — set NODE_EXTRA_CA_CERTS to that CA's PEM file (and HTTPS_PROXY " + "if you connect through a proxy). If the certificate is instead expired or " + "its hostname does not match, fix the endpoint URL or the system clock. " + "Then retry.";
3201
3034
  var NETWORK_INSTRUCTIONS = "Could not reach the UiPath service. Check your network connection and " + "VPN, confirm any HTTP_PROXY/HTTPS_PROXY/NO_PROXY settings are correct, " + "then retry.";
3202
3035
  var LOCAL_PERMISSION_MESSAGE_PATTERN = new RegExp(`\\b(${[...LOCAL_PERMISSION_ERROR_CODES].join("|")})\\b`);
3203
- function localPermissionInstructions(code, path2) {
3204
- const target = path2 !== undefined ? `'${path2}'` : "a local file or resource";
3036
+ function localPermissionInstructions(code, path) {
3037
+ const target = path !== undefined ? `'${path}'` : "a local file or resource";
3205
3038
  if (code === "EROFS") {
3206
3039
  return `The filesystem containing ${target} is read-only (EROFS), so the ` + "CLI could not write to it. This is a local environment problem, " + "not a UiPath service error — retrying will not help. Use a " + "writable location, or give this environment write access to the " + "path.";
3207
3040
  }
@@ -3238,12 +3071,12 @@ function describePermissionError(error) {
3238
3071
  const code = matchLocalPermissionCode(cur.code, message);
3239
3072
  if (!code)
3240
3073
  continue;
3241
- const path2 = localPermissionPath(cur.path, message);
3074
+ const path = localPermissionPath(cur.path, message);
3242
3075
  return {
3243
3076
  code,
3244
3077
  message: message ?? code,
3245
- ...path2 !== undefined ? { path: path2 } : {},
3246
- instructions: localPermissionInstructions(code, path2)
3078
+ ...path !== undefined ? { path } : {},
3079
+ instructions: localPermissionInstructions(code, path)
3247
3080
  };
3248
3081
  }
3249
3082
  return;
@@ -3255,11 +3088,25 @@ function matchLocalPermissionCode(code, message) {
3255
3088
  const match = message ? LOCAL_PERMISSION_MESSAGE_PATTERN.exec(message) : null;
3256
3089
  return match ? match[1] : undefined;
3257
3090
  }
3258
- function localPermissionPath(path2, message) {
3259
- if (typeof path2 === "string")
3260
- return path2;
3091
+ function localPermissionPath(path, message) {
3092
+ if (typeof path === "string")
3093
+ return path;
3261
3094
  return message ? /'([^']+)'/.exec(message)?.[1] : undefined;
3262
3095
  }
3096
+ function readHeader(response, name) {
3097
+ const headers = response?.headers;
3098
+ if (!headers || typeof headers !== "object")
3099
+ return;
3100
+ if (typeof headers.get === "function") {
3101
+ const value = headers.get(name);
3102
+ if (value)
3103
+ return value;
3104
+ }
3105
+ const plain = headers;
3106
+ const key = Object.keys(plain).find((k) => k.toLowerCase() === name.toLowerCase());
3107
+ const value = key === undefined ? undefined : plain[key];
3108
+ return typeof value === "string" && value !== "" ? value : undefined;
3109
+ }
3263
3110
  function isHtmlDocument(body) {
3264
3111
  return /^\s*(<!doctype html|<html\b)/i.test(body);
3265
3112
  }
@@ -3276,36 +3123,9 @@ function retryHintForRetryAfter(seconds) {
3276
3123
  return "RetryAfter60Seconds";
3277
3124
  }
3278
3125
  function classifyError(status, error) {
3279
- if (status === 400 || status === 409 || status === 422) {
3280
- return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
3281
- }
3282
- if (status === 401) {
3283
- return {
3284
- errorCode: "authentication_required",
3285
- retry: "RetryWillNotFix"
3286
- };
3287
- }
3288
- if (status === 403) {
3289
- return { errorCode: "permission_denied", retry: "RetryWillNotFix" };
3290
- }
3291
- if (status === 404) {
3292
- return { errorCode: "not_found", retry: "RetryWillNotFix" };
3293
- }
3294
- if (status === 405) {
3295
- return { errorCode: "method_not_allowed", retry: "RetryWillNotFix" };
3296
- }
3297
- if (status === 413) {
3298
- return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
3299
- }
3300
- if (status === 408) {
3301
- return { errorCode: "timeout", retry: "RetryLater" };
3302
- }
3303
- if (status === 429) {
3304
- return { errorCode: "rate_limited", retry: "RetryLater" };
3305
- }
3306
- if (status !== undefined && status >= 500 && status < 600) {
3307
- return { errorCode: "server_error", retry: "RetryLater" };
3308
- }
3126
+ const byStatus = classifyHttpStatus(status);
3127
+ if (byStatus)
3128
+ return byStatus;
3309
3129
  if (status === undefined && describePermissionError(error)) {
3310
3130
  return {
3311
3131
  errorCode: "local_permission_denied",
@@ -3321,6 +3141,17 @@ function classifyError(status, error) {
3321
3141
  }
3322
3142
  return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
3323
3143
  }
3144
+ function withCarriedClass(inferred, error) {
3145
+ const errorCode = carriedErrorCode(error);
3146
+ const retry = carriedRetry(error);
3147
+ if (errorCode === undefined || errorCode === inferred.errorCode) {
3148
+ return {
3149
+ errorCode: inferred.errorCode,
3150
+ retry: retry ?? inferred.retry
3151
+ };
3152
+ }
3153
+ return { errorCode, retry: retry ?? defaultRetryForErrorCode(errorCode) };
3154
+ }
3324
3155
  function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
3325
3156
  if (extractedMessage) {
3326
3157
  return `HTTP ${status}: ${extractedMessage}`;
@@ -3376,9 +3207,14 @@ async function extractErrorDetails(error, options) {
3376
3207
  const classificationStatus = status ?? findHttpStatusInGraph(error);
3377
3208
  const classification = classifyError(classificationStatus, error);
3378
3209
  let retry = classification.retry;
3210
+ const htmlForbidden = status === 403 && rawBody !== undefined && isHtmlDocument(rawBody);
3211
+ const rayId = htmlForbidden ? readHeader(response, "cf-ray") : undefined;
3212
+ const cloudflareBlock = htmlForbidden && (rayId !== undefined || /\bcloudflare\b/i.test(readHeader(response, "server") ?? ""));
3379
3213
  if (status === 401) {
3380
3214
  message = DEFAULT_401;
3381
3215
  result = "AuthenticationError";
3216
+ } else if (cloudflareBlock) {
3217
+ message = rayId ? `${CLOUDFLARE_BLOCK_403} Cloudflare Ray ID: ${rayId}.` : CLOUDFLARE_BLOCK_403;
3382
3218
  } else if (status === 403) {
3383
3219
  message = options?.forbiddenMessage ?? DEFAULT_403;
3384
3220
  result = "AuthenticationError";
@@ -3406,138 +3242,554 @@ async function extractErrorDetails(error, options) {
3406
3242
  } else {
3407
3243
  message = `HTTP ${status}: ${rawMessage}`;
3408
3244
  }
3409
- } else {
3410
- message = rawMessage;
3245
+ } else {
3246
+ message = rawMessage;
3247
+ }
3248
+ if (status === undefined) {
3249
+ const connectivity = describeConnectivityError(error);
3250
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
3251
+ message = `${message}: ${connectivity.message}`;
3252
+ }
3253
+ }
3254
+ const permission = status === undefined ? describePermissionError(error) : undefined;
3255
+ if (permission) {
3256
+ if (permission.message !== message && !message.includes(permission.message)) {
3257
+ message = `${message}: ${permission.message}`;
3258
+ }
3259
+ if (!message.includes(permission.instructions)) {
3260
+ const punctuated = message.endsWith(".") ? message : `${message}.`;
3261
+ message = `${punctuated} ${permission.instructions}`;
3262
+ }
3263
+ }
3264
+ let details = rawMessage;
3265
+ if (htmlForbidden) {
3266
+ details = cloudflareBlock ? CLOUDFLARE_BLOCK_403_INSTRUCTIONS : HTML_RESPONSE_MESSAGE;
3267
+ } else if (rawBody) {
3268
+ if (parsedBody) {
3269
+ const extra = {};
3270
+ if (parsedBody.errorCode)
3271
+ extra.errorCode = parsedBody.errorCode;
3272
+ if (parsedBody.detail)
3273
+ extra.detail = parsedBody.detail;
3274
+ if (parsedBody.details)
3275
+ extra.details = parsedBody.details;
3276
+ if (parsedBody.errors != null)
3277
+ extra.errors = parsedBody.errors;
3278
+ if (parsedBody.data && typeof parsedBody.data === "object" && Object.keys(parsedBody.data).length > 0) {
3279
+ extra.data = parsedBody.data;
3280
+ }
3281
+ details = Object.keys(extra).length > 0 ? JSON.stringify(extra) : rawBody;
3282
+ } else {
3283
+ details = rawBody;
3284
+ }
3285
+ } else if (typeof err.message === "string") {
3286
+ details = err.message;
3287
+ } else {
3288
+ details = describeThrownValue(error);
3289
+ }
3290
+ const context = {};
3291
+ if (classificationStatus) {
3292
+ context.httpStatus = classificationStatus;
3293
+ }
3294
+ if (parsedBody?.errorCode && typeof parsedBody.errorCode === "string") {
3295
+ context.errorCode = parsedBody.errorCode;
3296
+ } else if (parsedBody?.code && typeof parsedBody.code === "string") {
3297
+ context.errorCode = parsedBody.code;
3298
+ }
3299
+ if (parsedBody?.requestId && typeof parsedBody.requestId === "string") {
3300
+ context.requestId = parsedBody.requestId;
3301
+ } else if (cloudflareBlock && rayId) {
3302
+ context.requestId = rayId;
3303
+ }
3304
+ if (parsedBody?.traceId && typeof parsedBody.traceId === "string") {
3305
+ context.traceId = parsedBody.traceId;
3306
+ }
3307
+ if (permission?.path !== undefined) {
3308
+ context.path = permission.path;
3309
+ }
3310
+ if (status === 429) {
3311
+ const retryAfterValue = readHeader(response, "retry-after");
3312
+ if (retryAfterValue) {
3313
+ const seconds = Number(retryAfterValue);
3314
+ if (!Number.isNaN(seconds)) {
3315
+ context.retryAfter = seconds;
3316
+ retry = retryHintForRetryAfter(seconds);
3317
+ }
3318
+ }
3319
+ }
3320
+ const hasContext = Object.keys(context).length > 0;
3321
+ let parsedErrors;
3322
+ if (parsedBody?.errors && typeof parsedBody.errors === "object") {
3323
+ const errors = {};
3324
+ for (const [field, raw] of Object.entries(parsedBody.errors)) {
3325
+ if (Array.isArray(raw)) {
3326
+ const messages = raw.map((entry) => {
3327
+ if (typeof entry === "string")
3328
+ return entry;
3329
+ if (entry && typeof entry === "object" && typeof entry.message === "string") {
3330
+ return entry.message;
3331
+ }
3332
+ return String(entry);
3333
+ }).filter(Boolean);
3334
+ if (messages.length > 0)
3335
+ errors[field] = messages;
3336
+ } else if (typeof raw === "string") {
3337
+ errors[field] = [raw];
3338
+ }
3339
+ }
3340
+ if (Object.keys(errors).length > 0)
3341
+ parsedErrors = errors;
3342
+ }
3343
+ return {
3344
+ result,
3345
+ ...withCarriedClass({ errorCode: classification.errorCode, retry }, error),
3346
+ message,
3347
+ details,
3348
+ ...hasContext ? { context } : {},
3349
+ ...parsedErrors ? { parsedErrors } : {}
3350
+ };
3351
+ }
3352
+ function extractErrorMessageSync(error) {
3353
+ if (error instanceof Error) {
3354
+ return error.message;
3355
+ }
3356
+ if (typeof error === "object" && error !== null) {
3357
+ if ("status" in error && error.status === 401) {
3358
+ return DEFAULT_401;
3359
+ }
3360
+ if ("message" in error && typeof error.message === "string") {
3361
+ return error.message;
3362
+ }
3363
+ }
3364
+ return describeThrownValue(error);
3365
+ }
3366
+
3367
+ // ../common/src/error-instructions.ts
3368
+ function extractHttpStatus(err) {
3369
+ if (!err || typeof err !== "object")
3370
+ return;
3371
+ const e = err;
3372
+ const structured = e.response?.status ?? e.status ?? e.statusCode;
3373
+ if (structured !== undefined)
3374
+ return structured;
3375
+ return typeof e.message === "string" ? parseHttpStatusFromMessage(e.message) : undefined;
3376
+ }
3377
+ var GENERIC = "Check authentication and parameters";
3378
+ function hasIdentityInstructionContext(err) {
3379
+ return err !== null && typeof err === "object" && "instructionContext" in err && err.instructionContext === "identity";
3380
+ }
3381
+ function instructionsFor(ctx, err) {
3382
+ if (ctx === "auth" && hasIdentityInstructionContext(err)) {
3383
+ return instructionsFor("identity");
3384
+ }
3385
+ switch (ctx) {
3386
+ case "auth":
3387
+ return "Run 'uip login' to authenticate. To inspect the current session, run 'uip whoami'.";
3388
+ case "auth-configuration":
3389
+ return "Fix the authentication settings named in Message, then retry.";
3390
+ case "identity":
3391
+ return "Select an active tenant with 'uip login tenant set <tenant>' and ensure your login includes an organization";
3392
+ case "input-parse":
3393
+ return "Ensure --inputs is valid JSON or pipe JSON via stdin";
3394
+ case "input-validate":
3395
+ return "Fix the flagged input fields to match the process's input schema";
3396
+ case "flag-format":
3397
+ return "Check the flag value format — see --help for the expected shape";
3398
+ case "permissions":
3399
+ return "Confirm your user has the required permissions in this folder/tenant, or re-authenticate with 'uip login' if your session has lapsed";
3400
+ case "backend": {
3401
+ const status = extractHttpStatus(err);
3402
+ if (status === 401) {
3403
+ return "Re-authenticate with 'uip login' — your session is invalid or expired";
3404
+ }
3405
+ if (status === 403) {
3406
+ return "Confirm your user has access to the resource, and the required permissions in this folder or tenant";
3407
+ }
3408
+ if (status === 404) {
3409
+ return "Verify the resource exists in the current folder/tenant";
3410
+ }
3411
+ if (status === 400 || status === 422) {
3412
+ return "Request was rejected — check flag values and inputs";
3413
+ }
3414
+ if (status === 405) {
3415
+ return "Check the command name and the base URL in use — the endpoint may not exist";
3416
+ }
3417
+ if (status === 408) {
3418
+ return "The request timed out — retry; if it persists, narrow the request (e.g. --limit on list commands)";
3419
+ }
3420
+ if (status === 409) {
3421
+ return "The resource already exists, or changed since it was read — list it to see the current state";
3422
+ }
3423
+ if (status === 413) {
3424
+ return "The upload is over the size limit — exclude unused dependencies or drop large files, then retry";
3425
+ }
3426
+ if (status === 429) {
3427
+ return "Rate limit reached — wait and retry; when the service suggests a delay, Retry and Context.retryAfter carry it";
3428
+ }
3429
+ if (status !== undefined && status >= 500 && status < 600) {
3430
+ return "The service returned a server error — retry; if it persists, check service status";
3431
+ }
3432
+ const permission = describePermissionError(err);
3433
+ if (permission) {
3434
+ return permission.instructions;
3435
+ }
3436
+ const connectivity = describeConnectivityError(err);
3437
+ if (connectivity) {
3438
+ return connectivity.instructions;
3439
+ }
3440
+ return GENERIC;
3441
+ }
3442
+ }
3443
+ }
3444
+
3445
+ // ../../node_modules/commander/index.js
3446
+ var exports_commander = {};
3447
+ __exportCjs(exports_commander, {
3448
+ program: () => $program,
3449
+ createCommand: () => $createCommand,
3450
+ createOption: () => $createOption,
3451
+ createArgument: () => $createArgument,
3452
+ Command: () => $Command,
3453
+ Option: () => $Option,
3454
+ Argument: () => $Argument,
3455
+ Help: () => $Help,
3456
+ CommanderError: () => $CommanderError,
3457
+ InvalidArgumentError: () => $InvalidArgumentError,
3458
+ InvalidOptionArgumentError: () => $InvalidOptionArgumentError
3459
+ }, {
3460
+ program: (value) => $program = value,
3461
+ createCommand: (value) => $createCommand = value,
3462
+ createOption: (value) => $createOption = value,
3463
+ createArgument: (value) => $createArgument = value,
3464
+ Command: (value) => $Command = value,
3465
+ Option: (value) => $Option = value,
3466
+ Argument: (value) => $Argument = value,
3467
+ Help: (value) => $Help = value,
3468
+ CommanderError: (value) => $CommanderError = value,
3469
+ InvalidArgumentError: (value) => $InvalidArgumentError = value,
3470
+ InvalidOptionArgumentError: (value) => $InvalidOptionArgumentError = value
3471
+ });
3472
+ var { Argument } = require_argument();
3473
+ var { Command: Command2 } = require_command();
3474
+ var { CommanderError, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3475
+ var { Help } = require_help();
3476
+ var { Option } = require_option();
3477
+ var $program = new Command2;
3478
+ var $createCommand = (name) => new Command2(name);
3479
+ var $createOption = (flags, description) => new Option(flags, description);
3480
+ var $createArgument = (name, description) => new Argument(name, description);
3481
+ var $Command = Command2;
3482
+ var $Option = Option;
3483
+ var $Argument = Argument;
3484
+ var $Help = Help;
3485
+ var $CommanderError = CommanderError;
3486
+ var $InvalidArgumentError = InvalidArgumentError2;
3487
+ var $InvalidOptionArgumentError = InvalidArgumentError2;
3488
+
3489
+ // ../../node_modules/commander/esm.mjs
3490
+ var {
3491
+ program,
3492
+ createCommand,
3493
+ createArgument,
3494
+ createOption,
3495
+ CommanderError: CommanderError2,
3496
+ InvalidArgumentError,
3497
+ InvalidOptionArgumentError,
3498
+ Command,
3499
+ Argument: Argument2,
3500
+ Option: Option2,
3501
+ Help: Help2
3502
+ } = exports_commander;
3503
+
3504
+ // ../filesystem/src/node.ts
3505
+ import { createHash, randomUUID } from "node:crypto";
3506
+ import { existsSync } from "node:fs";
3507
+ import * as fs from "node:fs/promises";
3508
+ import * as os from "node:os";
3509
+ import * as path from "node:path";
3510
+ var LOCK_HEARTBEAT_MS = 5000;
3511
+ var LOCK_STALE_MS = 15000;
3512
+ var LOCK_MAX_WAIT_MS = 20000;
3513
+ var LOCK_MAX_HOLD_MS = 60000;
3514
+ var LOCK_RETRY_MIN_MS = 100;
3515
+ var LOCK_RETRY_JITTER_MS = 200;
3516
+ var HASH_CHUNK_BYTES = 256 * 1024;
3517
+ var hashBuffers = [];
3518
+ var HASH_BUFFERS_KEPT = 64;
3519
+
3520
+ class NodeFileSystem {
3521
+ path = {
3522
+ join: path.join,
3523
+ resolve: path.resolve,
3524
+ relative: path.relative,
3525
+ dirname: path.dirname,
3526
+ isAbsolute: path.isAbsolute,
3527
+ basename: path.basename
3528
+ };
3529
+ env = {
3530
+ cwd: process.cwd,
3531
+ homedir: os.homedir,
3532
+ tmpdir: os.tmpdir,
3533
+ getenv: (key) => process.env[key]
3534
+ };
3535
+ utils = {
3536
+ open: async (url) => {
3537
+ const { default: open } = await import("./index-nzr4mx5p.js");
3538
+ await open(url);
3539
+ }
3540
+ };
3541
+ async readFile(path2, options) {
3542
+ try {
3543
+ if (options) {
3544
+ return await fs.readFile(path2, "utf-8");
3545
+ }
3546
+ return await fs.readFile(path2);
3547
+ } catch (error) {
3548
+ if (this.isEnoent(error))
3549
+ return null;
3550
+ throw error;
3551
+ }
3552
+ }
3553
+ async writeFile(filePath, data) {
3554
+ const dir = path.dirname(filePath);
3555
+ if (dir) {
3556
+ await fs.mkdir(dir, { recursive: true });
3557
+ }
3558
+ await fs.writeFile(filePath, data);
3559
+ }
3560
+ async appendFile(filePath, data) {
3561
+ const dir = path.dirname(filePath);
3562
+ if (dir) {
3563
+ await fs.mkdir(dir, { recursive: true });
3564
+ }
3565
+ await fs.appendFile(filePath, data);
3566
+ }
3567
+ async readdir(dirPath) {
3568
+ try {
3569
+ return await fs.readdir(dirPath);
3570
+ } catch (error) {
3571
+ if (this.isEnoent(error))
3572
+ return [];
3573
+ throw error;
3574
+ }
3411
3575
  }
3412
- if (status === undefined) {
3413
- const connectivity = describeConnectivityError(error);
3414
- if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
3415
- message = `${message}: ${connectivity.message}`;
3576
+ async readdirEntries(dirPath) {
3577
+ try {
3578
+ return await fs.readdir(dirPath, { withFileTypes: true });
3579
+ } catch (error) {
3580
+ if (this.isEnoent(error))
3581
+ return [];
3582
+ throw error;
3416
3583
  }
3417
3584
  }
3418
- const permission = status === undefined ? describePermissionError(error) : undefined;
3419
- if (permission) {
3420
- if (permission.message !== message && !message.includes(permission.message)) {
3421
- message = `${message}: ${permission.message}`;
3422
- }
3423
- if (!message.includes(permission.instructions)) {
3424
- const punctuated = message.endsWith(".") ? message : `${message}.`;
3425
- message = `${punctuated} ${permission.instructions}`;
3585
+ async stat(filePath) {
3586
+ try {
3587
+ const stats = await fs.stat(filePath);
3588
+ return {
3589
+ isFile: () => stats.isFile(),
3590
+ isDirectory: () => stats.isDirectory(),
3591
+ size: stats.size,
3592
+ mtimeMs: stats.mtimeMs,
3593
+ ctimeMs: stats.ctimeMs
3594
+ };
3595
+ } catch (error) {
3596
+ if (this.isEnoent(error))
3597
+ return null;
3598
+ throw error;
3426
3599
  }
3427
3600
  }
3428
- let details = rawMessage;
3429
- if (rawBody) {
3430
- if (parsedBody) {
3431
- const extra = {};
3432
- if (parsedBody.errorCode)
3433
- extra.errorCode = parsedBody.errorCode;
3434
- if (parsedBody.detail)
3435
- extra.detail = parsedBody.detail;
3436
- if (parsedBody.details)
3437
- extra.details = parsedBody.details;
3438
- if (parsedBody.errors != null)
3439
- extra.errors = parsedBody.errors;
3440
- if (parsedBody.data && typeof parsedBody.data === "object" && Object.keys(parsedBody.data).length > 0) {
3441
- extra.data = parsedBody.data;
3601
+ async exists(filePath) {
3602
+ return existsSync(filePath);
3603
+ }
3604
+ async mkdir(dirPath) {
3605
+ await fs.mkdir(dirPath, { recursive: true });
3606
+ }
3607
+ async acquireLock(lockPath) {
3608
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
3609
+ const lockFile = `${canonicalPath}.lock`;
3610
+ const ownerId = randomUUID();
3611
+ const start = Date.now();
3612
+ while (true) {
3613
+ try {
3614
+ await fs.writeFile(lockFile, ownerId, { flag: "wx" });
3615
+ return this.createLockRelease(lockFile, ownerId);
3616
+ } catch (error) {
3617
+ if (!this.hasErrnoCode(error, "EEXIST")) {
3618
+ throw error;
3619
+ }
3620
+ const stats = await fs.stat(lockFile).catch(() => null);
3621
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
3622
+ const reclaimed = await fs.rm(lockFile, { force: true }).then(() => true).catch(() => false);
3623
+ if (reclaimed)
3624
+ continue;
3625
+ }
3626
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
3627
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
3628
+ }
3629
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
3442
3630
  }
3443
- details = Object.keys(extra).length > 0 ? JSON.stringify(extra) : rawBody;
3444
- } else {
3445
- details = rawBody;
3446
3631
  }
3447
- } else if (typeof err.message === "string") {
3448
- details = err.message;
3449
- } else {
3450
- details = describeThrownValue(error);
3451
- }
3452
- const context = {};
3453
- if (classificationStatus) {
3454
- context.httpStatus = classificationStatus;
3455
3632
  }
3456
- if (parsedBody?.errorCode && typeof parsedBody.errorCode === "string") {
3457
- context.errorCode = parsedBody.errorCode;
3458
- } else if (parsedBody?.code && typeof parsedBody.code === "string") {
3459
- context.errorCode = parsedBody.code;
3633
+ async canonicalizeLockTarget(lockPath) {
3634
+ const absolute = path.resolve(lockPath);
3635
+ const fullReal = await fs.realpath(absolute).catch(() => null);
3636
+ if (fullReal)
3637
+ return fullReal;
3638
+ const parent = path.dirname(absolute);
3639
+ const base = path.basename(absolute);
3640
+ const canonicalParent = await fs.realpath(parent).catch(() => parent);
3641
+ return path.join(canonicalParent, base);
3460
3642
  }
3461
- if (parsedBody?.requestId && typeof parsedBody.requestId === "string") {
3462
- context.requestId = parsedBody.requestId;
3643
+ createLockRelease(lockFile, ownerId) {
3644
+ const heartbeatStart = Date.now();
3645
+ let heartbeatTimer;
3646
+ let stopped = false;
3647
+ const stopHeartbeat = () => {
3648
+ stopped = true;
3649
+ if (heartbeatTimer)
3650
+ clearTimeout(heartbeatTimer);
3651
+ };
3652
+ const scheduleNextHeartbeat = () => {
3653
+ if (stopped)
3654
+ return;
3655
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
3656
+ stopped = true;
3657
+ return;
3658
+ }
3659
+ heartbeatTimer = setTimeout(() => {
3660
+ runHeartbeat();
3661
+ }, LOCK_HEARTBEAT_MS);
3662
+ heartbeatTimer.unref?.();
3663
+ };
3664
+ const runHeartbeat = async () => {
3665
+ if (stopped)
3666
+ return;
3667
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
3668
+ if (stopped)
3669
+ return;
3670
+ if (current !== ownerId) {
3671
+ stopped = true;
3672
+ return;
3673
+ }
3674
+ const now = Date.now() / 1000;
3675
+ await fs.utimes(lockFile, now, now).catch(() => {});
3676
+ scheduleNextHeartbeat();
3677
+ };
3678
+ scheduleNextHeartbeat();
3679
+ let released = false;
3680
+ return async () => {
3681
+ if (released)
3682
+ return;
3683
+ released = true;
3684
+ stopHeartbeat();
3685
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
3686
+ if (current === ownerId) {
3687
+ await fs.rm(lockFile, { force: true });
3688
+ }
3689
+ };
3463
3690
  }
3464
- if (parsedBody?.traceId && typeof parsedBody.traceId === "string") {
3465
- context.traceId = parsedBody.traceId;
3691
+ async rm(filePath) {
3692
+ await fs.rm(filePath, { recursive: true, force: true });
3466
3693
  }
3467
- if (permission?.path !== undefined) {
3468
- context.path = permission.path;
3694
+ async rename(oldPath, newPath) {
3695
+ await fs.rename(oldPath, newPath);
3469
3696
  }
3470
- if (status === 429) {
3471
- const resp = response;
3472
- const headersObj = resp?.headers;
3473
- let retryAfterValue;
3474
- if (headersObj && typeof headersObj === "object" && typeof headersObj.get === "function") {
3475
- retryAfterValue = headersObj.get("retry-after") ?? undefined;
3697
+ async isSymbolicLink(filePath) {
3698
+ try {
3699
+ return (await fs.lstat(filePath)).isSymbolicLink();
3700
+ } catch (error) {
3701
+ if (this.isEnoent(error) || this.hasErrnoCode(error, "ENOTDIR")) {
3702
+ return false;
3703
+ }
3704
+ throw error;
3476
3705
  }
3477
- if (!retryAfterValue && headersObj && typeof headersObj === "object") {
3478
- const headers = headersObj;
3479
- retryAfterValue = headers["retry-after"] ?? headers["Retry-After"];
3706
+ }
3707
+ async hashFile(filePath) {
3708
+ let handle;
3709
+ try {
3710
+ handle = await fs.open(filePath, "r");
3711
+ } catch (error) {
3712
+ if (this.isEnoent(error))
3713
+ return null;
3714
+ throw error;
3480
3715
  }
3481
- if (retryAfterValue) {
3482
- const seconds = Number(retryAfterValue);
3483
- if (!Number.isNaN(seconds)) {
3484
- context.retryAfter = seconds;
3485
- retry = retryHintForRetryAfter(seconds);
3716
+ const buffer = hashBuffers.pop() ?? Buffer.allocUnsafe(HASH_CHUNK_BYTES);
3717
+ try {
3718
+ const opened = await handle.stat();
3719
+ const stats = {
3720
+ isFile: () => opened.isFile(),
3721
+ isDirectory: () => opened.isDirectory(),
3722
+ size: opened.size,
3723
+ mtimeMs: opened.mtimeMs,
3724
+ ctimeMs: opened.ctimeMs
3725
+ };
3726
+ const hash = createHash("sha256");
3727
+ let size = 0;
3728
+ for (;; ) {
3729
+ const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, null);
3730
+ if (bytesRead === 0)
3731
+ break;
3732
+ hash.update(buffer.subarray(0, bytesRead));
3733
+ size += bytesRead;
3486
3734
  }
3735
+ return { sha256: hash.digest("hex"), size, stats };
3736
+ } finally {
3737
+ if (hashBuffers.length < HASH_BUFFERS_KEPT) {
3738
+ hashBuffers.push(buffer);
3739
+ }
3740
+ await handle.close();
3487
3741
  }
3488
3742
  }
3489
- const hasContext = Object.keys(context).length > 0;
3490
- let parsedErrors;
3491
- if (parsedBody?.errors && typeof parsedBody.errors === "object") {
3492
- const errors = {};
3493
- for (const [field, raw] of Object.entries(parsedBody.errors)) {
3494
- if (Array.isArray(raw)) {
3495
- const messages = raw.map((entry) => {
3496
- if (typeof entry === "string")
3497
- return entry;
3498
- if (entry && typeof entry === "object" && typeof entry.message === "string") {
3499
- return entry.message;
3500
- }
3501
- return String(entry);
3502
- }).filter(Boolean);
3503
- if (messages.length > 0)
3504
- errors[field] = messages;
3505
- } else if (typeof raw === "string") {
3506
- errors[field] = [raw];
3507
- }
3743
+ async realpath(filePath) {
3744
+ try {
3745
+ return await fs.realpath(filePath);
3746
+ } catch (error) {
3747
+ if (this.isEnoent(error))
3748
+ return filePath;
3749
+ throw error;
3508
3750
  }
3509
- if (Object.keys(errors).length > 0)
3510
- parsedErrors = errors;
3511
3751
  }
3512
- return {
3513
- result,
3514
- errorCode: classification.errorCode,
3515
- message,
3516
- retry,
3517
- details,
3518
- ...hasContext ? { context } : {},
3519
- ...parsedErrors ? { parsedErrors } : {}
3520
- };
3521
- }
3522
- function extractErrorMessageSync(error) {
3523
- if (error instanceof Error) {
3524
- return error.message;
3752
+ async getTempDir() {
3753
+ return await fs.mkdtemp(path.join(os.tmpdir(), "uipath-fs-"));
3525
3754
  }
3526
- if (typeof error === "object" && error !== null) {
3527
- if ("status" in error && error.status === 401) {
3528
- return DEFAULT_401;
3755
+ async copyDirectory(sourcePath, destPath) {
3756
+ const sourceStats = await this.stat(sourcePath);
3757
+ if (!sourceStats) {
3758
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
3529
3759
  }
3530
- if ("message" in error && typeof error.message === "string") {
3531
- return error.message;
3760
+ if (!sourceStats.isDirectory()) {
3761
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
3762
+ }
3763
+ await this.mkdir(destPath);
3764
+ const entries = await this.readdir(sourcePath);
3765
+ for (const entry of entries) {
3766
+ const srcEntry = path.join(sourcePath, entry);
3767
+ const destEntry = path.join(destPath, entry);
3768
+ const entryStats = await this.stat(srcEntry);
3769
+ if (!entryStats)
3770
+ continue;
3771
+ if (entryStats.isDirectory()) {
3772
+ await this.copyDirectory(srcEntry, destEntry);
3773
+ } else if (entryStats.isFile()) {
3774
+ const content = await this.readFile(srcEntry);
3775
+ if (content !== null) {
3776
+ await this.writeFile(destEntry, content);
3777
+ }
3778
+ }
3532
3779
  }
3533
3780
  }
3534
- return describeThrownValue(error);
3535
- }
3536
- // ../common/src/exit-code.ts
3537
- function setExitCode(code) {
3538
- process.exitCode = code;
3781
+ isEnoent(error) {
3782
+ return this.hasErrnoCode(error, "ENOENT");
3783
+ }
3784
+ hasErrnoCode(error, code) {
3785
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
3786
+ }
3539
3787
  }
3540
3788
 
3789
+ // ../filesystem/src/index.ts
3790
+ var fsInstance = new NodeFileSystem;
3791
+ var getFileSystem = () => fsInstance;
3792
+
3541
3793
  // ../common/src/output-context.ts
3542
3794
  function createStorage() {
3543
3795
  const [error, mod] = catchError(() => __require("node:async_hooks"));
@@ -3571,8 +3823,8 @@ function getOutputSink() {
3571
3823
 
3572
3824
  // ../common/src/logger.ts
3573
3825
  var logFilePathSlot = singleton("logFilePath");
3574
- function setGlobalLogFilePath(path2) {
3575
- logFilePathSlot.set(path2);
3826
+ function setGlobalLogFilePath(path) {
3827
+ logFilePathSlot.set(path);
3576
3828
  }
3577
3829
  function getGlobalLogFilePath() {
3578
3830
  return logFilePathSlot.get("");
@@ -3640,14 +3892,14 @@ class SimpleLogger {
3640
3892
  return this.fileLoggingEnabled || !!getGlobalLogFilePath();
3641
3893
  }
3642
3894
  writeToFile(formatted) {
3643
- const path2 = this.logFilePath || getGlobalLogFilePath();
3644
- if (!path2)
3895
+ const path = this.logFilePath || getGlobalLogFilePath();
3896
+ if (!path)
3645
3897
  return;
3646
3898
  const timestamp = new Date().toISOString();
3647
3899
  this.pendingWrites = Promise.all([
3648
3900
  this.pendingWrites,
3649
3901
  this.pendingInit
3650
- ]).then(() => getFileSystem().appendFile(path2, `${timestamp} ${formatted}`).catch(() => {}));
3902
+ ]).then(() => getFileSystem().appendFile(path, `${timestamp} ${formatted}`).catch(() => {}));
3651
3903
  }
3652
3904
  write(formatted) {
3653
3905
  if (this.isFileLoggingActive()) {
@@ -3697,17 +3949,17 @@ class SimpleLogger {
3697
3949
  setGlobalLogFilePath("");
3698
3950
  }
3699
3951
  }
3700
- setLogFile(path2) {
3701
- this.logFilePath = path2;
3702
- setGlobalLogFilePath(path2);
3703
- if (!path2)
3952
+ setLogFile(path) {
3953
+ this.logFilePath = path;
3954
+ setGlobalLogFilePath(path);
3955
+ if (!path)
3704
3956
  return;
3705
3957
  this.fileLoggingEnabled = true;
3706
- const fs2 = getFileSystem();
3958
+ const fs = getFileSystem();
3707
3959
  this.pendingInit = (async () => {
3708
3960
  const [error] = await catchError((async () => {
3709
- await fs2.mkdir(fs2.path.dirname(path2));
3710
- await fs2.writeFile(path2, "");
3961
+ await fs.mkdir(fs.path.dirname(path));
3962
+ await fs.writeFile(path, "");
3711
3963
  })());
3712
3964
  if (error)
3713
3965
  this.fileLoggingEnabled = false;
@@ -3755,18 +4007,111 @@ function getLogFilePath() {
3755
4007
  return logger.getLogFilePath();
3756
4008
  }
3757
4009
 
4010
+ // ../common/src/timings.ts
4011
+ var TIMINGS_ENV_VAR = "UIP_TIMINGS";
4012
+ function createStorage2() {
4013
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
4014
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
4015
+ return {
4016
+ getStore: () => {
4017
+ return;
4018
+ },
4019
+ run: (_store, fn) => fn()
4020
+ };
4021
+ }
4022
+ return new mod.AsyncLocalStorage;
4023
+ }
4024
+ var storageSlot = singleton("TimingStorage");
4025
+ var stateSlot = singleton("Timings");
4026
+ var rootStartedSlot = singleton("TimingsRootStarted");
4027
+ var longLivedHostSlot = singleton("TimingsLongLivedHost");
4028
+ var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
4029
+ function newState(baseline) {
4030
+ return { baseline, httpMs: 0, httpCalls: 0 };
4031
+ }
4032
+ function getState() {
4033
+ const scoped = storage.getStore();
4034
+ if (scoped) {
4035
+ return scoped;
4036
+ }
4037
+ const pinned = livePinnedState();
4038
+ if (pinned !== undefined) {
4039
+ return pinned;
4040
+ }
4041
+ return newState(processStartIsInvocationStart() ? 0 : performance.now());
4042
+ }
4043
+ function livePinnedState() {
4044
+ const pinned = stateSlot.get();
4045
+ return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
4046
+ }
4047
+ function processStartIsInvocationStart() {
4048
+ return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
4049
+ }
4050
+ function timingsEnabled() {
4051
+ if (typeof process === "undefined") {
4052
+ return false;
4053
+ }
4054
+ const value = process.env?.[TIMINGS_ENV_VAR];
4055
+ if (value === undefined) {
4056
+ return false;
4057
+ }
4058
+ const normalized = value.trim().toLowerCase();
4059
+ return normalized === "1" || normalized === "true";
4060
+ }
4061
+ function recordExitCode(exitCode) {
4062
+ if (!timingsEnabled()) {
4063
+ return;
4064
+ }
4065
+ getState().exitCode = exitCode;
4066
+ }
4067
+ function invocationStartedAt() {
4068
+ return new Date(performance.timeOrigin + getState().baseline);
4069
+ }
4070
+ function invocationElapsedMs() {
4071
+ return performance.now() - getState().baseline;
4072
+ }
4073
+ function markCommandStart() {
4074
+ if (!timingsEnabled()) {
4075
+ return;
4076
+ }
4077
+ getState().commandStart = performance.now();
4078
+ }
4079
+ function recordCommandDuration(durationMs) {
4080
+ if (!timingsEnabled()) {
4081
+ return;
4082
+ }
4083
+ getState().commandMs = durationMs;
4084
+ }
4085
+
4086
+ // ../common/src/exit-code.ts
4087
+ function setExitCode(code) {
4088
+ process.exitCode = code;
4089
+ recordExitCode(code);
4090
+ }
4091
+ var GENERIC_FAILURE_EXIT_CODE = 1;
4092
+ function recordCommandExit(code) {
4093
+ if (code === GENERIC_FAILURE_EXIT_CODE && getExitCode() !== 0) {
4094
+ return;
4095
+ }
4096
+ setExitCode(code);
4097
+ }
4098
+ function getExitCode() {
4099
+ const code = process.exitCode;
4100
+ return typeof code === "number" ? code : 0;
4101
+ }
4102
+
3758
4103
  // ../common/src/output-codecs.ts
3759
4104
  var yamlSlot = singleton("YamlCodec");
3760
4105
  var jmespathSlot = singleton("JmespathCodec");
3761
4106
  async function loadOutputCodecsAsync(needed) {
3762
4107
  const loads = [];
3763
4108
  if (needed.yaml && yamlSlot.get() === undefined) {
3764
- loads.push(import("./js-yaml-87cdx6bm.js").then((mod) => {
4109
+ loads.push(import("./js-yaml-a2bk27p6.js").then((mod) => {
3765
4110
  yamlSlot.set(mod);
3766
4111
  }));
3767
4112
  }
3768
4113
  if (needed.filter && jmespathSlot.get() === undefined) {
3769
- loads.push(import("./jmespath-e4a59c8w.js").then((m)=>__toESM(m.default,1)).then((mod) => {
4114
+ loads.push(import("./jmespath-wwym30dp.js").then((m)=>__toESM(m.default,1)).then((mod) => {
3770
4115
  jmespathSlot.set(mod);
3771
4116
  }));
3772
4117
  }
@@ -3791,6 +4136,16 @@ function getOutputFilter() {
3791
4136
  return filterSlot.get();
3792
4137
  }
3793
4138
 
4139
+ // ../common/src/result-types.ts
4140
+ var RESULTS = {
4141
+ Success: "Success",
4142
+ Failure: "Failure",
4143
+ ConfigError: "ConfigError",
4144
+ AuthenticationError: "AuthenticationError",
4145
+ ValidationError: "ValidationError",
4146
+ TimeoutError: "TimeoutError"
4147
+ };
4148
+
3794
4149
  // ../common/src/telemetry/command-terminal.ts
3795
4150
  var recordedFailureSlot = singleton("CommandTelemetryFailure");
3796
4151
  var AUTH_ERROR_CODES = new Set([
@@ -3909,17 +4264,8 @@ function terminalSignalFor(input, outcome) {
3909
4264
  }
3910
4265
  return outcome === "cancelled" ? "SIGINT" : undefined;
3911
4266
  }
3912
- function classifyHttpStatus(status) {
3913
- if (status === 401 || status === 403) {
3914
- return "auth";
3915
- }
3916
- if (status === 400 || status === 409 || status === 422) {
3917
- return "validation";
3918
- }
3919
- if (status === 408) {
3920
- return "timeout";
3921
- }
3922
- return "network_http";
4267
+ function classifyFailingHttpStatus(status) {
4268
+ return classifyFromErrorCode(classifyHttpStatus(status)?.errorCode) ?? "network_http";
3923
4269
  }
3924
4270
  function classifyFromResult(result) {
3925
4271
  switch (result) {
@@ -3999,7 +4345,7 @@ function classifyError2(input) {
3999
4345
  }
4000
4346
  const status = recorded?.context?.httpStatus ?? findHttpStatusInGraph(input.error);
4001
4347
  if (status !== undefined) {
4002
- return classifyHttpStatus(status);
4348
+ return classifyFailingHttpStatus(status);
4003
4349
  }
4004
4350
  return classifyFromResult(recorded?.result) ?? classifyFromErrorCode(recorded?.errorCode) ?? classifyFromError(input.error) ?? "unknown";
4005
4351
  }
@@ -4031,6 +4377,7 @@ function buildCommandTerminalTelemetryProperties(input) {
4031
4377
  var CommonTelemetryEvents = {
4032
4378
  Start: "Application.Start",
4033
4379
  Error: "Application.Error",
4380
+ ProjectActivity: "Cli.ProjectActivity",
4034
4381
  ShipSucceeded: "Cli.ShipSucceeded"
4035
4382
  };
4036
4383
 
@@ -4351,6 +4698,12 @@ function getTelemetryOperationId() {
4351
4698
  telemetryOperationIdSlot.set(generated);
4352
4699
  return generated;
4353
4700
  }
4701
+ // ../common/src/telemetry/global-telemetry-properties.ts
4702
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
4703
+ function getGlobalTelemetryProperties() {
4704
+ return telemetryPropsSlot.get();
4705
+ }
4706
+
4354
4707
  // ../common/src/telemetry/span-clock.ts
4355
4708
  function startSpanClock() {
4356
4709
  const started = performance.now();
@@ -4542,87 +4895,21 @@ class TelemetryService {
4542
4895
  return hex;
4543
4896
  }
4544
4897
  }
4545
- // ../common/src/timings.ts
4546
- var TIMINGS_ENV_VAR = "UIP_TIMINGS";
4547
- function createStorage2() {
4548
- const [error, mod] = catchError(() => __require("node:async_hooks"));
4549
- if (error || typeof mod?.AsyncLocalStorage !== "function") {
4550
- return {
4551
- getStore: () => {
4552
- return;
4553
- },
4554
- run: (_store, fn) => fn()
4555
- };
4556
- }
4557
- return new mod.AsyncLocalStorage;
4558
- }
4559
- var storageSlot = singleton("TimingStorage");
4560
- var stateSlot = singleton("Timings");
4561
- var rootStartedSlot = singleton("TimingsRootStarted");
4562
- var longLivedHostSlot = singleton("TimingsLongLivedHost");
4563
- var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
4564
- function newState(baseline) {
4565
- return { baseline, httpMs: 0, httpCalls: 0 };
4566
- }
4567
- function getState() {
4568
- const scoped = storage.getStore();
4569
- if (scoped) {
4570
- return scoped;
4571
- }
4572
- const pinned = livePinnedState();
4573
- if (pinned !== undefined) {
4574
- return pinned;
4575
- }
4576
- return newState(processStartIsInvocationStart() ? 0 : performance.now());
4577
- }
4578
- function livePinnedState() {
4579
- const pinned = stateSlot.get();
4580
- return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
4581
- }
4582
- function processStartIsInvocationStart() {
4583
- return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
4584
- }
4585
- function timingsEnabled() {
4586
- if (typeof process === "undefined") {
4587
- return false;
4588
- }
4589
- const value = process.env?.[TIMINGS_ENV_VAR];
4590
- if (value === undefined) {
4591
- return false;
4592
- }
4593
- const normalized = value.trim().toLowerCase();
4594
- return normalized === "1" || normalized === "true";
4595
- }
4596
- function recordExitCode(exitCode) {
4597
- if (!timingsEnabled()) {
4598
- return;
4599
- }
4600
- getState().exitCode = exitCode;
4601
- }
4602
- function invocationStartedAt() {
4603
- return new Date(performance.timeOrigin + getState().baseline);
4604
- }
4605
- function invocationElapsedMs() {
4606
- return performance.now() - getState().baseline;
4607
- }
4608
- function markCommandStart() {
4609
- if (!timingsEnabled()) {
4610
- return;
4611
- }
4612
- getState().commandStart = performance.now();
4613
- }
4614
- function recordCommandDuration(durationMs) {
4615
- if (!timingsEnabled()) {
4616
- return;
4617
- }
4618
- getState().commandMs = durationMs;
4619
- }
4620
4898
  // ../common/src/telemetry/proxy-http-agent.ts
4621
4899
  var slot = singleton("ProxyAuthHttpsAgent");
4622
4900
 
4623
4901
  // ../common/src/telemetry/node-appinsights-telemetry-provider.ts
4624
4902
  var providerSlot = singleton("TelemetryProvider");
4625
4903
 
4904
+ // ../common/src/telemetry/telemetry-config.ts
4905
+ function isTelemetryDisabled() {
4906
+ const value = process.env.UIPATH_TELEMETRY_DISABLED;
4907
+ return value === "1" || value === "true";
4908
+ }
4909
+ function isProjectTelemetryDisabled() {
4910
+ return isTelemetryDisabled() || process.env.UIPATH_PROJECT_TELEMETRY_DISABLED === "1" || process.env.UIPATH_PROJECT_TELEMETRY_DISABLED === "true";
4911
+ }
4912
+
4626
4913
  // ../common/src/telemetry/telemetry-spool.ts
4627
4914
  var sidecarEntrySlot = singleton("TelemetrySidecarEntry");
4628
4915
  var MAX_SPOOL_AGE_MS = 72 * 60 * 60 * 1000;
@@ -4647,67 +4934,26 @@ function getTelemetryInstance() {
4647
4934
  return global;
4648
4935
  if (!_localTelemetryInstance) {
4649
4936
  _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
4650
- setGlobalTelemetryInstance(_localTelemetryInstance);
4651
- }
4652
- return _localTelemetryInstance;
4653
- }
4654
- var telemetry = new Proxy({}, {
4655
- get(_, prop) {
4656
- const instance = getTelemetryInstance();
4657
- const value = instance[prop];
4658
- return typeof value === "function" ? value.bind(instance) : value;
4659
- }
4660
- });
4661
-
4662
- // ../common/src/formatter.ts
4663
- var ANSI_STYLES = {
4664
- red: "\x1B[31m",
4665
- dim: "\x1B[2m"
4666
- };
4667
- var ANSI_RESET = "\x1B[0m";
4668
- function styleLine(line, style) {
4669
- return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
4670
- }
4671
- var CLI_ERROR_CODES = [
4672
- "invalid_argument",
4673
- "authentication_required",
4674
- "permission_denied",
4675
- "local_permission_denied",
4676
- "not_found",
4677
- "rate_limited",
4678
- "network_error",
4679
- "timeout",
4680
- "server_error",
4681
- "method_not_allowed",
4682
- "not_supported",
4683
- "configuration_error",
4684
- "execution_failed",
4685
- "unknown_error"
4686
- ];
4687
- var RETRY_HINTS = [
4688
- "RetryWillNotFix",
4689
- "RetryLater",
4690
- "RetryAfter1Second",
4691
- "RetryAfter10Seconds",
4692
- "RetryAfter30Seconds",
4693
- "RetryAfter60Seconds"
4694
- ];
4695
- var CLI_ERROR_CODE_VALUES = new Set(CLI_ERROR_CODES);
4696
- var RETRY_HINT_VALUES = new Set(RETRY_HINTS);
4697
- function isCliErrorCode(value) {
4698
- return typeof value === "string" && CLI_ERROR_CODE_VALUES.has(value);
4699
- }
4700
- function isRetryHint(value) {
4701
- return typeof value === "string" && RETRY_HINT_VALUES.has(value);
4702
- }
4703
- var RESULTS = {
4704
- Success: "Success",
4705
- Failure: "Failure",
4706
- ConfigError: "ConfigError",
4707
- AuthenticationError: "AuthenticationError",
4708
- ValidationError: "ValidationError",
4709
- TimeoutError: "TimeoutError"
4937
+ setGlobalTelemetryInstance(_localTelemetryInstance);
4938
+ }
4939
+ return _localTelemetryInstance;
4940
+ }
4941
+ var telemetry = new Proxy({}, {
4942
+ get(_, prop) {
4943
+ const instance = getTelemetryInstance();
4944
+ const value = instance[prop];
4945
+ return typeof value === "function" ? value.bind(instance) : value;
4946
+ }
4947
+ });
4948
+ // ../common/src/formatter.ts
4949
+ var ANSI_STYLES = {
4950
+ red: "\x1B[31m",
4951
+ dim: "\x1B[2m"
4710
4952
  };
4953
+ var ANSI_RESET = "\x1B[0m";
4954
+ function styleLine(line, style) {
4955
+ return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
4956
+ }
4711
4957
  var EXIT_CODES = {
4712
4958
  Success: 0,
4713
4959
  Failure: 1,
@@ -4716,6 +4962,9 @@ var EXIT_CODES = {
4716
4962
  ValidationError: 3,
4717
4963
  TimeoutError: 4
4718
4964
  };
4965
+ function exitCodeForResult(result) {
4966
+ return EXIT_CODES[result] ?? EXIT_CODES.Failure;
4967
+ }
4719
4968
  function escapeNonAscii(jsonText) {
4720
4969
  return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
4721
4970
  const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
@@ -5391,8 +5640,8 @@ function carriesOnlyNulls(value) {
5391
5640
  }
5392
5641
  return false;
5393
5642
  }
5394
- function nameList(names, cap2 = 12) {
5395
- const shown = names.slice(0, cap2).map((n) => `\`${n}\``);
5643
+ function nameList(names, cap = 12) {
5644
+ const shown = names.slice(0, cap).map((n) => `\`${n}\``);
5396
5645
  const rest = names.length - shown.length;
5397
5646
  return shown.join(", ") + (rest > 0 ? `, and ${rest} more` : "");
5398
5647
  }
@@ -5529,40 +5778,11 @@ function defaultErrorCodeForResult(result) {
5529
5778
  return "unknown_error";
5530
5779
  }
5531
5780
  }
5532
- function parseHttpStatusFromMessage2(message) {
5533
- const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
5534
- if (!match)
5535
- return;
5536
- const status = Number(match[1]);
5537
- return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
5538
- }
5539
- function defaultErrorCodeForHttpStatus(status) {
5540
- if (status === undefined)
5541
- return;
5542
- if (status === 400 || status === 409 || status === 422) {
5543
- return "invalid_argument";
5544
- }
5545
- if (status === 401)
5546
- return "authentication_required";
5547
- if (status === 403)
5548
- return "permission_denied";
5549
- if (status === 404)
5550
- return "not_found";
5551
- if (status === 405)
5552
- return "method_not_allowed";
5553
- if (status === 408)
5554
- return "timeout";
5555
- if (status === 429)
5556
- return "rate_limited";
5557
- if (status >= 500 && status < 600)
5558
- return "server_error";
5559
- return;
5560
- }
5561
5781
  var LOCAL_PERMISSION_TEXT_PATTERN = new RegExp(`(?:\\b|\\()(?:${[...LOCAL_PERMISSION_ERROR_CODES].join("|")})(?::\\s|\\))`);
5562
5782
  function defaultErrorCodeForFailure(data) {
5563
5783
  if (data.Result === RESULTS.Failure) {
5564
- const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
5565
- const errorCode = defaultErrorCodeForHttpStatus(status);
5784
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage(data.Message);
5785
+ const errorCode = classifyHttpStatus(status)?.errorCode;
5566
5786
  if (errorCode)
5567
5787
  return errorCode;
5568
5788
  if (status === undefined && (LOCAL_PERMISSION_TEXT_PATTERN.test(data.Message) || LOCAL_PERMISSION_TEXT_PATTERN.test(data.Instructions))) {
@@ -5571,17 +5791,6 @@ function defaultErrorCodeForFailure(data) {
5571
5791
  }
5572
5792
  return defaultErrorCodeForResult(data.Result);
5573
5793
  }
5574
- function defaultRetryForErrorCode(errorCode) {
5575
- switch (errorCode) {
5576
- case "network_error":
5577
- case "rate_limited":
5578
- case "server_error":
5579
- case "timeout":
5580
- return "RetryLater";
5581
- default:
5582
- return "RetryWillNotFix";
5583
- }
5584
- }
5585
5794
  var OutputFormatter;
5586
5795
  ((OutputFormatter) => {
5587
5796
  function success(data, options) {
@@ -5613,7 +5822,7 @@ var OutputFormatter;
5613
5822
  data.Log ??= getLogFilePath() || undefined;
5614
5823
  data.ErrorCode ??= defaultErrorCodeForFailure(data);
5615
5824
  data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
5616
- const exitCode = EXIT_CODES[data.Result] ?? 1;
5825
+ const exitCode = exitCodeForResult(data.Result);
5617
5826
  setExitCode(exitCode);
5618
5827
  recordCommandFailureTelemetry({
5619
5828
  result: data.Result,
@@ -5707,6 +5916,41 @@ var OutputFormatter;
5707
5916
  }
5708
5917
  OutputFormatter.formatToString = formatToString;
5709
5918
  })(OutputFormatter ||= {});
5919
+
5920
+ // ../common/src/sdk-user-agent.ts
5921
+ var USER_AGENT_HEADER = "User-Agent";
5922
+ var AGENT_PROPERTY = BaseDimensions.Agent;
5923
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
5924
+ function splitUserAgentTokens(value) {
5925
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
5926
+ }
5927
+ function appendUserAgentToken(value, userAgent) {
5928
+ const tokens = splitUserAgentTokens(value);
5929
+ const seen = new Set(tokens);
5930
+ for (const token of splitUserAgentTokens(userAgent)) {
5931
+ if (!seen.has(token)) {
5932
+ tokens.push(token);
5933
+ seen.add(token);
5934
+ }
5935
+ }
5936
+ return tokens.join(" ");
5937
+ }
5938
+ function getEffectiveUserAgent(userAgent) {
5939
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
5940
+ }
5941
+ function getHeaderName(headers, headerName) {
5942
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
5943
+ }
5944
+ function getSdkUserAgentToken(pkg) {
5945
+ const packageName = pkg.name.replace(/^@uipath\//, "");
5946
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
5947
+ }
5948
+ function addSdkUserAgentHeader(headers, userAgent) {
5949
+ const result = { ...headers ?? {} };
5950
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
5951
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
5952
+ return result;
5953
+ }
5710
5954
  // ../common/src/command-examples.ts
5711
5955
  var examplesByCommand = new WeakMap;
5712
5956
  Command.prototype.examples = function(examples) {
@@ -5725,6 +5969,228 @@ Command.prototype.previewCommand = function(nameAndArgs, opts) {
5725
5969
  return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
5726
5970
  };
5727
5971
 
5972
+ // ../common/src/pass-through-tail.ts
5973
+ function maybeOption(arg) {
5974
+ return arg.length > 1 && arg[0] === "-";
5975
+ }
5976
+ function tokenizeTail(cmd, tail) {
5977
+ const find = (flag) => cmd.options.find((option) => option.long === flag || option.short === flag);
5978
+ const digitShort = cmd.options.some((option) => option.short !== undefined && /^-\d$/.test(option.short));
5979
+ const negativeNumber = (arg) => !digitShort && /^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg);
5980
+ const tokens = [];
5981
+ let firstUnknown = -1;
5982
+ let sentinel = -1;
5983
+ let variadic;
5984
+ let group;
5985
+ let groupIndex = 0;
5986
+ let i = 0;
5987
+ while (i < tail.length || group !== undefined) {
5988
+ const index = group === undefined ? i : groupIndex;
5989
+ const arg = group ?? tail[i++];
5990
+ group = undefined;
5991
+ if (arg === "--") {
5992
+ sentinel = index;
5993
+ tokens.push({ kind: "sentinel", index });
5994
+ for (let j = i;j < tail.length; j++) {
5995
+ tokens.push({
5996
+ kind: "operand",
5997
+ index: j,
5998
+ text: tail[j],
5999
+ literal: true
6000
+ });
6001
+ }
6002
+ break;
6003
+ }
6004
+ if (variadic && (!maybeOption(arg) || negativeNumber(arg))) {
6005
+ tokens.push({
6006
+ kind: "option",
6007
+ index,
6008
+ text: arg,
6009
+ option: variadic,
6010
+ value: arg
6011
+ });
6012
+ continue;
6013
+ }
6014
+ variadic = undefined;
6015
+ if (maybeOption(arg)) {
6016
+ const option = find(arg);
6017
+ if (option) {
6018
+ let value;
6019
+ if (option.required) {
6020
+ value = tail[i];
6021
+ if (value !== undefined)
6022
+ i++;
6023
+ } else if (option.optional) {
6024
+ const next = tail[i];
6025
+ if (next !== undefined && (!maybeOption(next) || negativeNumber(next))) {
6026
+ value = next;
6027
+ i++;
6028
+ }
6029
+ }
6030
+ tokens.push({
6031
+ kind: "option",
6032
+ index,
6033
+ text: arg,
6034
+ option,
6035
+ ...value === undefined ? {} : { value }
6036
+ });
6037
+ variadic = option.variadic ? option : undefined;
6038
+ continue;
6039
+ }
6040
+ }
6041
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
6042
+ const option = find(`-${arg[1]}`);
6043
+ if (option) {
6044
+ if (option.required || option.optional) {
6045
+ tokens.push({
6046
+ kind: "option",
6047
+ index,
6048
+ text: arg,
6049
+ option,
6050
+ value: arg.slice(2)
6051
+ });
6052
+ } else {
6053
+ tokens.push({ kind: "option", index, text: arg, option });
6054
+ group = `-${arg.slice(2)}`;
6055
+ groupIndex = index;
6056
+ }
6057
+ continue;
6058
+ }
6059
+ }
6060
+ if (/^--[^=]+=/.test(arg)) {
6061
+ const equals = arg.indexOf("=");
6062
+ const option = find(arg.slice(0, equals));
6063
+ if (option && (option.required || option.optional)) {
6064
+ tokens.push({
6065
+ kind: "option",
6066
+ index,
6067
+ text: arg,
6068
+ option,
6069
+ value: arg.slice(equals + 1)
6070
+ });
6071
+ continue;
6072
+ }
6073
+ }
6074
+ if (maybeOption(arg) && !negativeNumber(arg)) {
6075
+ const equals = arg.startsWith("--") ? arg.indexOf("=") : -1;
6076
+ if (firstUnknown === -1)
6077
+ firstUnknown = index;
6078
+ tokens.push({
6079
+ kind: "unknown",
6080
+ index,
6081
+ text: arg,
6082
+ flag: equals > 0 ? arg.slice(0, equals) : arg,
6083
+ ...equals > 0 ? { inlineValue: arg.slice(equals + 1) } : {}
6084
+ });
6085
+ continue;
6086
+ }
6087
+ tokens.push({ kind: "operand", index, text: arg, literal: false });
6088
+ }
6089
+ return { tokens, firstUnknown, sentinel };
6090
+ }
6091
+
6092
+ // ../common/src/project-telemetry.ts
6093
+ var RESOLVER = Symbol.for("@uipath/common/projectTelemetryResolver");
6094
+ var CAPTURE = Symbol.for("@uipath/common/projectTelemetryCapture");
6095
+ var CONTEXT_RESOLVER = Symbol.for("@uipath/common/projectContextTelemetryResolver");
6096
+ var RULES = Symbol.for("@uipath/common/projectTargetRules");
6097
+ function logSkipped(what, error) {
6098
+ logger.debug(`[project-telemetry] ${what} skipped: ${error instanceof Error ? error.message : String(error)}`);
6099
+ }
6100
+ function bounded(work, what) {
6101
+ return withinProjectIdentityBudget(work, () => logSkipped(what, `no answer within ${PROJECT_IDENTITY_LOOKUP_BUDGET_MS} ms`));
6102
+ }
6103
+ async function identityWithContext(command, identity) {
6104
+ const props = projectIdentityProperties(identity);
6105
+ if (!identity.projectDirectory || isProjectTelemetryDisabled())
6106
+ return props;
6107
+ for (let node = command;node; node = node.parent ?? undefined) {
6108
+ const resolver = node[CONTEXT_RESOLVER];
6109
+ if (typeof resolver !== "function")
6110
+ continue;
6111
+ try {
6112
+ return {
6113
+ ...await resolver(identity.projectDirectory),
6114
+ ...props
6115
+ };
6116
+ } catch (error) {
6117
+ logSkipped("solution context lookup", error);
6118
+ return props;
6119
+ }
6120
+ }
6121
+ return props;
6122
+ }
6123
+ function getProjectTelemetryResolver(command) {
6124
+ for (let node = command;node; node = node.parent) {
6125
+ const resolver = node[RESOLVER];
6126
+ if (typeof resolver === "function")
6127
+ return resolver;
6128
+ }
6129
+ return;
6130
+ }
6131
+ function attachProjectTelemetryCapture(command, capture) {
6132
+ command[CAPTURE] = capture;
6133
+ }
6134
+ class ProjectTelemetrySession {
6135
+ resolver;
6136
+ command;
6137
+ target;
6138
+ props = {};
6139
+ explicit = false;
6140
+ input;
6141
+ constructor(resolver, command) {
6142
+ this.resolver = resolver;
6143
+ this.command = command;
6144
+ }
6145
+ async setTarget(path) {
6146
+ this.target = path;
6147
+ if (this.input) {
6148
+ await this.resolve({
6149
+ ...this.input,
6150
+ phase: "after",
6151
+ success: true
6152
+ });
6153
+ this.explicit = true;
6154
+ }
6155
+ }
6156
+ async setIdentity(identity) {
6157
+ try {
6158
+ const props = await bounded(identityWithContext(this.command, identity), "project identity capture");
6159
+ if (props !== undefined)
6160
+ this.setProperties(props);
6161
+ } catch (error) {
6162
+ logSkipped("project identity capture", error);
6163
+ }
6164
+ }
6165
+ setProperties(properties) {
6166
+ try {
6167
+ this.props = { ...properties };
6168
+ this.explicit = true;
6169
+ } catch (error) {
6170
+ logSkipped("project identity properties", error);
6171
+ }
6172
+ }
6173
+ properties() {
6174
+ return { ...this.props };
6175
+ }
6176
+ async resolve(input) {
6177
+ this.input = input;
6178
+ if (this.explicit)
6179
+ return;
6180
+ try {
6181
+ const props = await bounded(this.resolver({
6182
+ ...input,
6183
+ target: this.target
6184
+ }), `project identity (${input.phase})`);
6185
+ if (props !== undefined) {
6186
+ this.props = props;
6187
+ }
6188
+ } catch (error) {
6189
+ logSkipped(`project identity (${input.phase})`, error);
6190
+ }
6191
+ }
6192
+ }
6193
+
5728
6194
  // ../common/src/telemetry/command-attribution.ts
5729
6195
  var LEGACY_SKILL_NAMESPACE = "uipath:";
5730
6196
  var MAX_SKILL_NAME_LENGTH = 80;
@@ -5969,8 +6435,7 @@ var pollSignalSlot = singleton("PollSignal");
5969
6435
  var TELEMETRY_COMMAND_ARG_PREFIX = "uip.cmd.arg.";
5970
6436
  var processContext = {
5971
6437
  exit: (code) => {
5972
- recordExitCode(code);
5973
- setExitCode(code);
6438
+ recordCommandExit(code);
5974
6439
  },
5975
6440
  get pollSignal() {
5976
6441
  return pollSignalSlot.get();
@@ -5995,6 +6460,8 @@ function recordableArgValue(value, choices) {
5995
6460
  function extractCommandParams(cmd) {
5996
6461
  const params = {};
5997
6462
  forEachSuppliedArgument(cmd, (name, value, choices, defaulted) => {
6463
+ if (name === undefined)
6464
+ return;
5998
6465
  const recordable = recordableArgValue(value, choices);
5999
6466
  params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = recordable === TELEMETRY_ARG_VALUE_WITHHELD && defaulted ? TELEMETRY_ARG_VALUE_DEFAULTED : recordable;
6000
6467
  });
@@ -6010,7 +6477,8 @@ function isDefaultedPositional(cmd, index) {
6010
6477
  function forEachSuppliedArgument(cmd, visit) {
6011
6478
  const registered = cmd.registeredArguments ?? [];
6012
6479
  const processed = cmd.processedArgs ?? [];
6013
- for (let i = 0;i < registered.length; i++) {
6480
+ const bound = boundPositionalCount(cmd);
6481
+ for (let i = 0;i < bound; i++) {
6014
6482
  const name = registered[i].name();
6015
6483
  if (name && processed[i] !== undefined) {
6016
6484
  visit(name, processed[i], registered[i].argChoices, isDefaultedPositional(cmd, i));
@@ -6025,6 +6493,71 @@ function forEachSuppliedArgument(cmd, visit) {
6025
6493
  visit(key, value, choicesByAttribute.get(key), isDefaultedOption(cmd, key));
6026
6494
  }
6027
6495
  }
6496
+ forEachPassThroughToken(cmd, bound, (name, value) => {
6497
+ visit(name, value, name === undefined ? undefined : choicesByAttribute.get(name), false);
6498
+ });
6499
+ }
6500
+ function boundPositionalCount(cmd) {
6501
+ const registered = cmd.registeredArguments ?? [];
6502
+ if (registered.some((argument) => argument.variadic)) {
6503
+ return registered.length;
6504
+ }
6505
+ if ((cmd.args ?? []).length <= registered.length) {
6506
+ return registered.length;
6507
+ }
6508
+ const firstFlag = tokenizeTail(cmd, (cmd.args ?? []).slice(1)).tokens.find((token) => token.kind !== "operand")?.index ?? -1;
6509
+ return firstFlag === -1 ? registered.length : Math.min(registered.length, firstFlag + 1);
6510
+ }
6511
+ function forEachPassThroughToken(cmd, bound, visit) {
6512
+ const registered = cmd.registeredArguments ?? [];
6513
+ const fillsPositionals = !registered.some((argument) => argument.variadic);
6514
+ const { tokens, firstUnknown } = tokenizeTail(cmd, (cmd.args ?? []).slice(bound));
6515
+ const repeated = new Map;
6516
+ let nextPositional = bound;
6517
+ for (const token of tokens) {
6518
+ const pastUnknown = firstUnknown !== -1 && token.index > firstUnknown;
6519
+ if (token.kind === "sentinel")
6520
+ continue;
6521
+ if (token.kind === "operand") {
6522
+ const claimable = !pastUnknown && fillsPositionals && nextPositional < registered.length;
6523
+ const name = claimable ? registered[nextPositional++].name() : undefined;
6524
+ visit(name || undefined, token.text);
6525
+ continue;
6526
+ }
6527
+ if (token.kind === "unknown") {
6528
+ const bare = token.flag.replace(/^-+/, "");
6529
+ const key = bare.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
6530
+ const keyable = token.flag.startsWith("--") || token.flag.length === 2;
6531
+ if (!pastUnknown && keyable && /^[a-z][a-z0-9-]*$/i.test(bare) && key) {
6532
+ visit(key, token.inlineValue ?? true);
6533
+ } else {
6534
+ visit(undefined, token.text);
6535
+ if (token.inlineValue !== undefined) {
6536
+ visit(undefined, token.inlineValue);
6537
+ } else if (!token.flag.startsWith("--") && token.flag.length > 2) {
6538
+ visit(undefined, token.flag.slice(2));
6539
+ }
6540
+ }
6541
+ continue;
6542
+ }
6543
+ if (pastUnknown) {
6544
+ visit(undefined, token.text);
6545
+ if (token.value !== undefined)
6546
+ visit(undefined, token.value);
6547
+ continue;
6548
+ }
6549
+ const option = token.option;
6550
+ const name = option.attributeName();
6551
+ const value = option.negate ? false : option.required || option.optional ? token.value ?? true : true;
6552
+ const previous = repeated.get(name);
6553
+ if (previous) {
6554
+ previous.push(value);
6555
+ visit(name, previous);
6556
+ } else {
6557
+ repeated.set(name, [value]);
6558
+ visit(name, value);
6559
+ }
6560
+ }
6028
6561
  }
6029
6562
  function withheldArgumentValues(cmd) {
6030
6563
  const values = [];
@@ -6086,6 +6619,8 @@ Command.prototype.trackedAction = function(context, fn, properties) {
6086
6619
  const telemetryName = commandTelemetryName(commandParts);
6087
6620
  const commandPath = commandInvocationPath(commandParts);
6088
6621
  const props = typeof properties === "function" ? properties(...args) : properties;
6622
+ const projectResolver = getProjectTelemetryResolver(command);
6623
+ const projectSession = projectResolver && !isProjectTelemetryDisabled() ? new ProjectTelemetrySession(projectResolver, command) : undefined;
6089
6624
  markCommandStart();
6090
6625
  const supplied = recordSuppliedArgumentValues(withheldArgumentValues(command));
6091
6626
  try {
@@ -6098,6 +6633,12 @@ Command.prototype.trackedAction = function(context, fn, properties) {
6098
6633
  if (violation) {
6099
6634
  return Promise.reject(violation);
6100
6635
  }
6636
+ if (projectSession) {
6637
+ return projectSession.resolve({ command, args, phase: "before" }).then(() => {
6638
+ attachProjectTelemetryCapture(command, projectSession);
6639
+ return fn(...args);
6640
+ });
6641
+ }
6101
6642
  return fn(...args);
6102
6643
  }));
6103
6644
  if (error) {
@@ -6106,22 +6647,26 @@ Command.prototype.trackedAction = function(context, fn, properties) {
6106
6647
  const typed = error;
6107
6648
  const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
6108
6649
  const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
6109
- const finalResult = customResult ?? RESULTS.Failure;
6650
+ const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
6651
+ const classified = cancellationExitCode === undefined ? await extractErrorDetails(error) : undefined;
6652
+ const finalResult = customResult ?? classified?.result ?? RESULTS.Failure;
6110
6653
  const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
6111
6654
  const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
6112
6655
  const typedRetry = typed.retry ?? typed.Retry;
6113
6656
  const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
6114
6657
  const typedContext = typed.context ?? typed.Context;
6115
6658
  const customContext = isErrorContext(typedContext) ? typedContext : undefined;
6116
- const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
6117
6659
  fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
6660
+ const errorCode = customErrorCode ?? classified?.errorCode;
6661
+ const retry = customRetry ?? classified?.retry;
6662
+ const errorContext = customContext ?? classified?.context;
6118
6663
  OutputFormatter.error({
6119
6664
  Result: finalResult,
6120
- ...customErrorCode ? { ErrorCode: customErrorCode } : {},
6665
+ ...errorCode ? { ErrorCode: errorCode } : {},
6121
6666
  Message: errorMessage,
6122
6667
  Instructions: customInstructions ?? commandHelpHint(commandPath),
6123
- ...customRetry ? { Retry: customRetry } : {},
6124
- ...customContext ? { Context: customContext } : {}
6668
+ ...retry ? { Retry: retry } : {},
6669
+ ...errorContext ? { Context: errorContext } : {}
6125
6670
  });
6126
6671
  context.exit(fallbackExitCode);
6127
6672
  }
@@ -6130,6 +6675,14 @@ Command.prototype.trackedAction = function(context, fn, properties) {
6130
6675
  const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
6131
6676
  const recordedFailure = takeRecordedCommandFailureTelemetry();
6132
6677
  const success = !error && exitCode === 0;
6678
+ if (projectSession) {
6679
+ await projectSession.resolve({
6680
+ command,
6681
+ args,
6682
+ phase: "after",
6683
+ success
6684
+ });
6685
+ }
6133
6686
  const terminalTelemetry = buildCommandTerminalTelemetryProperties({
6134
6687
  error,
6135
6688
  exitCode,
@@ -6147,6 +6700,7 @@ Command.prototype.trackedAction = function(context, fn, properties) {
6147
6700
  }
6148
6701
  const baseProperties = redactProperties({
6149
6702
  ...commandParams,
6703
+ ...projectSession?.properties(),
6150
6704
  ...props,
6151
6705
  ...buildCommandTelemetryAttribution(commandPath, process.env.UIPATH_SKILL),
6152
6706
  ...buildAgentSessionTelemetry(process.env),
@@ -6157,6 +6711,8 @@ Command.prototype.trackedAction = function(context, fn, properties) {
6157
6711
  });
6158
6712
  emitInvocationRequest(telemetryName, success, baseProperties);
6159
6713
  } finally {
6714
+ if (projectSession)
6715
+ attachProjectTelemetryCapture(command, undefined);
6160
6716
  releaseSuppliedArgumentValues(supplied);
6161
6717
  }
6162
6718
  });
@@ -6379,75 +6935,6 @@ var RESERVED_KEYWORDS_LOWER = new Set([
6379
6935
  "writeonly",
6380
6936
  "xor"
6381
6937
  ]);
6382
- // ../common/src/error-instructions.ts
6383
- function extractHttpStatus(err) {
6384
- if (!err || typeof err !== "object")
6385
- return;
6386
- const e = err;
6387
- const structured = e.response?.status ?? e.status ?? e.statusCode;
6388
- if (structured !== undefined)
6389
- return structured;
6390
- return typeof e.message === "string" ? parseHttpStatusFromMessage(e.message) : undefined;
6391
- }
6392
- var GENERIC = "Check authentication and parameters";
6393
- function instructionsFor(ctx, err) {
6394
- switch (ctx) {
6395
- case "auth":
6396
- return "Run 'uip login' to authenticate. To inspect the current session, run 'uip whoami'.";
6397
- case "identity":
6398
- return "Select an active tenant with 'uip login tenant set <tenant>' and ensure your login includes an organization";
6399
- case "input-parse":
6400
- return "Ensure --inputs is valid JSON or pipe JSON via stdin";
6401
- case "input-validate":
6402
- return "Fix the flagged input fields to match the process's input schema";
6403
- case "flag-format":
6404
- return "Check the flag value format — see --help for the expected shape";
6405
- case "permissions":
6406
- return "Confirm your user has the required permissions in this folder/tenant, or re-authenticate with 'uip login' if your session has lapsed";
6407
- case "backend": {
6408
- const status = extractHttpStatus(err);
6409
- if (status === 401) {
6410
- return "Re-authenticate with 'uip login' — your session is invalid or expired";
6411
- }
6412
- if (status === 403) {
6413
- return "Confirm your user has access to the resource, and the required permissions in this folder or tenant";
6414
- }
6415
- if (status === 404) {
6416
- return "Verify the resource exists in the current folder/tenant";
6417
- }
6418
- if (status === 400 || status === 422) {
6419
- return "Request was rejected — check flag values and inputs";
6420
- }
6421
- if (status === 405) {
6422
- return "Check the command name and the base URL in use — the endpoint may not exist";
6423
- }
6424
- if (status === 408) {
6425
- return "The request timed out — retry; if it persists, narrow the request (e.g. --limit on list commands)";
6426
- }
6427
- if (status === 409) {
6428
- return "The resource already exists, or changed since it was read — list it to see the current state";
6429
- }
6430
- if (status === 413) {
6431
- return "The upload is over the size limit — exclude unused dependencies or drop large files, then retry";
6432
- }
6433
- if (status === 429) {
6434
- return "Rate limit reached — wait and retry; when the service suggests a delay, Retry and Context.retryAfter carry it";
6435
- }
6436
- if (status !== undefined && status >= 500 && status < 600) {
6437
- return "The service returned a server error — retry; if it persists, check service status";
6438
- }
6439
- const permission = describePermissionError(err);
6440
- if (permission) {
6441
- return permission.instructions;
6442
- }
6443
- const connectivity = describeConnectivityError(err);
6444
- if (connectivity) {
6445
- return connectivity.instructions;
6446
- }
6447
- return GENERIC;
6448
- }
6449
- }
6450
- }
6451
6938
  // ../common/src/host-global-options.ts
6452
6939
  var HOST_GLOBAL_OPTIONS_WITH_VALUE = [
6453
6940
  "--output",
@@ -6637,9 +7124,9 @@ function getProfileStorage() {
6637
7124
  if (isAuthProfileStorage(existing)) {
6638
7125
  return existing;
6639
7126
  }
6640
- const storage2 = createProfileStorage();
6641
- globalSlot[AUTH_PROFILE_STORAGE_KEY] = storage2;
6642
- return storage2;
7127
+ const storage = createProfileStorage();
7128
+ globalSlot[AUTH_PROFILE_STORAGE_KEY] = storage;
7129
+ return storage;
6643
7130
  }
6644
7131
  var profileStorage = getProfileStorage();
6645
7132
 
@@ -6670,8 +7157,8 @@ function resolveAuthProfileFilePath(profile) {
6670
7157
  if (normalized === undefined) {
6671
7158
  throw new AuthProfileValidationError(`"${DEFAULT_AUTH_PROFILE}" is the built-in profile and does not have a profile file path.`);
6672
7159
  }
6673
- const fs2 = getFileSystem();
6674
- return fs2.path.join(fs2.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
7160
+ const fs = getFileSystem();
7161
+ return fs.path.join(fs.env.homedir(), UIPATH_HOME_DIR, PROFILE_DIR, normalized, AUTH_FILENAME);
6675
7162
  }
6676
7163
  function getActiveAuthProfileFilePath() {
6677
7164
  const profile = getActiveAuthProfile();
@@ -6937,6 +7424,8 @@ var ENV_AUTH_VARS = {
6937
7424
  };
6938
7425
 
6939
7426
  class EnvAuthConfigError extends Error {
7427
+ errorCode = "configuration_error";
7428
+ retry = "RetryWillNotFix";
6940
7429
  constructor(message) {
6941
7430
  super(message);
6942
7431
  this.name = "EnvAuthConfigError";
@@ -6975,11 +7464,11 @@ var readAuthFromEnv = () => {
6975
7464
  if (!rawUrl) {
6976
7465
  throw new EnvAuthConfigError(`${ENV_AUTH_VARS.token} is not a JWT (treating it as an opaque token, ` + `e.g. a Personal Access Token). Set ${OPAQUE_TOKEN_BASE_URL_VAR} to the ` + `UiPath base URL if this is a PAT, or fix the token if it was meant to ` + `be a JWT (parse error: ${parseErrorMessage}).`);
6977
7466
  }
6978
- const baseUrl2 = resolveBaseUrl(rawUrl, `Failed to validate ${OPAQUE_TOKEN_BASE_URL_VAR}`);
7467
+ const baseUrl = resolveBaseUrl(rawUrl, `Failed to validate ${OPAQUE_TOKEN_BASE_URL_VAR}`);
6979
7468
  return {
6980
7469
  loginStatus: "Logged in",
6981
7470
  accessToken,
6982
- baseUrl: baseUrl2,
7471
+ baseUrl,
6983
7472
  organizationName,
6984
7473
  organizationId,
6985
7474
  tenantName,
@@ -7020,8 +7509,8 @@ var SURFACE_WINDOW_MS = 60 * 60 * 1000;
7020
7509
  async function refreshTokenFingerprint(refreshToken) {
7021
7510
  const bytes = new TextEncoder().encode(refreshToken);
7022
7511
  if (globalThis.crypto?.subtle) {
7023
- const digest2 = await globalThis.crypto.subtle.digest("SHA-256", bytes);
7024
- return Array.from(new Uint8Array(digest2), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
7512
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
7513
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
7025
7514
  }
7026
7515
  const { createHash } = await import("node:crypto");
7027
7516
  return createHash("sha256").update(refreshToken).digest("hex").slice(0, 16);
@@ -7030,9 +7519,9 @@ function breakerPathFor(authPath) {
7030
7519
  return `${authPath}${BREAKER_SUFFIX}`;
7031
7520
  }
7032
7521
  async function loadRefreshBreaker(authPath) {
7033
- const fs2 = getFileSystem();
7522
+ const fs = getFileSystem();
7034
7523
  try {
7035
- const content = await fs2.readFile(breakerPathFor(authPath), "utf-8");
7524
+ const content = await fs.readFile(breakerPathFor(authPath), "utf-8");
7036
7525
  if (!content)
7037
7526
  return {};
7038
7527
  const parsed = JSON.parse(content);
@@ -7043,20 +7532,20 @@ async function loadRefreshBreaker(authPath) {
7043
7532
  }
7044
7533
  async function saveRefreshBreaker(authPath, state) {
7045
7534
  try {
7046
- const fs2 = getFileSystem();
7047
- const path2 = breakerPathFor(authPath);
7048
- await fs2.mkdir(fs2.path.dirname(path2));
7049
- const tempPath = `${path2}.tmp`;
7050
- await fs2.writeFile(tempPath, JSON.stringify(state));
7051
- await fs2.rename(tempPath, path2);
7535
+ const fs = getFileSystem();
7536
+ const path = breakerPathFor(authPath);
7537
+ await fs.mkdir(fs.path.dirname(path));
7538
+ const tempPath = `${path}.tmp`;
7539
+ await fs.writeFile(tempPath, JSON.stringify(state));
7540
+ await fs.rename(tempPath, path);
7052
7541
  } catch {}
7053
7542
  }
7054
7543
  async function clearRefreshBreaker(authPath) {
7055
- const fs2 = getFileSystem();
7056
- const path2 = breakerPathFor(authPath);
7544
+ const fs = getFileSystem();
7545
+ const path = breakerPathFor(authPath);
7057
7546
  try {
7058
- if (await fs2.exists(path2)) {
7059
- await fs2.rm(path2);
7547
+ if (await fs.exists(path)) {
7548
+ await fs.rm(path);
7060
7549
  }
7061
7550
  } catch {}
7062
7551
  }
@@ -7077,13 +7566,13 @@ var ROBOT_USER_SERVICES_PIPE = "UiPathUserServices";
7077
7566
  var ROBOT_USER_SERVICES_ALTERNATE_PIPE = `${ROBOT_USER_SERVICES_PIPE}Alternate`;
7078
7567
  var PIPE_NAME_MAX_LENGTH = 103;
7079
7568
  var getRobotIpcPipeNames = async () => {
7080
- const fs2 = getFileSystem();
7081
- const username = fs2.env.getenv("USER") ?? fs2.env.getenv("USERNAME");
7569
+ const fs = getFileSystem();
7570
+ const username = fs.env.getenv("USER") ?? fs.env.getenv("USERNAME");
7082
7571
  if (!username) {
7083
7572
  throw new Error("Unable to determine current username");
7084
7573
  }
7085
- const tempPath = fs2.env.getenv("TMPDIR") ?? "/tmp/";
7086
- return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs2.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
7574
+ const tempPath = fs.env.getenv("TMPDIR") ?? "/tmp/";
7575
+ return [ROBOT_USER_SERVICES_PIPE, ROBOT_USER_SERVICES_ALTERNATE_PIPE].map((baseName) => fs.path.join(tempPath, `${baseName}_${username}`).substring(0, PIPE_NAME_MAX_LENGTH));
7087
7576
  };
7088
7577
  var defaultIsRobotIpcAvailable = async () => {
7089
7578
  if (process.platform === "win32") {
@@ -7093,20 +7582,20 @@ var defaultIsRobotIpcAvailable = async () => {
7093
7582
  if (pipeNamesError || !pipeNames) {
7094
7583
  return false;
7095
7584
  }
7096
- const fs2 = getFileSystem();
7585
+ const fs = getFileSystem();
7097
7586
  for (const pipeName of pipeNames) {
7098
- const [existsError, exists] = await catchError2(fs2.exists(pipeName));
7587
+ const [existsError, exists] = await catchError2(fs.exists(pipeName));
7099
7588
  if (!existsError && exists === true) {
7100
7589
  return true;
7101
7590
  }
7102
7591
  }
7103
7592
  return false;
7104
7593
  };
7105
- var withTimeout = (promise, timeoutMs) => new Promise((resolve2, reject) => {
7594
+ var withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
7106
7595
  const timer = setTimeout(() => reject(new Error(`Robot IPC call timed out after ${timeoutMs}ms`)), timeoutMs);
7107
7596
  promise.then((value) => {
7108
7597
  clearTimeout(timer);
7109
- resolve2(value);
7598
+ resolve(value);
7110
7599
  }, (error) => {
7111
7600
  clearTimeout(timer);
7112
7601
  reject(error);
@@ -7279,9 +7768,12 @@ var refreshAccessToken = async ({
7279
7768
  body: tokenParams
7280
7769
  });
7281
7770
  const tokenData = await tokenResponse.json();
7282
- if (!tokenResponse.ok) {
7771
+ if (tokenResponse.status === 400 || tokenResponse.status === 401) {
7283
7772
  throw new TokenRefreshOAuthError;
7284
7773
  }
7774
+ if (!tokenResponse.ok) {
7775
+ throw new Error(`Token refresh failed: HTTP ${tokenResponse.status}`);
7776
+ }
7285
7777
  const newAccessToken = tokenData.access_token;
7286
7778
  const newRefreshToken = tokenData.refresh_token;
7287
7779
  if (typeof newAccessToken !== "string" || typeof newRefreshToken !== "string") {
@@ -7313,9 +7805,9 @@ var errorCode = (err) => {
7313
7805
  }
7314
7806
  return "EUNKNOWN";
7315
7807
  };
7316
- var probeAsync = async (fs2, candidate) => {
7808
+ var probeAsync = async (fs, candidate) => {
7317
7809
  try {
7318
- const stats = await fs2.stat(candidate);
7810
+ const stats = await fs.stat(candidate);
7319
7811
  if (stats === null) {
7320
7812
  return { exists: false };
7321
7813
  }
@@ -7342,36 +7834,36 @@ var probeAsync = async (fs2, candidate) => {
7342
7834
  }
7343
7835
  };
7344
7836
  var resolveEnvFileLocationAsync = async (envFilePath = DEFAULT_ENV_FILENAME, opts) => {
7345
- const fs2 = getFileSystem();
7346
- if (fs2.path.isAbsolute(envFilePath)) {
7347
- const probe2 = await probeAsync(fs2, envFilePath);
7348
- return probe2.exists ? { exists: true, absolutePath: envFilePath, source: "absolute" } : {
7837
+ const fs = getFileSystem();
7838
+ if (fs.path.isAbsolute(envFilePath)) {
7839
+ const probe = await probeAsync(fs, envFilePath);
7840
+ return probe.exists ? { exists: true, absolutePath: envFilePath, source: "absolute" } : {
7349
7841
  exists: false,
7350
7842
  absolutePath: envFilePath,
7351
7843
  source: "absolute",
7352
- ...probe2.unusable ? { unusable: probe2.unusable } : {}
7844
+ ...probe.unusable ? { unusable: probe.unusable } : {}
7353
7845
  };
7354
7846
  }
7355
- const cwd = opts?.cwd ?? fs2.env.cwd();
7847
+ const cwd = opts?.cwd ?? fs.env.cwd();
7356
7848
  let searchDir = cwd;
7357
7849
  while (true) {
7358
- const candidate = fs2.path.join(searchDir, envFilePath);
7359
- const probe2 = await probeAsync(fs2, candidate);
7360
- if (probe2.exists) {
7850
+ const candidate = fs.path.join(searchDir, envFilePath);
7851
+ const probe = await probeAsync(fs, candidate);
7852
+ if (probe.exists) {
7361
7853
  return {
7362
7854
  exists: true,
7363
7855
  absolutePath: candidate,
7364
7856
  source: searchDir === cwd ? "cwd" : "ancestor"
7365
7857
  };
7366
7858
  }
7367
- const parentDir = fs2.path.dirname(searchDir);
7859
+ const parentDir = fs.path.dirname(searchDir);
7368
7860
  if (parentDir === searchDir) {
7369
7861
  break;
7370
7862
  }
7371
7863
  searchDir = parentDir;
7372
7864
  }
7373
- const homePath = fs2.path.join(fs2.env.homedir(), envFilePath);
7374
- const probe = await probeAsync(fs2, homePath);
7865
+ const homePath = fs.path.join(fs.env.homedir(), envFilePath);
7866
+ const probe = await probeAsync(fs, homePath);
7375
7867
  if (probe.exists) {
7376
7868
  return { exists: true, absolutePath: homePath, source: "home" };
7377
7869
  }
@@ -7414,12 +7906,12 @@ var parseEnvContent = (content) => {
7414
7906
  return env;
7415
7907
  };
7416
7908
  var loadEnvFileAsync = async ({ envPath }) => {
7417
- const fs2 = getFileSystem();
7418
- const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.cwd(), envPath);
7419
- if (!await fs2.exists(absolutePath)) {
7909
+ const fs = getFileSystem();
7910
+ const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.cwd(), envPath);
7911
+ if (!await fs.exists(absolutePath)) {
7420
7912
  throw new Error(`Environment file not found: ${envPath}`);
7421
7913
  }
7422
- const content = await fs2.readFile(absolutePath, "utf-8");
7914
+ const content = await fs.readFile(absolutePath, "utf-8");
7423
7915
  if (content === null) {
7424
7916
  throw new Error(`Environment file not found: ${envPath}`);
7425
7917
  }
@@ -7430,10 +7922,10 @@ var saveEnvFileAsync = async ({
7430
7922
  data,
7431
7923
  merge = true
7432
7924
  }) => {
7433
- const fs2 = getFileSystem();
7434
- const absolutePath = fs2.path.isAbsolute(envPath) ? envPath : fs2.path.join(fs2.env.homedir(), envPath);
7925
+ const fs = getFileSystem();
7926
+ const absolutePath = fs.path.isAbsolute(envPath) ? envPath : fs.path.join(fs.env.homedir(), envPath);
7435
7927
  let existingData = {};
7436
- if (merge && await fs2.exists(absolutePath)) {
7928
+ if (merge && await fs.exists(absolutePath)) {
7437
7929
  try {
7438
7930
  existingData = await loadEnvFileAsync({ envPath: absolutePath });
7439
7931
  } catch {}
@@ -7451,11 +7943,11 @@ var saveEnvFileAsync = async ({
7451
7943
  const content = `${lines.join(`
7452
7944
  `)}
7453
7945
  `;
7454
- const dir = fs2.path.dirname(absolutePath);
7455
- await fs2.mkdir(dir);
7946
+ const dir = fs.path.dirname(absolutePath);
7947
+ await fs.mkdir(dir);
7456
7948
  const tempPath = `${absolutePath}.tmp`;
7457
- await fs2.writeFile(tempPath, content);
7458
- await fs2.rename(tempPath, absolutePath);
7949
+ await fs.writeFile(tempPath, content);
7950
+ await fs.rename(tempPath, absolutePath);
7459
7951
  };
7460
7952
 
7461
7953
  // ../auth/src/loginStatus.ts
@@ -7579,11 +8071,11 @@ async function loadFileCredentials(loadEnvFile, absolutePath) {
7579
8071
  return { credentials };
7580
8072
  }
7581
8073
  async function getGlobalCredsHint(getFs, loadEnvFile, absolutePath, envFilePath) {
7582
- const fs2 = getFs();
7583
- const globalPath = fs2.path.join(fs2.env.homedir(), envFilePath);
8074
+ const fs = getFs();
8075
+ const globalPath = fs.path.join(fs.env.homedir(), envFilePath);
7584
8076
  if (absolutePath === globalPath)
7585
8077
  return;
7586
- if (!await fs2.exists(globalPath))
8078
+ if (!await fs.exists(globalPath))
7587
8079
  return;
7588
8080
  try {
7589
8081
  const globalCreds = await loadEnvFile({ envPath: globalPath });
@@ -7998,6 +8490,51 @@ function normalizeTokenRefreshUnavailableFailure() {
7998
8490
  function errorMessage(error) {
7999
8491
  return error instanceof Error ? error.message : String(error);
8000
8492
  }
8493
+
8494
+ // ../auth/src/authContext.ts
8495
+ class AuthContextUnavailableError extends Error {
8496
+ instructionContext;
8497
+ sessionHint;
8498
+ errorCode = "authentication_required";
8499
+ retry = "RetryWillNotFix";
8500
+ constructor(message, instructionContext = "auth", sessionHint) {
8501
+ super(message);
8502
+ this.instructionContext = instructionContext;
8503
+ this.sessionHint = sessionHint;
8504
+ this.name = "AuthContextUnavailableError";
8505
+ }
8506
+ }
8507
+ var getAuthContext = async (options = {}) => {
8508
+ const status = await getLoginStatusAsync({
8509
+ ensureTokenValidityMinutes: options.ensureTokenValidityMinutes,
8510
+ envFilePath: options.envFilePath
8511
+ });
8512
+ if (status.loginStatus !== "Logged in" || !status.baseUrl || !status.accessToken) {
8513
+ throw new AuthContextUnavailableError(status.hint ? `Not logged in. ${status.hint}` : "Not logged in. Run 'uip login' first.", "auth", status.hint);
8514
+ }
8515
+ const tenantName = options.tenant || status.tenantName;
8516
+ if (options.requireOrganizationId && !status.organizationId) {
8517
+ throw new AuthContextUnavailableError("Organization ID not available. Ensure you are logged in with an organization context.", "identity");
8518
+ }
8519
+ if (options.requireOrganizationName && !status.organizationName) {
8520
+ throw new AuthContextUnavailableError("Organization name not available. Ensure you are logged in with an organization context.", "identity");
8521
+ }
8522
+ if (options.requireTenantId && !status.tenantId) {
8523
+ throw new AuthContextUnavailableError(`Tenant ID not available. Ensure UIPATH_TENANT_ID is set.${status.hint ? ` ${status.hint}` : ""}`, "identity", status.hint);
8524
+ }
8525
+ if (options.requireTenantName && !tenantName) {
8526
+ throw new AuthContextUnavailableError("Tenant not provided and UIPATH_TENANT_NAME not set. Run 'uip login' to select a tenant, or use 'uip login tenant set <tenant>' to switch tenants.", "identity");
8527
+ }
8528
+ return {
8529
+ baseUrl: status.baseUrl,
8530
+ accessToken: status.accessToken,
8531
+ organizationId: status.organizationId,
8532
+ organizationName: status.organizationName,
8533
+ tenantId: status.tenantId,
8534
+ tenantName,
8535
+ identity: status.identity
8536
+ };
8537
+ };
8001
8538
  // ../auth/src/selectTenant.ts
8002
8539
  var TENANT_SELECTION_REQUIRED_CODE = "TENANT_SELECTION_REQUIRED";
8003
8540
  var INVALID_TENANT_CODE = "INVALID_TENANT";
@@ -8008,6 +8545,6 @@ var TENANT_SELECTION_CODES = new Set([
8008
8545
  // src/api/external-user-id.ts
8009
8546
  var CLI_EXTERNAL_USER_ID = "app-user-cli-cas";
8010
8547
 
8011
- export { package_default, getFileSystem, catchError, extractErrorDetails, extractErrorMessageSync, RESULTS, EXIT_CODES, OutputFormatter, InvalidArgumentError, Command, processContext, requireConfirmation, instructionsFor, canPrompt, parseBoundedInt, getSdkUserAgentToken, addSdkUserAgentHeader, getLoginStatusAsync, CLI_EXTERNAL_USER_ID };
8548
+ export { package_default, getFileSystem, catchError, carriedErrorCode, extractErrorDetails, extractErrorMessageSync, hasIdentityInstructionContext, instructionsFor, RESULTS, InvalidArgumentError, Command, EXIT_CODES, OutputFormatter, processContext, requireConfirmation, canPrompt, parseBoundedInt, getSdkUserAgentToken, addSdkUserAgentHeader, getAuthContext, CLI_EXTERNAL_USER_ID };
8012
8549
 
8013
- //# debugId=A995FE1ED1FAFAC464756E2164756E21
8550
+ //# debugId=6CF80D57636FFCB064756E2164756E21