@uipath/case-tool 1.200.0-preview.109 → 1.201.0-preview.115

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.
@@ -0,0 +1,4821 @@
1
+ import {
2
+ getFileSystem
3
+ } from "./packager-tool-1cb0d5e0.js";
4
+ import {
5
+ __commonJS,
6
+ __require,
7
+ __toESM
8
+ } from "./packager-tool-wckvcay0.js";
9
+
10
+ // ../../node_modules/commander/lib/error.js
11
+ var require_error = __commonJS((exports) => {
12
+ class CommanderError extends Error {
13
+ constructor(exitCode, code, message) {
14
+ super(message);
15
+ Error.captureStackTrace(this, this.constructor);
16
+ this.name = this.constructor.name;
17
+ this.code = code;
18
+ this.exitCode = exitCode;
19
+ this.nestedError = undefined;
20
+ }
21
+ }
22
+
23
+ class InvalidArgumentError extends CommanderError {
24
+ constructor(message) {
25
+ super(1, "commander.invalidArgument", message);
26
+ Error.captureStackTrace(this, this.constructor);
27
+ this.name = this.constructor.name;
28
+ }
29
+ }
30
+ exports.CommanderError = CommanderError;
31
+ exports.InvalidArgumentError = InvalidArgumentError;
32
+ });
33
+
34
+ // ../../node_modules/commander/lib/argument.js
35
+ var require_argument = __commonJS((exports) => {
36
+ var { InvalidArgumentError } = require_error();
37
+
38
+ class Argument {
39
+ constructor(name, description) {
40
+ this.description = description || "";
41
+ this.variadic = false;
42
+ this.parseArg = undefined;
43
+ this.defaultValue = undefined;
44
+ this.defaultValueDescription = undefined;
45
+ this.argChoices = undefined;
46
+ switch (name[0]) {
47
+ case "<":
48
+ this.required = true;
49
+ this._name = name.slice(1, -1);
50
+ break;
51
+ case "[":
52
+ this.required = false;
53
+ this._name = name.slice(1, -1);
54
+ break;
55
+ default:
56
+ this.required = true;
57
+ this._name = name;
58
+ break;
59
+ }
60
+ if (this._name.endsWith("...")) {
61
+ this.variadic = true;
62
+ this._name = this._name.slice(0, -3);
63
+ }
64
+ }
65
+ name() {
66
+ return this._name;
67
+ }
68
+ _collectValue(value, previous) {
69
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
70
+ return [value];
71
+ }
72
+ previous.push(value);
73
+ return previous;
74
+ }
75
+ default(value, description) {
76
+ this.defaultValue = value;
77
+ this.defaultValueDescription = description;
78
+ return this;
79
+ }
80
+ argParser(fn) {
81
+ this.parseArg = fn;
82
+ return this;
83
+ }
84
+ choices(values) {
85
+ this.argChoices = values.slice();
86
+ this.parseArg = (arg, previous) => {
87
+ if (!this.argChoices.includes(arg)) {
88
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
89
+ }
90
+ if (this.variadic) {
91
+ return this._collectValue(arg, previous);
92
+ }
93
+ return arg;
94
+ };
95
+ return this;
96
+ }
97
+ argRequired() {
98
+ this.required = true;
99
+ return this;
100
+ }
101
+ argOptional() {
102
+ this.required = false;
103
+ return this;
104
+ }
105
+ }
106
+ function humanReadableArgName(arg) {
107
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
108
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
109
+ }
110
+ exports.Argument = Argument;
111
+ exports.humanReadableArgName = humanReadableArgName;
112
+ });
113
+
114
+ // ../../node_modules/commander/lib/help.js
115
+ var require_help = __commonJS((exports) => {
116
+ var { humanReadableArgName } = require_argument();
117
+
118
+ class Help {
119
+ constructor() {
120
+ this.helpWidth = undefined;
121
+ this.minWidthToWrap = 40;
122
+ this.sortSubcommands = false;
123
+ this.sortOptions = false;
124
+ this.showGlobalOptions = false;
125
+ }
126
+ prepareContext(contextOptions) {
127
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
128
+ }
129
+ visibleCommands(cmd) {
130
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
131
+ const helpCommand = cmd._getHelpCommand();
132
+ if (helpCommand && !helpCommand._hidden) {
133
+ visibleCommands.push(helpCommand);
134
+ }
135
+ if (this.sortSubcommands) {
136
+ visibleCommands.sort((a, b) => {
137
+ return a.name().localeCompare(b.name());
138
+ });
139
+ }
140
+ return visibleCommands;
141
+ }
142
+ compareOptions(a, b) {
143
+ const getSortKey = (option) => {
144
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
145
+ };
146
+ return getSortKey(a).localeCompare(getSortKey(b));
147
+ }
148
+ visibleOptions(cmd) {
149
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
150
+ const helpOption = cmd._getHelpOption();
151
+ if (helpOption && !helpOption.hidden) {
152
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
153
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
154
+ if (!removeShort && !removeLong) {
155
+ visibleOptions.push(helpOption);
156
+ } else if (helpOption.long && !removeLong) {
157
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
158
+ } else if (helpOption.short && !removeShort) {
159
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
160
+ }
161
+ }
162
+ if (this.sortOptions) {
163
+ visibleOptions.sort(this.compareOptions);
164
+ }
165
+ return visibleOptions;
166
+ }
167
+ visibleGlobalOptions(cmd) {
168
+ if (!this.showGlobalOptions)
169
+ return [];
170
+ const globalOptions = [];
171
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
172
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
173
+ globalOptions.push(...visibleOptions);
174
+ }
175
+ if (this.sortOptions) {
176
+ globalOptions.sort(this.compareOptions);
177
+ }
178
+ return globalOptions;
179
+ }
180
+ visibleArguments(cmd) {
181
+ if (cmd._argsDescription) {
182
+ cmd.registeredArguments.forEach((argument) => {
183
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
184
+ });
185
+ }
186
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
187
+ return cmd.registeredArguments;
188
+ }
189
+ return [];
190
+ }
191
+ subcommandTerm(cmd) {
192
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
193
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
194
+ }
195
+ optionTerm(option) {
196
+ return option.flags;
197
+ }
198
+ argumentTerm(argument) {
199
+ return argument.name();
200
+ }
201
+ longestSubcommandTermLength(cmd, helper) {
202
+ return helper.visibleCommands(cmd).reduce((max, command) => {
203
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
204
+ }, 0);
205
+ }
206
+ longestOptionTermLength(cmd, helper) {
207
+ return helper.visibleOptions(cmd).reduce((max, option) => {
208
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
209
+ }, 0);
210
+ }
211
+ longestGlobalOptionTermLength(cmd, helper) {
212
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
213
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
214
+ }, 0);
215
+ }
216
+ longestArgumentTermLength(cmd, helper) {
217
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
218
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
219
+ }, 0);
220
+ }
221
+ commandUsage(cmd) {
222
+ let cmdName = cmd._name;
223
+ if (cmd._aliases[0]) {
224
+ cmdName = cmdName + "|" + cmd._aliases[0];
225
+ }
226
+ let ancestorCmdNames = "";
227
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
228
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
229
+ }
230
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
231
+ }
232
+ commandDescription(cmd) {
233
+ return cmd.description();
234
+ }
235
+ subcommandDescription(cmd) {
236
+ return cmd.summary() || cmd.description();
237
+ }
238
+ optionDescription(option) {
239
+ const extraInfo = [];
240
+ if (option.argChoices) {
241
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
242
+ }
243
+ if (option.defaultValue !== undefined) {
244
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
245
+ if (showDefault) {
246
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
247
+ }
248
+ }
249
+ if (option.presetArg !== undefined && option.optional) {
250
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
251
+ }
252
+ if (option.envVar !== undefined) {
253
+ extraInfo.push(`env: ${option.envVar}`);
254
+ }
255
+ if (extraInfo.length > 0) {
256
+ const extraDescription = `(${extraInfo.join(", ")})`;
257
+ if (option.description) {
258
+ return `${option.description} ${extraDescription}`;
259
+ }
260
+ return extraDescription;
261
+ }
262
+ return option.description;
263
+ }
264
+ argumentDescription(argument) {
265
+ const extraInfo = [];
266
+ if (argument.argChoices) {
267
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
268
+ }
269
+ if (argument.defaultValue !== undefined) {
270
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
271
+ }
272
+ if (extraInfo.length > 0) {
273
+ const extraDescription = `(${extraInfo.join(", ")})`;
274
+ if (argument.description) {
275
+ return `${argument.description} ${extraDescription}`;
276
+ }
277
+ return extraDescription;
278
+ }
279
+ return argument.description;
280
+ }
281
+ formatItemList(heading, items, helper) {
282
+ if (items.length === 0)
283
+ return [];
284
+ return [helper.styleTitle(heading), ...items, ""];
285
+ }
286
+ groupItems(unsortedItems, visibleItems, getGroup) {
287
+ const result = new Map;
288
+ unsortedItems.forEach((item) => {
289
+ const group = getGroup(item);
290
+ if (!result.has(group))
291
+ result.set(group, []);
292
+ });
293
+ visibleItems.forEach((item) => {
294
+ const group = getGroup(item);
295
+ if (!result.has(group)) {
296
+ result.set(group, []);
297
+ }
298
+ result.get(group).push(item);
299
+ });
300
+ return result;
301
+ }
302
+ formatHelp(cmd, helper) {
303
+ const termWidth = helper.padWidth(cmd, helper);
304
+ const helpWidth = helper.helpWidth ?? 80;
305
+ function callFormatItem(term, description) {
306
+ return helper.formatItem(term, termWidth, description, helper);
307
+ }
308
+ let output = [
309
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
310
+ ""
311
+ ];
312
+ const commandDescription = helper.commandDescription(cmd);
313
+ if (commandDescription.length > 0) {
314
+ output = output.concat([
315
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
316
+ ""
317
+ ]);
318
+ }
319
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
320
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
321
+ });
322
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
323
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
324
+ optionGroups.forEach((options, group) => {
325
+ const optionList = options.map((option) => {
326
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
327
+ });
328
+ output = output.concat(this.formatItemList(group, optionList, helper));
329
+ });
330
+ if (helper.showGlobalOptions) {
331
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
332
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
333
+ });
334
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
335
+ }
336
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
337
+ commandGroups.forEach((commands, group) => {
338
+ const commandList = commands.map((sub) => {
339
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
340
+ });
341
+ output = output.concat(this.formatItemList(group, commandList, helper));
342
+ });
343
+ return output.join(`
344
+ `);
345
+ }
346
+ displayWidth(str) {
347
+ return stripColor(str).length;
348
+ }
349
+ styleTitle(str) {
350
+ return str;
351
+ }
352
+ styleUsage(str) {
353
+ return str.split(" ").map((word) => {
354
+ if (word === "[options]")
355
+ return this.styleOptionText(word);
356
+ if (word === "[command]")
357
+ return this.styleSubcommandText(word);
358
+ if (word[0] === "[" || word[0] === "<")
359
+ return this.styleArgumentText(word);
360
+ return this.styleCommandText(word);
361
+ }).join(" ");
362
+ }
363
+ styleCommandDescription(str) {
364
+ return this.styleDescriptionText(str);
365
+ }
366
+ styleOptionDescription(str) {
367
+ return this.styleDescriptionText(str);
368
+ }
369
+ styleSubcommandDescription(str) {
370
+ return this.styleDescriptionText(str);
371
+ }
372
+ styleArgumentDescription(str) {
373
+ return this.styleDescriptionText(str);
374
+ }
375
+ styleDescriptionText(str) {
376
+ return str;
377
+ }
378
+ styleOptionTerm(str) {
379
+ return this.styleOptionText(str);
380
+ }
381
+ styleSubcommandTerm(str) {
382
+ return str.split(" ").map((word) => {
383
+ if (word === "[options]")
384
+ return this.styleOptionText(word);
385
+ if (word[0] === "[" || word[0] === "<")
386
+ return this.styleArgumentText(word);
387
+ return this.styleSubcommandText(word);
388
+ }).join(" ");
389
+ }
390
+ styleArgumentTerm(str) {
391
+ return this.styleArgumentText(str);
392
+ }
393
+ styleOptionText(str) {
394
+ return str;
395
+ }
396
+ styleArgumentText(str) {
397
+ return str;
398
+ }
399
+ styleSubcommandText(str) {
400
+ return str;
401
+ }
402
+ styleCommandText(str) {
403
+ return str;
404
+ }
405
+ padWidth(cmd, helper) {
406
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
407
+ }
408
+ preformatted(str) {
409
+ return /\n[^\S\r\n]/.test(str);
410
+ }
411
+ formatItem(term, termWidth, description, helper) {
412
+ const itemIndent = 2;
413
+ const itemIndentStr = " ".repeat(itemIndent);
414
+ if (!description)
415
+ return itemIndentStr + term;
416
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
417
+ const spacerWidth = 2;
418
+ const helpWidth = this.helpWidth ?? 80;
419
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
420
+ let formattedDescription;
421
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
422
+ formattedDescription = description;
423
+ } else {
424
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
425
+ formattedDescription = wrappedDescription.replace(/\n/g, `
426
+ ` + " ".repeat(termWidth + spacerWidth));
427
+ }
428
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
429
+ ${itemIndentStr}`);
430
+ }
431
+ boxWrap(str, width) {
432
+ if (width < this.minWidthToWrap)
433
+ return str;
434
+ const rawLines = str.split(/\r\n|\n/);
435
+ const chunkPattern = /[\s]*[^\s]+/g;
436
+ const wrappedLines = [];
437
+ rawLines.forEach((line) => {
438
+ const chunks = line.match(chunkPattern);
439
+ if (chunks === null) {
440
+ wrappedLines.push("");
441
+ return;
442
+ }
443
+ let sumChunks = [chunks.shift()];
444
+ let sumWidth = this.displayWidth(sumChunks[0]);
445
+ chunks.forEach((chunk) => {
446
+ const visibleWidth = this.displayWidth(chunk);
447
+ if (sumWidth + visibleWidth <= width) {
448
+ sumChunks.push(chunk);
449
+ sumWidth += visibleWidth;
450
+ return;
451
+ }
452
+ wrappedLines.push(sumChunks.join(""));
453
+ const nextChunk = chunk.trimStart();
454
+ sumChunks = [nextChunk];
455
+ sumWidth = this.displayWidth(nextChunk);
456
+ });
457
+ wrappedLines.push(sumChunks.join(""));
458
+ });
459
+ return wrappedLines.join(`
460
+ `);
461
+ }
462
+ }
463
+ function stripColor(str) {
464
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
465
+ return str.replace(sgrPattern, "");
466
+ }
467
+ exports.Help = Help;
468
+ exports.stripColor = stripColor;
469
+ });
470
+
471
+ // ../../node_modules/commander/lib/option.js
472
+ var require_option = __commonJS((exports) => {
473
+ var { InvalidArgumentError } = require_error();
474
+
475
+ class Option {
476
+ constructor(flags, description) {
477
+ this.flags = flags;
478
+ this.description = description || "";
479
+ this.required = flags.includes("<");
480
+ this.optional = flags.includes("[");
481
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
482
+ this.mandatory = false;
483
+ const optionFlags = splitOptionFlags(flags);
484
+ this.short = optionFlags.shortFlag;
485
+ this.long = optionFlags.longFlag;
486
+ this.negate = false;
487
+ if (this.long) {
488
+ this.negate = this.long.startsWith("--no-");
489
+ }
490
+ this.defaultValue = undefined;
491
+ this.defaultValueDescription = undefined;
492
+ this.presetArg = undefined;
493
+ this.envVar = undefined;
494
+ this.parseArg = undefined;
495
+ this.hidden = false;
496
+ this.argChoices = undefined;
497
+ this.conflictsWith = [];
498
+ this.implied = undefined;
499
+ this.helpGroupHeading = undefined;
500
+ }
501
+ default(value, description) {
502
+ this.defaultValue = value;
503
+ this.defaultValueDescription = description;
504
+ return this;
505
+ }
506
+ preset(arg) {
507
+ this.presetArg = arg;
508
+ return this;
509
+ }
510
+ conflicts(names) {
511
+ this.conflictsWith = this.conflictsWith.concat(names);
512
+ return this;
513
+ }
514
+ implies(impliedOptionValues) {
515
+ let newImplied = impliedOptionValues;
516
+ if (typeof impliedOptionValues === "string") {
517
+ newImplied = { [impliedOptionValues]: true };
518
+ }
519
+ this.implied = Object.assign(this.implied || {}, newImplied);
520
+ return this;
521
+ }
522
+ env(name) {
523
+ this.envVar = name;
524
+ return this;
525
+ }
526
+ argParser(fn) {
527
+ this.parseArg = fn;
528
+ return this;
529
+ }
530
+ makeOptionMandatory(mandatory = true) {
531
+ this.mandatory = !!mandatory;
532
+ return this;
533
+ }
534
+ hideHelp(hide = true) {
535
+ this.hidden = !!hide;
536
+ return this;
537
+ }
538
+ _collectValue(value, previous) {
539
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
540
+ return [value];
541
+ }
542
+ previous.push(value);
543
+ return previous;
544
+ }
545
+ choices(values) {
546
+ this.argChoices = values.slice();
547
+ this.parseArg = (arg, previous) => {
548
+ if (!this.argChoices.includes(arg)) {
549
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
550
+ }
551
+ if (this.variadic) {
552
+ return this._collectValue(arg, previous);
553
+ }
554
+ return arg;
555
+ };
556
+ return this;
557
+ }
558
+ name() {
559
+ if (this.long) {
560
+ return this.long.replace(/^--/, "");
561
+ }
562
+ return this.short.replace(/^-/, "");
563
+ }
564
+ attributeName() {
565
+ if (this.negate) {
566
+ return camelcase(this.name().replace(/^no-/, ""));
567
+ }
568
+ return camelcase(this.name());
569
+ }
570
+ helpGroup(heading) {
571
+ this.helpGroupHeading = heading;
572
+ return this;
573
+ }
574
+ is(arg) {
575
+ return this.short === arg || this.long === arg;
576
+ }
577
+ isBoolean() {
578
+ return !this.required && !this.optional && !this.negate;
579
+ }
580
+ }
581
+
582
+ class DualOptions {
583
+ constructor(options) {
584
+ this.positiveOptions = new Map;
585
+ this.negativeOptions = new Map;
586
+ this.dualOptions = new Set;
587
+ options.forEach((option) => {
588
+ if (option.negate) {
589
+ this.negativeOptions.set(option.attributeName(), option);
590
+ } else {
591
+ this.positiveOptions.set(option.attributeName(), option);
592
+ }
593
+ });
594
+ this.negativeOptions.forEach((value, key) => {
595
+ if (this.positiveOptions.has(key)) {
596
+ this.dualOptions.add(key);
597
+ }
598
+ });
599
+ }
600
+ valueFromOption(value, option) {
601
+ const optionKey = option.attributeName();
602
+ if (!this.dualOptions.has(optionKey))
603
+ return true;
604
+ const preset = this.negativeOptions.get(optionKey).presetArg;
605
+ const negativeValue = preset !== undefined ? preset : false;
606
+ return option.negate === (negativeValue === value);
607
+ }
608
+ }
609
+ function camelcase(str) {
610
+ return str.split("-").reduce((str2, word) => {
611
+ return str2 + word[0].toUpperCase() + word.slice(1);
612
+ });
613
+ }
614
+ function splitOptionFlags(flags) {
615
+ let shortFlag;
616
+ let longFlag;
617
+ const shortFlagExp = /^-[^-]$/;
618
+ const longFlagExp = /^--[^-]/;
619
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
620
+ if (shortFlagExp.test(flagParts[0]))
621
+ shortFlag = flagParts.shift();
622
+ if (longFlagExp.test(flagParts[0]))
623
+ longFlag = flagParts.shift();
624
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
625
+ shortFlag = flagParts.shift();
626
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
627
+ shortFlag = longFlag;
628
+ longFlag = flagParts.shift();
629
+ }
630
+ if (flagParts[0].startsWith("-")) {
631
+ const unsupportedFlag = flagParts[0];
632
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
633
+ if (/^-[^-][^-]/.test(unsupportedFlag))
634
+ throw new Error(`${baseError}
635
+ - a short flag is a single dash and a single character
636
+ - either use a single dash and a single character (for a short flag)
637
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
638
+ if (shortFlagExp.test(unsupportedFlag))
639
+ throw new Error(`${baseError}
640
+ - too many short flags`);
641
+ if (longFlagExp.test(unsupportedFlag))
642
+ throw new Error(`${baseError}
643
+ - too many long flags`);
644
+ throw new Error(`${baseError}
645
+ - unrecognised flag format`);
646
+ }
647
+ if (shortFlag === undefined && longFlag === undefined)
648
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
649
+ return { shortFlag, longFlag };
650
+ }
651
+ exports.Option = Option;
652
+ exports.DualOptions = DualOptions;
653
+ });
654
+
655
+ // ../../node_modules/commander/lib/suggestSimilar.js
656
+ var require_suggestSimilar = __commonJS((exports) => {
657
+ var maxDistance = 3;
658
+ function editDistance(a, b) {
659
+ if (Math.abs(a.length - b.length) > maxDistance)
660
+ return Math.max(a.length, b.length);
661
+ const d = [];
662
+ for (let i = 0;i <= a.length; i++) {
663
+ d[i] = [i];
664
+ }
665
+ for (let j = 0;j <= b.length; j++) {
666
+ d[0][j] = j;
667
+ }
668
+ for (let j = 1;j <= b.length; j++) {
669
+ for (let i = 1;i <= a.length; i++) {
670
+ let cost = 1;
671
+ if (a[i - 1] === b[j - 1]) {
672
+ cost = 0;
673
+ } else {
674
+ cost = 1;
675
+ }
676
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
677
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
678
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
679
+ }
680
+ }
681
+ }
682
+ return d[a.length][b.length];
683
+ }
684
+ function suggestSimilar(word, candidates) {
685
+ if (!candidates || candidates.length === 0)
686
+ return "";
687
+ candidates = Array.from(new Set(candidates));
688
+ const searchingOptions = word.startsWith("--");
689
+ if (searchingOptions) {
690
+ word = word.slice(2);
691
+ candidates = candidates.map((candidate) => candidate.slice(2));
692
+ }
693
+ let similar = [];
694
+ let bestDistance = maxDistance;
695
+ const minSimilarity = 0.4;
696
+ candidates.forEach((candidate) => {
697
+ if (candidate.length <= 1)
698
+ return;
699
+ const distance = editDistance(word, candidate);
700
+ const length = Math.max(word.length, candidate.length);
701
+ const similarity = (length - distance) / length;
702
+ if (similarity > minSimilarity) {
703
+ if (distance < bestDistance) {
704
+ bestDistance = distance;
705
+ similar = [candidate];
706
+ } else if (distance === bestDistance) {
707
+ similar.push(candidate);
708
+ }
709
+ }
710
+ });
711
+ similar.sort((a, b) => a.localeCompare(b));
712
+ if (searchingOptions) {
713
+ similar = similar.map((candidate) => `--${candidate}`);
714
+ }
715
+ if (similar.length > 1) {
716
+ return `
717
+ (Did you mean one of ${similar.join(", ")}?)`;
718
+ }
719
+ if (similar.length === 1) {
720
+ return `
721
+ (Did you mean ${similar[0]}?)`;
722
+ }
723
+ return "";
724
+ }
725
+ exports.suggestSimilar = suggestSimilar;
726
+ });
727
+
728
+ // ../../node_modules/commander/lib/command.js
729
+ var require_command = __commonJS((exports) => {
730
+ var EventEmitter = __require("node:events").EventEmitter;
731
+ var childProcess = __require("node:child_process");
732
+ var path = __require("node:path");
733
+ var fs = __require("node:fs");
734
+ var process2 = __require("node:process");
735
+ var { Argument, humanReadableArgName } = require_argument();
736
+ var { CommanderError } = require_error();
737
+ var { Help, stripColor } = require_help();
738
+ var { Option, DualOptions } = require_option();
739
+ var { suggestSimilar } = require_suggestSimilar();
740
+
741
+ class Command extends EventEmitter {
742
+ constructor(name) {
743
+ super();
744
+ this.commands = [];
745
+ this.options = [];
746
+ this.parent = null;
747
+ this._allowUnknownOption = false;
748
+ this._allowExcessArguments = false;
749
+ this.registeredArguments = [];
750
+ this._args = this.registeredArguments;
751
+ this.args = [];
752
+ this.rawArgs = [];
753
+ this.processedArgs = [];
754
+ this._scriptPath = null;
755
+ this._name = name || "";
756
+ this._optionValues = {};
757
+ this._optionValueSources = {};
758
+ this._storeOptionsAsProperties = false;
759
+ this._actionHandler = null;
760
+ this._executableHandler = false;
761
+ this._executableFile = null;
762
+ this._executableDir = null;
763
+ this._defaultCommandName = null;
764
+ this._exitCallback = null;
765
+ this._aliases = [];
766
+ this._combineFlagAndOptionalValue = true;
767
+ this._description = "";
768
+ this._summary = "";
769
+ this._argsDescription = undefined;
770
+ this._enablePositionalOptions = false;
771
+ this._passThroughOptions = false;
772
+ this._lifeCycleHooks = {};
773
+ this._showHelpAfterError = false;
774
+ this._showSuggestionAfterError = true;
775
+ this._savedState = null;
776
+ this._outputConfiguration = {
777
+ writeOut: (str) => process2.stdout.write(str),
778
+ writeErr: (str) => process2.stderr.write(str),
779
+ outputError: (str, write) => write(str),
780
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
781
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
782
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
783
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
784
+ stripColor: (str) => stripColor(str)
785
+ };
786
+ this._hidden = false;
787
+ this._helpOption = undefined;
788
+ this._addImplicitHelpCommand = undefined;
789
+ this._helpCommand = undefined;
790
+ this._helpConfiguration = {};
791
+ this._helpGroupHeading = undefined;
792
+ this._defaultCommandGroup = undefined;
793
+ this._defaultOptionGroup = undefined;
794
+ }
795
+ copyInheritedSettings(sourceCommand) {
796
+ this._outputConfiguration = sourceCommand._outputConfiguration;
797
+ this._helpOption = sourceCommand._helpOption;
798
+ this._helpCommand = sourceCommand._helpCommand;
799
+ this._helpConfiguration = sourceCommand._helpConfiguration;
800
+ this._exitCallback = sourceCommand._exitCallback;
801
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
802
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
803
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
804
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
805
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
806
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
807
+ return this;
808
+ }
809
+ _getCommandAndAncestors() {
810
+ const result = [];
811
+ for (let command = this;command; command = command.parent) {
812
+ result.push(command);
813
+ }
814
+ return result;
815
+ }
816
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
817
+ let desc = actionOptsOrExecDesc;
818
+ let opts = execOpts;
819
+ if (typeof desc === "object" && desc !== null) {
820
+ opts = desc;
821
+ desc = null;
822
+ }
823
+ opts = opts || {};
824
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
825
+ const cmd = this.createCommand(name);
826
+ if (desc) {
827
+ cmd.description(desc);
828
+ cmd._executableHandler = true;
829
+ }
830
+ if (opts.isDefault)
831
+ this._defaultCommandName = cmd._name;
832
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
833
+ cmd._executableFile = opts.executableFile || null;
834
+ if (args)
835
+ cmd.arguments(args);
836
+ this._registerCommand(cmd);
837
+ cmd.parent = this;
838
+ cmd.copyInheritedSettings(this);
839
+ if (desc)
840
+ return this;
841
+ return cmd;
842
+ }
843
+ createCommand(name) {
844
+ return new Command(name);
845
+ }
846
+ createHelp() {
847
+ return Object.assign(new Help, this.configureHelp());
848
+ }
849
+ configureHelp(configuration) {
850
+ if (configuration === undefined)
851
+ return this._helpConfiguration;
852
+ this._helpConfiguration = configuration;
853
+ return this;
854
+ }
855
+ configureOutput(configuration) {
856
+ if (configuration === undefined)
857
+ return this._outputConfiguration;
858
+ this._outputConfiguration = {
859
+ ...this._outputConfiguration,
860
+ ...configuration
861
+ };
862
+ return this;
863
+ }
864
+ showHelpAfterError(displayHelp = true) {
865
+ if (typeof displayHelp !== "string")
866
+ displayHelp = !!displayHelp;
867
+ this._showHelpAfterError = displayHelp;
868
+ return this;
869
+ }
870
+ showSuggestionAfterError(displaySuggestion = true) {
871
+ this._showSuggestionAfterError = !!displaySuggestion;
872
+ return this;
873
+ }
874
+ addCommand(cmd, opts) {
875
+ if (!cmd._name) {
876
+ throw new Error(`Command passed to .addCommand() must have a name
877
+ - specify the name in Command constructor or using .name()`);
878
+ }
879
+ opts = opts || {};
880
+ if (opts.isDefault)
881
+ this._defaultCommandName = cmd._name;
882
+ if (opts.noHelp || opts.hidden)
883
+ cmd._hidden = true;
884
+ this._registerCommand(cmd);
885
+ cmd.parent = this;
886
+ cmd._checkForBrokenPassThrough();
887
+ return this;
888
+ }
889
+ createArgument(name, description) {
890
+ return new Argument(name, description);
891
+ }
892
+ argument(name, description, parseArg, defaultValue) {
893
+ const argument = this.createArgument(name, description);
894
+ if (typeof parseArg === "function") {
895
+ argument.default(defaultValue).argParser(parseArg);
896
+ } else {
897
+ argument.default(parseArg);
898
+ }
899
+ this.addArgument(argument);
900
+ return this;
901
+ }
902
+ arguments(names) {
903
+ names.trim().split(/ +/).forEach((detail) => {
904
+ this.argument(detail);
905
+ });
906
+ return this;
907
+ }
908
+ addArgument(argument) {
909
+ const previousArgument = this.registeredArguments.slice(-1)[0];
910
+ if (previousArgument?.variadic) {
911
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
912
+ }
913
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
914
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
915
+ }
916
+ this.registeredArguments.push(argument);
917
+ return this;
918
+ }
919
+ helpCommand(enableOrNameAndArgs, description) {
920
+ if (typeof enableOrNameAndArgs === "boolean") {
921
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
922
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
923
+ this._initCommandGroup(this._getHelpCommand());
924
+ }
925
+ return this;
926
+ }
927
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
928
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
929
+ const helpDescription = description ?? "display help for command";
930
+ const helpCommand = this.createCommand(helpName);
931
+ helpCommand.helpOption(false);
932
+ if (helpArgs)
933
+ helpCommand.arguments(helpArgs);
934
+ if (helpDescription)
935
+ helpCommand.description(helpDescription);
936
+ this._addImplicitHelpCommand = true;
937
+ this._helpCommand = helpCommand;
938
+ if (enableOrNameAndArgs || description)
939
+ this._initCommandGroup(helpCommand);
940
+ return this;
941
+ }
942
+ addHelpCommand(helpCommand, deprecatedDescription) {
943
+ if (typeof helpCommand !== "object") {
944
+ this.helpCommand(helpCommand, deprecatedDescription);
945
+ return this;
946
+ }
947
+ this._addImplicitHelpCommand = true;
948
+ this._helpCommand = helpCommand;
949
+ this._initCommandGroup(helpCommand);
950
+ return this;
951
+ }
952
+ _getHelpCommand() {
953
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
954
+ if (hasImplicitHelpCommand) {
955
+ if (this._helpCommand === undefined) {
956
+ this.helpCommand(undefined, undefined);
957
+ }
958
+ return this._helpCommand;
959
+ }
960
+ return null;
961
+ }
962
+ hook(event, listener) {
963
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
964
+ if (!allowedValues.includes(event)) {
965
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
966
+ Expecting one of '${allowedValues.join("', '")}'`);
967
+ }
968
+ if (this._lifeCycleHooks[event]) {
969
+ this._lifeCycleHooks[event].push(listener);
970
+ } else {
971
+ this._lifeCycleHooks[event] = [listener];
972
+ }
973
+ return this;
974
+ }
975
+ exitOverride(fn) {
976
+ if (fn) {
977
+ this._exitCallback = fn;
978
+ } else {
979
+ this._exitCallback = (err) => {
980
+ if (err.code !== "commander.executeSubCommandAsync") {
981
+ throw err;
982
+ }
983
+ };
984
+ }
985
+ return this;
986
+ }
987
+ _exit(exitCode, code, message) {
988
+ if (this._exitCallback) {
989
+ this._exitCallback(new CommanderError(exitCode, code, message));
990
+ }
991
+ process2.exit(exitCode);
992
+ }
993
+ action(fn) {
994
+ const listener = (args) => {
995
+ const expectedArgsCount = this.registeredArguments.length;
996
+ const actionArgs = args.slice(0, expectedArgsCount);
997
+ if (this._storeOptionsAsProperties) {
998
+ actionArgs[expectedArgsCount] = this;
999
+ } else {
1000
+ actionArgs[expectedArgsCount] = this.opts();
1001
+ }
1002
+ actionArgs.push(this);
1003
+ return fn.apply(this, actionArgs);
1004
+ };
1005
+ this._actionHandler = listener;
1006
+ return this;
1007
+ }
1008
+ createOption(flags, description) {
1009
+ return new Option(flags, description);
1010
+ }
1011
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1012
+ try {
1013
+ return target.parseArg(value, previous);
1014
+ } catch (err) {
1015
+ if (err.code === "commander.invalidArgument") {
1016
+ const message = `${invalidArgumentMessage} ${err.message}`;
1017
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1018
+ }
1019
+ throw err;
1020
+ }
1021
+ }
1022
+ _registerOption(option) {
1023
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1024
+ if (matchingOption) {
1025
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1026
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1027
+ - already used by option '${matchingOption.flags}'`);
1028
+ }
1029
+ this._initOptionGroup(option);
1030
+ this.options.push(option);
1031
+ }
1032
+ _registerCommand(command) {
1033
+ const knownBy = (cmd) => {
1034
+ return [cmd.name()].concat(cmd.aliases());
1035
+ };
1036
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1037
+ if (alreadyUsed) {
1038
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1039
+ const newCmd = knownBy(command).join("|");
1040
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1041
+ }
1042
+ this._initCommandGroup(command);
1043
+ this.commands.push(command);
1044
+ }
1045
+ addOption(option) {
1046
+ this._registerOption(option);
1047
+ const oname = option.name();
1048
+ const name = option.attributeName();
1049
+ if (option.negate) {
1050
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1051
+ if (!this._findOption(positiveLongFlag)) {
1052
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1053
+ }
1054
+ } else if (option.defaultValue !== undefined) {
1055
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1056
+ }
1057
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1058
+ if (val == null && option.presetArg !== undefined) {
1059
+ val = option.presetArg;
1060
+ }
1061
+ const oldValue = this.getOptionValue(name);
1062
+ if (val !== null && option.parseArg) {
1063
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1064
+ } else if (val !== null && option.variadic) {
1065
+ val = option._collectValue(val, oldValue);
1066
+ }
1067
+ if (val == null) {
1068
+ if (option.negate) {
1069
+ val = false;
1070
+ } else if (option.isBoolean() || option.optional) {
1071
+ val = true;
1072
+ } else {
1073
+ val = "";
1074
+ }
1075
+ }
1076
+ this.setOptionValueWithSource(name, val, valueSource);
1077
+ };
1078
+ this.on("option:" + oname, (val) => {
1079
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1080
+ handleOptionValue(val, invalidValueMessage, "cli");
1081
+ });
1082
+ if (option.envVar) {
1083
+ this.on("optionEnv:" + oname, (val) => {
1084
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1085
+ handleOptionValue(val, invalidValueMessage, "env");
1086
+ });
1087
+ }
1088
+ return this;
1089
+ }
1090
+ _optionEx(config, flags, description, fn, defaultValue) {
1091
+ if (typeof flags === "object" && flags instanceof Option) {
1092
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1093
+ }
1094
+ const option = this.createOption(flags, description);
1095
+ option.makeOptionMandatory(!!config.mandatory);
1096
+ if (typeof fn === "function") {
1097
+ option.default(defaultValue).argParser(fn);
1098
+ } else if (fn instanceof RegExp) {
1099
+ const regex = fn;
1100
+ fn = (val, def) => {
1101
+ const m = regex.exec(val);
1102
+ return m ? m[0] : def;
1103
+ };
1104
+ option.default(defaultValue).argParser(fn);
1105
+ } else {
1106
+ option.default(fn);
1107
+ }
1108
+ return this.addOption(option);
1109
+ }
1110
+ option(flags, description, parseArg, defaultValue) {
1111
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1112
+ }
1113
+ requiredOption(flags, description, parseArg, defaultValue) {
1114
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1115
+ }
1116
+ combineFlagAndOptionalValue(combine = true) {
1117
+ this._combineFlagAndOptionalValue = !!combine;
1118
+ return this;
1119
+ }
1120
+ allowUnknownOption(allowUnknown = true) {
1121
+ this._allowUnknownOption = !!allowUnknown;
1122
+ return this;
1123
+ }
1124
+ allowExcessArguments(allowExcess = true) {
1125
+ this._allowExcessArguments = !!allowExcess;
1126
+ return this;
1127
+ }
1128
+ enablePositionalOptions(positional = true) {
1129
+ this._enablePositionalOptions = !!positional;
1130
+ return this;
1131
+ }
1132
+ passThroughOptions(passThrough = true) {
1133
+ this._passThroughOptions = !!passThrough;
1134
+ this._checkForBrokenPassThrough();
1135
+ return this;
1136
+ }
1137
+ _checkForBrokenPassThrough() {
1138
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1139
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1140
+ }
1141
+ }
1142
+ storeOptionsAsProperties(storeAsProperties = true) {
1143
+ if (this.options.length) {
1144
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1145
+ }
1146
+ if (Object.keys(this._optionValues).length) {
1147
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1148
+ }
1149
+ this._storeOptionsAsProperties = !!storeAsProperties;
1150
+ return this;
1151
+ }
1152
+ getOptionValue(key) {
1153
+ if (this._storeOptionsAsProperties) {
1154
+ return this[key];
1155
+ }
1156
+ return this._optionValues[key];
1157
+ }
1158
+ setOptionValue(key, value) {
1159
+ return this.setOptionValueWithSource(key, value, undefined);
1160
+ }
1161
+ setOptionValueWithSource(key, value, source) {
1162
+ if (this._storeOptionsAsProperties) {
1163
+ this[key] = value;
1164
+ } else {
1165
+ this._optionValues[key] = value;
1166
+ }
1167
+ this._optionValueSources[key] = source;
1168
+ return this;
1169
+ }
1170
+ getOptionValueSource(key) {
1171
+ return this._optionValueSources[key];
1172
+ }
1173
+ getOptionValueSourceWithGlobals(key) {
1174
+ let source;
1175
+ this._getCommandAndAncestors().forEach((cmd) => {
1176
+ if (cmd.getOptionValueSource(key) !== undefined) {
1177
+ source = cmd.getOptionValueSource(key);
1178
+ }
1179
+ });
1180
+ return source;
1181
+ }
1182
+ _prepareUserArgs(argv, parseOptions) {
1183
+ if (argv !== undefined && !Array.isArray(argv)) {
1184
+ throw new Error("first parameter to parse must be array or undefined");
1185
+ }
1186
+ parseOptions = parseOptions || {};
1187
+ if (argv === undefined && parseOptions.from === undefined) {
1188
+ if (process2.versions?.electron) {
1189
+ parseOptions.from = "electron";
1190
+ }
1191
+ const execArgv = process2.execArgv ?? [];
1192
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1193
+ parseOptions.from = "eval";
1194
+ }
1195
+ }
1196
+ if (argv === undefined) {
1197
+ argv = process2.argv;
1198
+ }
1199
+ this.rawArgs = argv.slice();
1200
+ let userArgs;
1201
+ switch (parseOptions.from) {
1202
+ case undefined:
1203
+ case "node":
1204
+ this._scriptPath = argv[1];
1205
+ userArgs = argv.slice(2);
1206
+ break;
1207
+ case "electron":
1208
+ if (process2.defaultApp) {
1209
+ this._scriptPath = argv[1];
1210
+ userArgs = argv.slice(2);
1211
+ } else {
1212
+ userArgs = argv.slice(1);
1213
+ }
1214
+ break;
1215
+ case "user":
1216
+ userArgs = argv.slice(0);
1217
+ break;
1218
+ case "eval":
1219
+ userArgs = argv.slice(1);
1220
+ break;
1221
+ default:
1222
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1223
+ }
1224
+ if (!this._name && this._scriptPath)
1225
+ this.nameFromFilename(this._scriptPath);
1226
+ this._name = this._name || "program";
1227
+ return userArgs;
1228
+ }
1229
+ parse(argv, parseOptions) {
1230
+ this._prepareForParse();
1231
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1232
+ this._parseCommand([], userArgs);
1233
+ return this;
1234
+ }
1235
+ async parseAsync(argv, parseOptions) {
1236
+ this._prepareForParse();
1237
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1238
+ await this._parseCommand([], userArgs);
1239
+ return this;
1240
+ }
1241
+ _prepareForParse() {
1242
+ if (this._savedState === null) {
1243
+ this.saveStateBeforeParse();
1244
+ } else {
1245
+ this.restoreStateBeforeParse();
1246
+ }
1247
+ }
1248
+ saveStateBeforeParse() {
1249
+ this._savedState = {
1250
+ _name: this._name,
1251
+ _optionValues: { ...this._optionValues },
1252
+ _optionValueSources: { ...this._optionValueSources }
1253
+ };
1254
+ }
1255
+ restoreStateBeforeParse() {
1256
+ if (this._storeOptionsAsProperties)
1257
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1258
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1259
+ this._name = this._savedState._name;
1260
+ this._scriptPath = null;
1261
+ this.rawArgs = [];
1262
+ this._optionValues = { ...this._savedState._optionValues };
1263
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1264
+ this.args = [];
1265
+ this.processedArgs = [];
1266
+ }
1267
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1268
+ if (fs.existsSync(executableFile))
1269
+ return;
1270
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1271
+ const executableMissing = `'${executableFile}' does not exist
1272
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1273
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1274
+ - ${executableDirMessage}`;
1275
+ throw new Error(executableMissing);
1276
+ }
1277
+ _executeSubCommand(subcommand, args) {
1278
+ args = args.slice();
1279
+ let launchWithNode = false;
1280
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1281
+ function findFile(baseDir, baseName) {
1282
+ const localBin = path.resolve(baseDir, baseName);
1283
+ if (fs.existsSync(localBin))
1284
+ return localBin;
1285
+ if (sourceExt.includes(path.extname(baseName)))
1286
+ return;
1287
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1288
+ if (foundExt)
1289
+ return `${localBin}${foundExt}`;
1290
+ return;
1291
+ }
1292
+ this._checkForMissingMandatoryOptions();
1293
+ this._checkForConflictingOptions();
1294
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1295
+ let executableDir = this._executableDir || "";
1296
+ if (this._scriptPath) {
1297
+ let resolvedScriptPath;
1298
+ try {
1299
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1300
+ } catch {
1301
+ resolvedScriptPath = this._scriptPath;
1302
+ }
1303
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1304
+ }
1305
+ if (executableDir) {
1306
+ let localFile = findFile(executableDir, executableFile);
1307
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1308
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1309
+ if (legacyName !== this._name) {
1310
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1311
+ }
1312
+ }
1313
+ executableFile = localFile || executableFile;
1314
+ }
1315
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1316
+ let proc;
1317
+ if (process2.platform !== "win32") {
1318
+ if (launchWithNode) {
1319
+ args.unshift(executableFile);
1320
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1321
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1322
+ } else {
1323
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1324
+ }
1325
+ } else {
1326
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1327
+ args.unshift(executableFile);
1328
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1329
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1330
+ }
1331
+ if (!proc.killed) {
1332
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1333
+ signals.forEach((signal) => {
1334
+ process2.on(signal, () => {
1335
+ if (proc.killed === false && proc.exitCode === null) {
1336
+ proc.kill(signal);
1337
+ }
1338
+ });
1339
+ });
1340
+ }
1341
+ const exitCallback = this._exitCallback;
1342
+ proc.on("close", (code) => {
1343
+ code = code ?? 1;
1344
+ if (!exitCallback) {
1345
+ process2.exit(code);
1346
+ } else {
1347
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1348
+ }
1349
+ });
1350
+ proc.on("error", (err) => {
1351
+ if (err.code === "ENOENT") {
1352
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1353
+ } else if (err.code === "EACCES") {
1354
+ throw new Error(`'${executableFile}' not executable`);
1355
+ }
1356
+ if (!exitCallback) {
1357
+ process2.exit(1);
1358
+ } else {
1359
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1360
+ wrappedError.nestedError = err;
1361
+ exitCallback(wrappedError);
1362
+ }
1363
+ });
1364
+ this.runningCommand = proc;
1365
+ }
1366
+ _dispatchSubcommand(commandName, operands, unknown) {
1367
+ const subCommand = this._findCommand(commandName);
1368
+ if (!subCommand)
1369
+ this.help({ error: true });
1370
+ subCommand._prepareForParse();
1371
+ let promiseChain;
1372
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1373
+ promiseChain = this._chainOrCall(promiseChain, () => {
1374
+ if (subCommand._executableHandler) {
1375
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1376
+ } else {
1377
+ return subCommand._parseCommand(operands, unknown);
1378
+ }
1379
+ });
1380
+ return promiseChain;
1381
+ }
1382
+ _dispatchHelpCommand(subcommandName) {
1383
+ if (!subcommandName) {
1384
+ this.help();
1385
+ }
1386
+ const subCommand = this._findCommand(subcommandName);
1387
+ if (subCommand && !subCommand._executableHandler) {
1388
+ subCommand.help();
1389
+ }
1390
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1391
+ }
1392
+ _checkNumberOfArguments() {
1393
+ this.registeredArguments.forEach((arg, i) => {
1394
+ if (arg.required && this.args[i] == null) {
1395
+ this.missingArgument(arg.name());
1396
+ }
1397
+ });
1398
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1399
+ return;
1400
+ }
1401
+ if (this.args.length > this.registeredArguments.length) {
1402
+ this._excessArguments(this.args);
1403
+ }
1404
+ }
1405
+ _processArguments() {
1406
+ const myParseArg = (argument, value, previous) => {
1407
+ let parsedValue = value;
1408
+ if (value !== null && argument.parseArg) {
1409
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1410
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1411
+ }
1412
+ return parsedValue;
1413
+ };
1414
+ this._checkNumberOfArguments();
1415
+ const processedArgs = [];
1416
+ this.registeredArguments.forEach((declaredArg, index) => {
1417
+ let value = declaredArg.defaultValue;
1418
+ if (declaredArg.variadic) {
1419
+ if (index < this.args.length) {
1420
+ value = this.args.slice(index);
1421
+ if (declaredArg.parseArg) {
1422
+ value = value.reduce((processed, v) => {
1423
+ return myParseArg(declaredArg, v, processed);
1424
+ }, declaredArg.defaultValue);
1425
+ }
1426
+ } else if (value === undefined) {
1427
+ value = [];
1428
+ }
1429
+ } else if (index < this.args.length) {
1430
+ value = this.args[index];
1431
+ if (declaredArg.parseArg) {
1432
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1433
+ }
1434
+ }
1435
+ processedArgs[index] = value;
1436
+ });
1437
+ this.processedArgs = processedArgs;
1438
+ }
1439
+ _chainOrCall(promise, fn) {
1440
+ if (promise?.then && typeof promise.then === "function") {
1441
+ return promise.then(() => fn());
1442
+ }
1443
+ return fn();
1444
+ }
1445
+ _chainOrCallHooks(promise, event) {
1446
+ let result = promise;
1447
+ const hooks = [];
1448
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1449
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1450
+ hooks.push({ hookedCommand, callback });
1451
+ });
1452
+ });
1453
+ if (event === "postAction") {
1454
+ hooks.reverse();
1455
+ }
1456
+ hooks.forEach((hookDetail) => {
1457
+ result = this._chainOrCall(result, () => {
1458
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1459
+ });
1460
+ });
1461
+ return result;
1462
+ }
1463
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1464
+ let result = promise;
1465
+ if (this._lifeCycleHooks[event] !== undefined) {
1466
+ this._lifeCycleHooks[event].forEach((hook) => {
1467
+ result = this._chainOrCall(result, () => {
1468
+ return hook(this, subCommand);
1469
+ });
1470
+ });
1471
+ }
1472
+ return result;
1473
+ }
1474
+ _parseCommand(operands, unknown) {
1475
+ const parsed = this.parseOptions(unknown);
1476
+ this._parseOptionsEnv();
1477
+ this._parseOptionsImplied();
1478
+ operands = operands.concat(parsed.operands);
1479
+ unknown = parsed.unknown;
1480
+ this.args = operands.concat(unknown);
1481
+ if (operands && this._findCommand(operands[0])) {
1482
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1483
+ }
1484
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1485
+ return this._dispatchHelpCommand(operands[1]);
1486
+ }
1487
+ if (this._defaultCommandName) {
1488
+ this._outputHelpIfRequested(unknown);
1489
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1490
+ }
1491
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1492
+ this.help({ error: true });
1493
+ }
1494
+ this._outputHelpIfRequested(parsed.unknown);
1495
+ this._checkForMissingMandatoryOptions();
1496
+ this._checkForConflictingOptions();
1497
+ const checkForUnknownOptions = () => {
1498
+ if (parsed.unknown.length > 0) {
1499
+ this.unknownOption(parsed.unknown[0]);
1500
+ }
1501
+ };
1502
+ const commandEvent = `command:${this.name()}`;
1503
+ if (this._actionHandler) {
1504
+ checkForUnknownOptions();
1505
+ this._processArguments();
1506
+ let promiseChain;
1507
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1508
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1509
+ if (this.parent) {
1510
+ promiseChain = this._chainOrCall(promiseChain, () => {
1511
+ this.parent.emit(commandEvent, operands, unknown);
1512
+ });
1513
+ }
1514
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1515
+ return promiseChain;
1516
+ }
1517
+ if (this.parent?.listenerCount(commandEvent)) {
1518
+ checkForUnknownOptions();
1519
+ this._processArguments();
1520
+ this.parent.emit(commandEvent, operands, unknown);
1521
+ } else if (operands.length) {
1522
+ if (this._findCommand("*")) {
1523
+ return this._dispatchSubcommand("*", operands, unknown);
1524
+ }
1525
+ if (this.listenerCount("command:*")) {
1526
+ this.emit("command:*", operands, unknown);
1527
+ } else if (this.commands.length) {
1528
+ this.unknownCommand();
1529
+ } else {
1530
+ checkForUnknownOptions();
1531
+ this._processArguments();
1532
+ }
1533
+ } else if (this.commands.length) {
1534
+ checkForUnknownOptions();
1535
+ this.help({ error: true });
1536
+ } else {
1537
+ checkForUnknownOptions();
1538
+ this._processArguments();
1539
+ }
1540
+ }
1541
+ _findCommand(name) {
1542
+ if (!name)
1543
+ return;
1544
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1545
+ }
1546
+ _findOption(arg) {
1547
+ return this.options.find((option) => option.is(arg));
1548
+ }
1549
+ _checkForMissingMandatoryOptions() {
1550
+ this._getCommandAndAncestors().forEach((cmd) => {
1551
+ cmd.options.forEach((anOption) => {
1552
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1553
+ cmd.missingMandatoryOptionValue(anOption);
1554
+ }
1555
+ });
1556
+ });
1557
+ }
1558
+ _checkForConflictingLocalOptions() {
1559
+ const definedNonDefaultOptions = this.options.filter((option) => {
1560
+ const optionKey = option.attributeName();
1561
+ if (this.getOptionValue(optionKey) === undefined) {
1562
+ return false;
1563
+ }
1564
+ return this.getOptionValueSource(optionKey) !== "default";
1565
+ });
1566
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1567
+ optionsWithConflicting.forEach((option) => {
1568
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1569
+ if (conflictingAndDefined) {
1570
+ this._conflictingOption(option, conflictingAndDefined);
1571
+ }
1572
+ });
1573
+ }
1574
+ _checkForConflictingOptions() {
1575
+ this._getCommandAndAncestors().forEach((cmd) => {
1576
+ cmd._checkForConflictingLocalOptions();
1577
+ });
1578
+ }
1579
+ parseOptions(args) {
1580
+ const operands = [];
1581
+ const unknown = [];
1582
+ let dest = operands;
1583
+ function maybeOption(arg) {
1584
+ return arg.length > 1 && arg[0] === "-";
1585
+ }
1586
+ const negativeNumberArg = (arg) => {
1587
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1588
+ return false;
1589
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1590
+ };
1591
+ let activeVariadicOption = null;
1592
+ let activeGroup = null;
1593
+ let i = 0;
1594
+ while (i < args.length || activeGroup) {
1595
+ const arg = activeGroup ?? args[i++];
1596
+ activeGroup = null;
1597
+ if (arg === "--") {
1598
+ if (dest === unknown)
1599
+ dest.push(arg);
1600
+ dest.push(...args.slice(i));
1601
+ break;
1602
+ }
1603
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1604
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1605
+ continue;
1606
+ }
1607
+ activeVariadicOption = null;
1608
+ if (maybeOption(arg)) {
1609
+ const option = this._findOption(arg);
1610
+ if (option) {
1611
+ if (option.required) {
1612
+ const value = args[i++];
1613
+ if (value === undefined)
1614
+ this.optionMissingArgument(option);
1615
+ this.emit(`option:${option.name()}`, value);
1616
+ } else if (option.optional) {
1617
+ let value = null;
1618
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1619
+ value = args[i++];
1620
+ }
1621
+ this.emit(`option:${option.name()}`, value);
1622
+ } else {
1623
+ this.emit(`option:${option.name()}`);
1624
+ }
1625
+ activeVariadicOption = option.variadic ? option : null;
1626
+ continue;
1627
+ }
1628
+ }
1629
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1630
+ const option = this._findOption(`-${arg[1]}`);
1631
+ if (option) {
1632
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1633
+ this.emit(`option:${option.name()}`, arg.slice(2));
1634
+ } else {
1635
+ this.emit(`option:${option.name()}`);
1636
+ activeGroup = `-${arg.slice(2)}`;
1637
+ }
1638
+ continue;
1639
+ }
1640
+ }
1641
+ if (/^--[^=]+=/.test(arg)) {
1642
+ const index = arg.indexOf("=");
1643
+ const option = this._findOption(arg.slice(0, index));
1644
+ if (option && (option.required || option.optional)) {
1645
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1646
+ continue;
1647
+ }
1648
+ }
1649
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1650
+ dest = unknown;
1651
+ }
1652
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1653
+ if (this._findCommand(arg)) {
1654
+ operands.push(arg);
1655
+ unknown.push(...args.slice(i));
1656
+ break;
1657
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1658
+ operands.push(arg, ...args.slice(i));
1659
+ break;
1660
+ } else if (this._defaultCommandName) {
1661
+ unknown.push(arg, ...args.slice(i));
1662
+ break;
1663
+ }
1664
+ }
1665
+ if (this._passThroughOptions) {
1666
+ dest.push(arg, ...args.slice(i));
1667
+ break;
1668
+ }
1669
+ dest.push(arg);
1670
+ }
1671
+ return { operands, unknown };
1672
+ }
1673
+ opts() {
1674
+ if (this._storeOptionsAsProperties) {
1675
+ const result = {};
1676
+ const len = this.options.length;
1677
+ for (let i = 0;i < len; i++) {
1678
+ const key = this.options[i].attributeName();
1679
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1680
+ }
1681
+ return result;
1682
+ }
1683
+ return this._optionValues;
1684
+ }
1685
+ optsWithGlobals() {
1686
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1687
+ }
1688
+ error(message, errorOptions) {
1689
+ this._outputConfiguration.outputError(`${message}
1690
+ `, this._outputConfiguration.writeErr);
1691
+ if (typeof this._showHelpAfterError === "string") {
1692
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1693
+ `);
1694
+ } else if (this._showHelpAfterError) {
1695
+ this._outputConfiguration.writeErr(`
1696
+ `);
1697
+ this.outputHelp({ error: true });
1698
+ }
1699
+ const config = errorOptions || {};
1700
+ const exitCode = config.exitCode || 1;
1701
+ const code = config.code || "commander.error";
1702
+ this._exit(exitCode, code, message);
1703
+ }
1704
+ _parseOptionsEnv() {
1705
+ this.options.forEach((option) => {
1706
+ if (option.envVar && option.envVar in process2.env) {
1707
+ const optionKey = option.attributeName();
1708
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1709
+ if (option.required || option.optional) {
1710
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1711
+ } else {
1712
+ this.emit(`optionEnv:${option.name()}`);
1713
+ }
1714
+ }
1715
+ }
1716
+ });
1717
+ }
1718
+ _parseOptionsImplied() {
1719
+ const dualHelper = new DualOptions(this.options);
1720
+ const hasCustomOptionValue = (optionKey) => {
1721
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1722
+ };
1723
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1724
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1725
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1726
+ });
1727
+ });
1728
+ }
1729
+ missingArgument(name) {
1730
+ const message = `error: missing required argument '${name}'`;
1731
+ this.error(message, { code: "commander.missingArgument" });
1732
+ }
1733
+ optionMissingArgument(option) {
1734
+ const message = `error: option '${option.flags}' argument missing`;
1735
+ this.error(message, { code: "commander.optionMissingArgument" });
1736
+ }
1737
+ missingMandatoryOptionValue(option) {
1738
+ const message = `error: required option '${option.flags}' not specified`;
1739
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1740
+ }
1741
+ _conflictingOption(option, conflictingOption) {
1742
+ const findBestOptionFromValue = (option2) => {
1743
+ const optionKey = option2.attributeName();
1744
+ const optionValue = this.getOptionValue(optionKey);
1745
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1746
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1747
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1748
+ return negativeOption;
1749
+ }
1750
+ return positiveOption || option2;
1751
+ };
1752
+ const getErrorMessage = (option2) => {
1753
+ const bestOption = findBestOptionFromValue(option2);
1754
+ const optionKey = bestOption.attributeName();
1755
+ const source = this.getOptionValueSource(optionKey);
1756
+ if (source === "env") {
1757
+ return `environment variable '${bestOption.envVar}'`;
1758
+ }
1759
+ return `option '${bestOption.flags}'`;
1760
+ };
1761
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1762
+ this.error(message, { code: "commander.conflictingOption" });
1763
+ }
1764
+ unknownOption(flag) {
1765
+ if (this._allowUnknownOption)
1766
+ return;
1767
+ let suggestion = "";
1768
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1769
+ let candidateFlags = [];
1770
+ let command = this;
1771
+ do {
1772
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1773
+ candidateFlags = candidateFlags.concat(moreFlags);
1774
+ command = command.parent;
1775
+ } while (command && !command._enablePositionalOptions);
1776
+ suggestion = suggestSimilar(flag, candidateFlags);
1777
+ }
1778
+ const message = `error: unknown option '${flag}'${suggestion}`;
1779
+ this.error(message, { code: "commander.unknownOption" });
1780
+ }
1781
+ _excessArguments(receivedArgs) {
1782
+ if (this._allowExcessArguments)
1783
+ return;
1784
+ const expected = this.registeredArguments.length;
1785
+ const s = expected === 1 ? "" : "s";
1786
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1787
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1788
+ this.error(message, { code: "commander.excessArguments" });
1789
+ }
1790
+ unknownCommand() {
1791
+ const unknownName = this.args[0];
1792
+ let suggestion = "";
1793
+ if (this._showSuggestionAfterError) {
1794
+ const candidateNames = [];
1795
+ this.createHelp().visibleCommands(this).forEach((command) => {
1796
+ candidateNames.push(command.name());
1797
+ if (command.alias())
1798
+ candidateNames.push(command.alias());
1799
+ });
1800
+ suggestion = suggestSimilar(unknownName, candidateNames);
1801
+ }
1802
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1803
+ this.error(message, { code: "commander.unknownCommand" });
1804
+ }
1805
+ version(str, flags, description) {
1806
+ if (str === undefined)
1807
+ return this._version;
1808
+ this._version = str;
1809
+ flags = flags || "-V, --version";
1810
+ description = description || "output the version number";
1811
+ const versionOption = this.createOption(flags, description);
1812
+ this._versionOptionName = versionOption.attributeName();
1813
+ this._registerOption(versionOption);
1814
+ this.on("option:" + versionOption.name(), () => {
1815
+ this._outputConfiguration.writeOut(`${str}
1816
+ `);
1817
+ this._exit(0, "commander.version", str);
1818
+ });
1819
+ return this;
1820
+ }
1821
+ description(str, argsDescription) {
1822
+ if (str === undefined && argsDescription === undefined)
1823
+ return this._description;
1824
+ this._description = str;
1825
+ if (argsDescription) {
1826
+ this._argsDescription = argsDescription;
1827
+ }
1828
+ return this;
1829
+ }
1830
+ summary(str) {
1831
+ if (str === undefined)
1832
+ return this._summary;
1833
+ this._summary = str;
1834
+ return this;
1835
+ }
1836
+ alias(alias) {
1837
+ if (alias === undefined)
1838
+ return this._aliases[0];
1839
+ let command = this;
1840
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1841
+ command = this.commands[this.commands.length - 1];
1842
+ }
1843
+ if (alias === command._name)
1844
+ throw new Error("Command alias can't be the same as its name");
1845
+ const matchingCommand = this.parent?._findCommand(alias);
1846
+ if (matchingCommand) {
1847
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1848
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1849
+ }
1850
+ command._aliases.push(alias);
1851
+ return this;
1852
+ }
1853
+ aliases(aliases) {
1854
+ if (aliases === undefined)
1855
+ return this._aliases;
1856
+ aliases.forEach((alias) => this.alias(alias));
1857
+ return this;
1858
+ }
1859
+ usage(str) {
1860
+ if (str === undefined) {
1861
+ if (this._usage)
1862
+ return this._usage;
1863
+ const args = this.registeredArguments.map((arg) => {
1864
+ return humanReadableArgName(arg);
1865
+ });
1866
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1867
+ }
1868
+ this._usage = str;
1869
+ return this;
1870
+ }
1871
+ name(str) {
1872
+ if (str === undefined)
1873
+ return this._name;
1874
+ this._name = str;
1875
+ return this;
1876
+ }
1877
+ helpGroup(heading) {
1878
+ if (heading === undefined)
1879
+ return this._helpGroupHeading ?? "";
1880
+ this._helpGroupHeading = heading;
1881
+ return this;
1882
+ }
1883
+ commandsGroup(heading) {
1884
+ if (heading === undefined)
1885
+ return this._defaultCommandGroup ?? "";
1886
+ this._defaultCommandGroup = heading;
1887
+ return this;
1888
+ }
1889
+ optionsGroup(heading) {
1890
+ if (heading === undefined)
1891
+ return this._defaultOptionGroup ?? "";
1892
+ this._defaultOptionGroup = heading;
1893
+ return this;
1894
+ }
1895
+ _initOptionGroup(option) {
1896
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1897
+ option.helpGroup(this._defaultOptionGroup);
1898
+ }
1899
+ _initCommandGroup(cmd) {
1900
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1901
+ cmd.helpGroup(this._defaultCommandGroup);
1902
+ }
1903
+ nameFromFilename(filename) {
1904
+ this._name = path.basename(filename, path.extname(filename));
1905
+ return this;
1906
+ }
1907
+ executableDir(path2) {
1908
+ if (path2 === undefined)
1909
+ return this._executableDir;
1910
+ this._executableDir = path2;
1911
+ return this;
1912
+ }
1913
+ helpInformation(contextOptions) {
1914
+ const helper = this.createHelp();
1915
+ const context = this._getOutputContext(contextOptions);
1916
+ helper.prepareContext({
1917
+ error: context.error,
1918
+ helpWidth: context.helpWidth,
1919
+ outputHasColors: context.hasColors
1920
+ });
1921
+ const text = helper.formatHelp(this, helper);
1922
+ if (context.hasColors)
1923
+ return text;
1924
+ return this._outputConfiguration.stripColor(text);
1925
+ }
1926
+ _getOutputContext(contextOptions) {
1927
+ contextOptions = contextOptions || {};
1928
+ const error = !!contextOptions.error;
1929
+ let baseWrite;
1930
+ let hasColors;
1931
+ let helpWidth;
1932
+ if (error) {
1933
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1934
+ hasColors = this._outputConfiguration.getErrHasColors();
1935
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1936
+ } else {
1937
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1938
+ hasColors = this._outputConfiguration.getOutHasColors();
1939
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1940
+ }
1941
+ const write = (str) => {
1942
+ if (!hasColors)
1943
+ str = this._outputConfiguration.stripColor(str);
1944
+ return baseWrite(str);
1945
+ };
1946
+ return { error, write, hasColors, helpWidth };
1947
+ }
1948
+ outputHelp(contextOptions) {
1949
+ let deprecatedCallback;
1950
+ if (typeof contextOptions === "function") {
1951
+ deprecatedCallback = contextOptions;
1952
+ contextOptions = undefined;
1953
+ }
1954
+ const outputContext = this._getOutputContext(contextOptions);
1955
+ const eventContext = {
1956
+ error: outputContext.error,
1957
+ write: outputContext.write,
1958
+ command: this
1959
+ };
1960
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1961
+ this.emit("beforeHelp", eventContext);
1962
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1963
+ if (deprecatedCallback) {
1964
+ helpInformation = deprecatedCallback(helpInformation);
1965
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1966
+ throw new Error("outputHelp callback must return a string or a Buffer");
1967
+ }
1968
+ }
1969
+ outputContext.write(helpInformation);
1970
+ if (this._getHelpOption()?.long) {
1971
+ this.emit(this._getHelpOption().long);
1972
+ }
1973
+ this.emit("afterHelp", eventContext);
1974
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1975
+ }
1976
+ helpOption(flags, description) {
1977
+ if (typeof flags === "boolean") {
1978
+ if (flags) {
1979
+ if (this._helpOption === null)
1980
+ this._helpOption = undefined;
1981
+ if (this._defaultOptionGroup) {
1982
+ this._initOptionGroup(this._getHelpOption());
1983
+ }
1984
+ } else {
1985
+ this._helpOption = null;
1986
+ }
1987
+ return this;
1988
+ }
1989
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
1990
+ if (flags || description)
1991
+ this._initOptionGroup(this._helpOption);
1992
+ return this;
1993
+ }
1994
+ _getHelpOption() {
1995
+ if (this._helpOption === undefined) {
1996
+ this.helpOption(undefined, undefined);
1997
+ }
1998
+ return this._helpOption;
1999
+ }
2000
+ addHelpOption(option) {
2001
+ this._helpOption = option;
2002
+ this._initOptionGroup(option);
2003
+ return this;
2004
+ }
2005
+ help(contextOptions) {
2006
+ this.outputHelp(contextOptions);
2007
+ let exitCode = Number(process2.exitCode ?? 0);
2008
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2009
+ exitCode = 1;
2010
+ }
2011
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2012
+ }
2013
+ addHelpText(position, text) {
2014
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2015
+ if (!allowedValues.includes(position)) {
2016
+ throw new Error(`Unexpected value for position to addHelpText.
2017
+ Expecting one of '${allowedValues.join("', '")}'`);
2018
+ }
2019
+ const helpEvent = `${position}Help`;
2020
+ this.on(helpEvent, (context) => {
2021
+ let helpStr;
2022
+ if (typeof text === "function") {
2023
+ helpStr = text({ error: context.error, command: context.command });
2024
+ } else {
2025
+ helpStr = text;
2026
+ }
2027
+ if (helpStr) {
2028
+ context.write(`${helpStr}
2029
+ `);
2030
+ }
2031
+ });
2032
+ return this;
2033
+ }
2034
+ _outputHelpIfRequested(args) {
2035
+ const helpOption = this._getHelpOption();
2036
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2037
+ if (helpRequested) {
2038
+ this.outputHelp();
2039
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2040
+ }
2041
+ }
2042
+ }
2043
+ function incrementNodeInspectorPort(args) {
2044
+ return args.map((arg) => {
2045
+ if (!arg.startsWith("--inspect")) {
2046
+ return arg;
2047
+ }
2048
+ let debugOption;
2049
+ let debugHost = "127.0.0.1";
2050
+ let debugPort = "9229";
2051
+ let match;
2052
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2053
+ debugOption = match[1];
2054
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2055
+ debugOption = match[1];
2056
+ if (/^\d+$/.test(match[3])) {
2057
+ debugPort = match[3];
2058
+ } else {
2059
+ debugHost = match[3];
2060
+ }
2061
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2062
+ debugOption = match[1];
2063
+ debugHost = match[3];
2064
+ debugPort = match[4];
2065
+ }
2066
+ if (debugOption && debugPort !== "0") {
2067
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2068
+ }
2069
+ return arg;
2070
+ });
2071
+ }
2072
+ function useColor() {
2073
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2074
+ return false;
2075
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2076
+ return true;
2077
+ return;
2078
+ }
2079
+ exports.Command = Command;
2080
+ exports.useColor = useColor;
2081
+ });
2082
+
2083
+ // ../../node_modules/commander/index.js
2084
+ var require_commander = __commonJS((exports) => {
2085
+ var { Argument } = require_argument();
2086
+ var { Command } = require_command();
2087
+ var { CommanderError, InvalidArgumentError } = require_error();
2088
+ var { Help } = require_help();
2089
+ var { Option } = require_option();
2090
+ exports.program = new Command;
2091
+ exports.createCommand = (name) => new Command(name);
2092
+ exports.createOption = (flags, description) => new Option(flags, description);
2093
+ exports.createArgument = (name, description) => new Argument(name, description);
2094
+ exports.Command = Command;
2095
+ exports.Option = Option;
2096
+ exports.Argument = Argument;
2097
+ exports.Help = Help;
2098
+ exports.CommanderError = CommanderError;
2099
+ exports.InvalidArgumentError = InvalidArgumentError;
2100
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2101
+ });
2102
+
2103
+ // ../../node_modules/commander/esm.mjs
2104
+ var import__ = __toESM(require_commander(), 1);
2105
+ var {
2106
+ program,
2107
+ createCommand,
2108
+ createArgument,
2109
+ createOption,
2110
+ CommanderError,
2111
+ InvalidArgumentError,
2112
+ InvalidOptionArgumentError,
2113
+ Command,
2114
+ Argument,
2115
+ Option,
2116
+ Help
2117
+ } = import__.default;
2118
+
2119
+ // ../common/src/singleton.ts
2120
+ var PREFIX = "@uipath/common/";
2121
+ var _g = globalThis;
2122
+ function singleton(ctorOrName) {
2123
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
2124
+ const key = Symbol.for(PREFIX + name);
2125
+ return {
2126
+ get(fallback) {
2127
+ return _g[key] ?? fallback;
2128
+ },
2129
+ set(value) {
2130
+ _g[key] = value;
2131
+ },
2132
+ clear() {
2133
+ delete _g[key];
2134
+ },
2135
+ getOrInit(factory, guard) {
2136
+ const existing = _g[key];
2137
+ if (existing != null && typeof existing === "object") {
2138
+ if (!guard || guard(existing)) {
2139
+ return existing;
2140
+ }
2141
+ }
2142
+ const instance = factory();
2143
+ _g[key] = instance;
2144
+ return instance;
2145
+ }
2146
+ };
2147
+ }
2148
+
2149
+ // ../common/src/preview.ts
2150
+ var previewSlot = singleton("PreviewBuild");
2151
+ function isPreviewBuild() {
2152
+ return previewSlot.get(false) ?? false;
2153
+ }
2154
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
2155
+ if (isPreviewBuild()) {
2156
+ return this.command(nameAndArgs, opts);
2157
+ }
2158
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
2159
+ };
2160
+
2161
+ // ../common/src/catch-error.ts
2162
+ function isPromiseLike(value) {
2163
+ return value !== null && typeof value === "object" && typeof value.then === "function";
2164
+ }
2165
+ function catchError(fnOrPromise) {
2166
+ if (isPromiseLike(fnOrPromise)) {
2167
+ return settlePromiseLike(fnOrPromise);
2168
+ }
2169
+ try {
2170
+ const result = fnOrPromise();
2171
+ if (isPromiseLike(result)) {
2172
+ return settlePromiseLike(result);
2173
+ }
2174
+ return [undefined, result];
2175
+ } catch (error) {
2176
+ return [
2177
+ error instanceof Error ? error : new Error(String(error)),
2178
+ undefined
2179
+ ];
2180
+ }
2181
+ }
2182
+ function settlePromiseLike(thenable) {
2183
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [
2184
+ error instanceof Error ? error : new Error(String(error)),
2185
+ undefined
2186
+ ]);
2187
+ }
2188
+
2189
+ // ../common/src/error-handler.ts
2190
+ var DEFAULT_401 = "Unauthorized (401). Run `uip login` to authenticate.";
2191
+ var DEFAULT_403 = "Forbidden (403). Ensure the account has the required permissions.";
2192
+ var DEFAULT_405 = "Method Not Allowed (405). The endpoint may not exist or the base URL may be incorrect.";
2193
+ 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.";
2194
+ var HTML_RESPONSE_MESSAGE = "Received HTML instead of the expected JSON response.";
2195
+ var NETWORK_ERROR_CODES = new Set([
2196
+ "ECONNREFUSED",
2197
+ "ECONNRESET",
2198
+ "ENOTFOUND",
2199
+ "EAI_AGAIN",
2200
+ "ETIMEDOUT",
2201
+ "EPIPE",
2202
+ "EHOSTUNREACH",
2203
+ "ENETUNREACH",
2204
+ "EAI_FAIL"
2205
+ ]);
2206
+ var TLS_ERROR_CODES = new Set([
2207
+ "SELF_SIGNED_CERT_IN_CHAIN",
2208
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2209
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2210
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2211
+ "UNABLE_TO_GET_ISSUER_CERT",
2212
+ "CERT_HAS_EXPIRED",
2213
+ "CERT_UNTRUSTED",
2214
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2215
+ ]);
2216
+ 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.";
2217
+ 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.";
2218
+ function describeConnectivityError(error) {
2219
+ const queue = [error];
2220
+ const seen = new Set;
2221
+ for (let steps = 0;queue.length > 0 && steps < 32; steps++) {
2222
+ const current = queue.shift();
2223
+ if (current === null || typeof current !== "object")
2224
+ continue;
2225
+ if (seen.has(current))
2226
+ continue;
2227
+ seen.add(current);
2228
+ const cur = current;
2229
+ const code = typeof cur.code === "string" ? cur.code : undefined;
2230
+ const message = typeof cur.message === "string" ? cur.message : undefined;
2231
+ if (code && TLS_ERROR_CODES.has(code)) {
2232
+ return {
2233
+ code,
2234
+ kind: "tls",
2235
+ message: message ?? code,
2236
+ instructions: TLS_INSTRUCTIONS
2237
+ };
2238
+ }
2239
+ if (code && NETWORK_ERROR_CODES.has(code)) {
2240
+ return {
2241
+ code,
2242
+ kind: "network",
2243
+ message: message ?? code,
2244
+ instructions: NETWORK_INSTRUCTIONS
2245
+ };
2246
+ }
2247
+ if (cur.cause !== undefined)
2248
+ queue.push(cur.cause);
2249
+ if (Array.isArray(cur.errors))
2250
+ queue.push(...cur.errors);
2251
+ }
2252
+ return;
2253
+ }
2254
+ function parseHttpStatusFromMessage(message) {
2255
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
2256
+ if (!match)
2257
+ return;
2258
+ const status = Number(match[1]);
2259
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
2260
+ }
2261
+ function isHtmlDocument(body) {
2262
+ return /^\s*(<!doctype html|<html\b)/i.test(body);
2263
+ }
2264
+ function retryHintForRetryAfter(seconds) {
2265
+ if (seconds <= 1) {
2266
+ return "RetryAfter1Second";
2267
+ }
2268
+ if (seconds <= 10) {
2269
+ return "RetryAfter10Seconds";
2270
+ }
2271
+ if (seconds <= 30) {
2272
+ return "RetryAfter30Seconds";
2273
+ }
2274
+ return "RetryAfter60Seconds";
2275
+ }
2276
+ function classifyError(status, error) {
2277
+ if (status === 400 || status === 409 || status === 422) {
2278
+ return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
2279
+ }
2280
+ if (status === 401) {
2281
+ return {
2282
+ errorCode: "authentication_required",
2283
+ retry: "RetryWillNotFix"
2284
+ };
2285
+ }
2286
+ if (status === 403) {
2287
+ return { errorCode: "permission_denied", retry: "RetryWillNotFix" };
2288
+ }
2289
+ if (status === 404) {
2290
+ return { errorCode: "not_found", retry: "RetryWillNotFix" };
2291
+ }
2292
+ if (status === 405) {
2293
+ return { errorCode: "method_not_allowed", retry: "RetryWillNotFix" };
2294
+ }
2295
+ if (status === 413) {
2296
+ return { errorCode: "invalid_argument", retry: "RetryWillNotFix" };
2297
+ }
2298
+ if (status === 408) {
2299
+ return { errorCode: "timeout", retry: "RetryLater" };
2300
+ }
2301
+ if (status === 429) {
2302
+ return { errorCode: "rate_limited", retry: "RetryLater" };
2303
+ }
2304
+ if (status !== undefined && status >= 500 && status < 600) {
2305
+ return { errorCode: "server_error", retry: "RetryLater" };
2306
+ }
2307
+ const connectivity = describeConnectivityError(error);
2308
+ if (connectivity) {
2309
+ return {
2310
+ errorCode: "network_error",
2311
+ retry: connectivity.kind === "tls" ? "RetryWillNotFix" : "RetryLater"
2312
+ };
2313
+ }
2314
+ return { errorCode: "unknown_error", retry: "RetryWillNotFix" };
2315
+ }
2316
+ function formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus) {
2317
+ if (extractedMessage) {
2318
+ return `HTTP ${status}: ${extractedMessage}`;
2319
+ }
2320
+ return inferredStatus !== undefined ? rawMessage : `HTTP ${status}: ${rawMessage}`;
2321
+ }
2322
+ async function extractErrorDetails(error, options) {
2323
+ const err = error !== null && error !== undefined && typeof error === "object" ? error : {};
2324
+ const response = err.response;
2325
+ const rawMessage = typeof err.message === "string" ? err.message : "Unknown error";
2326
+ const explicitStatus = err.status ?? response?.status;
2327
+ const inferredStatus = explicitStatus === undefined ? parseHttpStatusFromMessage(rawMessage) : undefined;
2328
+ const status = explicitStatus ?? inferredStatus;
2329
+ const isSuccessfulResponse = status !== undefined && status >= 200 && status < 300;
2330
+ let rawBody;
2331
+ let extractedMessage;
2332
+ let parsedBody;
2333
+ const textFn = response?.text?.bind(response);
2334
+ if (textFn) {
2335
+ const [bodyError, body] = await catchError((async () => textFn())());
2336
+ if (!bodyError && body) {
2337
+ rawBody = body;
2338
+ const [parseError, parsed] = catchError(() => JSON.parse(body));
2339
+ if (!parseError && parsed && typeof parsed === "object") {
2340
+ parsedBody = parsed;
2341
+ if (parsedBody.errors && typeof parsedBody.errors === "object") {
2342
+ for (const field of Object.values(parsedBody.errors)) {
2343
+ if (Array.isArray(field) && field.length > 0) {
2344
+ const first = field[0];
2345
+ if (first && typeof first.message === "string") {
2346
+ extractedMessage = first.message;
2347
+ break;
2348
+ }
2349
+ }
2350
+ }
2351
+ }
2352
+ if (!extractedMessage) {
2353
+ extractedMessage = typeof parsedBody.message === "string" ? parsedBody.message : typeof parsedBody.errorMessage === "string" ? parsedBody.errorMessage : typeof parsedBody.title === "string" ? parsedBody.title : undefined;
2354
+ }
2355
+ if (!extractedMessage) {
2356
+ extractedMessage = body;
2357
+ }
2358
+ if (extractedMessage && typeof parsedBody.detail === "string" && parsedBody.detail.length > 0 && !extractedMessage.includes(parsedBody.detail)) {
2359
+ extractedMessage = `${extractedMessage}: ${parsedBody.detail}`;
2360
+ }
2361
+ } else {
2362
+ extractedMessage = isHtmlDocument(body) ? HTML_RESPONSE_MESSAGE : body;
2363
+ }
2364
+ }
2365
+ }
2366
+ let message;
2367
+ let result = "Failure";
2368
+ const classification = classifyError(status, error);
2369
+ let retry = classification.retry;
2370
+ if (status === 401) {
2371
+ message = DEFAULT_401;
2372
+ result = "AuthenticationError";
2373
+ } else if (status === 403) {
2374
+ message = options?.forbiddenMessage ?? DEFAULT_403;
2375
+ result = "AuthenticationError";
2376
+ } else if (status === 405) {
2377
+ message = DEFAULT_405;
2378
+ } else if (status === 413) {
2379
+ message = DEFAULT_413;
2380
+ } else if (status === 400 || status === 422) {
2381
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
2382
+ result = "ValidationError";
2383
+ } else if (status === 429) {
2384
+ message = formatHttpStatusMessage(status, rawMessage, extractedMessage, inferredStatus);
2385
+ } else if (extractedMessage) {
2386
+ if (isSuccessfulResponse && rawMessage !== "Unknown error") {
2387
+ message = rawMessage;
2388
+ } else {
2389
+ message = status ? `HTTP ${status}: ${extractedMessage}` : extractedMessage;
2390
+ }
2391
+ } else if (status) {
2392
+ if (inferredStatus !== undefined) {
2393
+ message = rawMessage;
2394
+ } else if (rawMessage === "Unknown error" && response) {
2395
+ const statusText = response.statusText;
2396
+ message = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status} - request failed`;
2397
+ } else {
2398
+ message = `HTTP ${status}: ${rawMessage}`;
2399
+ }
2400
+ } else {
2401
+ message = rawMessage;
2402
+ }
2403
+ if (status === undefined) {
2404
+ const connectivity = describeConnectivityError(error);
2405
+ if (connectivity && connectivity.message !== message && !message.includes(connectivity.message)) {
2406
+ message = `${message}: ${connectivity.message}`;
2407
+ }
2408
+ }
2409
+ let details = rawMessage;
2410
+ if (rawBody) {
2411
+ if (parsedBody) {
2412
+ const extra = {};
2413
+ if (parsedBody.errorCode)
2414
+ extra.errorCode = parsedBody.errorCode;
2415
+ if (parsedBody.detail)
2416
+ extra.detail = parsedBody.detail;
2417
+ if (parsedBody.details)
2418
+ extra.details = parsedBody.details;
2419
+ if (parsedBody.errors != null)
2420
+ extra.errors = parsedBody.errors;
2421
+ if (parsedBody.data && typeof parsedBody.data === "object" && Object.keys(parsedBody.data).length > 0) {
2422
+ extra.data = parsedBody.data;
2423
+ }
2424
+ details = Object.keys(extra).length > 0 ? JSON.stringify(extra) : rawBody;
2425
+ } else {
2426
+ details = rawBody;
2427
+ }
2428
+ } else if (typeof err.message === "string") {
2429
+ details = err.message;
2430
+ } else {
2431
+ details = String(error);
2432
+ }
2433
+ const context = {};
2434
+ if (status) {
2435
+ context.httpStatus = status;
2436
+ }
2437
+ if (parsedBody?.errorCode && typeof parsedBody.errorCode === "string") {
2438
+ context.errorCode = parsedBody.errorCode;
2439
+ } else if (parsedBody?.code && typeof parsedBody.code === "string") {
2440
+ context.errorCode = parsedBody.code;
2441
+ }
2442
+ if (parsedBody?.requestId && typeof parsedBody.requestId === "string") {
2443
+ context.requestId = parsedBody.requestId;
2444
+ }
2445
+ if (parsedBody?.traceId && typeof parsedBody.traceId === "string") {
2446
+ context.traceId = parsedBody.traceId;
2447
+ }
2448
+ if (status === 429) {
2449
+ const resp = response;
2450
+ const headersObj = resp?.headers;
2451
+ let retryAfterValue;
2452
+ if (headersObj && typeof headersObj === "object" && typeof headersObj.get === "function") {
2453
+ retryAfterValue = headersObj.get("retry-after") ?? undefined;
2454
+ }
2455
+ if (!retryAfterValue && headersObj && typeof headersObj === "object") {
2456
+ const headers = headersObj;
2457
+ retryAfterValue = headers["retry-after"] ?? headers["Retry-After"];
2458
+ }
2459
+ if (retryAfterValue) {
2460
+ const seconds = Number(retryAfterValue);
2461
+ if (!Number.isNaN(seconds)) {
2462
+ context.retryAfter = seconds;
2463
+ retry = retryHintForRetryAfter(seconds);
2464
+ }
2465
+ }
2466
+ }
2467
+ const hasContext = Object.keys(context).length > 0;
2468
+ let parsedErrors;
2469
+ if (parsedBody?.errors && typeof parsedBody.errors === "object") {
2470
+ const errors = {};
2471
+ for (const [field, raw] of Object.entries(parsedBody.errors)) {
2472
+ if (Array.isArray(raw)) {
2473
+ const messages = raw.map((entry) => {
2474
+ if (typeof entry === "string")
2475
+ return entry;
2476
+ if (entry && typeof entry === "object" && typeof entry.message === "string") {
2477
+ return entry.message;
2478
+ }
2479
+ return String(entry);
2480
+ }).filter(Boolean);
2481
+ if (messages.length > 0)
2482
+ errors[field] = messages;
2483
+ } else if (typeof raw === "string") {
2484
+ errors[field] = [raw];
2485
+ }
2486
+ }
2487
+ if (Object.keys(errors).length > 0)
2488
+ parsedErrors = errors;
2489
+ }
2490
+ return {
2491
+ result,
2492
+ errorCode: classification.errorCode,
2493
+ message,
2494
+ retry,
2495
+ details,
2496
+ ...hasContext ? { context } : {},
2497
+ ...parsedErrors ? { parsedErrors } : {}
2498
+ };
2499
+ }
2500
+ async function extractErrorMessage(error, options) {
2501
+ const { message } = await extractErrorDetails(error, options);
2502
+ return message;
2503
+ }
2504
+ // ../common/src/command-examples.ts
2505
+ var examplesByCommand = new WeakMap;
2506
+ Command.prototype.examples = function(examples) {
2507
+ examplesByCommand.set(this, examples);
2508
+ return this;
2509
+ };
2510
+ // ../common/src/output-context.ts
2511
+ function createStorage() {
2512
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
2513
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
2514
+ return {
2515
+ getStore: () => {
2516
+ return;
2517
+ },
2518
+ run: (_store, fn) => fn()
2519
+ };
2520
+ }
2521
+ return new mod.AsyncLocalStorage;
2522
+ }
2523
+ var storageSingleton = singleton("OutputStorage");
2524
+ var sinkSlot = singleton("OutputSink");
2525
+ var outputStorage = storageSingleton.getOrInit(createStorage, (v) => ("getStore" in v));
2526
+ var CONSOLE_FALLBACK = {
2527
+ writeOut: (str) => process.stdout.write(str),
2528
+ writeErr: (str) => process.stderr.write(str),
2529
+ writeLog: (str) => process.stdout.write(str),
2530
+ capabilities: {
2531
+ isInteractive: false,
2532
+ canReadInput: false,
2533
+ supportsColor: false,
2534
+ outputWidth: 80
2535
+ }
2536
+ };
2537
+ function getOutputSink() {
2538
+ return outputStorage.getStore() ?? sinkSlot.get() ?? CONSOLE_FALLBACK;
2539
+ }
2540
+
2541
+ // ../common/src/logger.ts
2542
+ var logFilePathSlot = singleton("logFilePath");
2543
+ function setGlobalLogFilePath(path) {
2544
+ logFilePathSlot.set(path);
2545
+ }
2546
+ function getGlobalLogFilePath() {
2547
+ return logFilePathSlot.get("");
2548
+ }
2549
+ var DEFAULT_LOG_LEVEL = 3 /* ERROR */;
2550
+
2551
+ class SimpleLogger {
2552
+ __brand = "SimpleLogger";
2553
+ level;
2554
+ logFilePath;
2555
+ fileLoggingEnabled;
2556
+ pendingWrites = Promise.resolve();
2557
+ pendingInit = Promise.resolve();
2558
+ constructor() {
2559
+ this.level = SimpleLogger.resolveLevel();
2560
+ this.logFilePath = "";
2561
+ this.fileLoggingEnabled = false;
2562
+ }
2563
+ static getInstance() {
2564
+ return loggerSingleton.getOrInit(() => new SimpleLogger, (v) => ("__brand" in v) && v.__brand === "SimpleLogger");
2565
+ }
2566
+ static resetInstance() {
2567
+ loggerSingleton.clear();
2568
+ }
2569
+ static isNode = typeof process !== "undefined" && !!process.versions?.node;
2570
+ static resolveLevel() {
2571
+ if (SimpleLogger.isNode) {
2572
+ const explicitLevel = SimpleLogger.parseLevel(process.env?.UIP_LOG_LEVEL ?? "");
2573
+ if (explicitLevel !== undefined)
2574
+ return explicitLevel;
2575
+ const debugVal = process.env?.DEBUG;
2576
+ if (debugVal === "true" || debugVal === "1") {
2577
+ return 0 /* DEBUG */;
2578
+ }
2579
+ return DEFAULT_LOG_LEVEL;
2580
+ }
2581
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
2582
+ if (!localStorageError && hasDebug) {
2583
+ return 0 /* DEBUG */;
2584
+ }
2585
+ return DEFAULT_LOG_LEVEL;
2586
+ }
2587
+ static parseLevel(value) {
2588
+ switch (value.toLowerCase()) {
2589
+ case "debug":
2590
+ return 0 /* DEBUG */;
2591
+ case "info":
2592
+ return 1 /* INFO */;
2593
+ case "warn":
2594
+ return 2 /* WARN */;
2595
+ case "error":
2596
+ return 3 /* ERROR */;
2597
+ default:
2598
+ return;
2599
+ }
2600
+ }
2601
+ format(message, args) {
2602
+ if (args.length === 0)
2603
+ return `${message}
2604
+ `;
2605
+ return `${message} ${args.map(String).join(" ")}
2606
+ `;
2607
+ }
2608
+ isFileLoggingActive() {
2609
+ return this.fileLoggingEnabled || !!getGlobalLogFilePath();
2610
+ }
2611
+ writeToFile(formatted) {
2612
+ const path = this.logFilePath || getGlobalLogFilePath();
2613
+ if (!path)
2614
+ return;
2615
+ const timestamp = new Date().toISOString();
2616
+ this.pendingWrites = Promise.all([
2617
+ this.pendingWrites,
2618
+ this.pendingInit
2619
+ ]).then(() => getFileSystem().appendFile(path, `${timestamp} ${formatted}`).catch(() => {}));
2620
+ }
2621
+ debug(message, ...args) {
2622
+ if (this.level > 0 /* DEBUG */)
2623
+ return;
2624
+ const formatted = this.format(`[DEBUG] ${message}`, args);
2625
+ if (this.isFileLoggingActive()) {
2626
+ this.writeToFile(formatted);
2627
+ } else {
2628
+ getOutputSink().writeErr(formatted);
2629
+ }
2630
+ }
2631
+ info(message, ...args) {
2632
+ if (this.level > 1 /* INFO */)
2633
+ return;
2634
+ const formatted = this.format(message, args);
2635
+ if (this.isFileLoggingActive()) {
2636
+ this.writeToFile(formatted);
2637
+ } else {
2638
+ getOutputSink().writeErr(formatted);
2639
+ }
2640
+ }
2641
+ warn(message, ...args) {
2642
+ if (this.level > 2 /* WARN */)
2643
+ return;
2644
+ const formatted = this.format(`[WARN] ${message}`, args);
2645
+ if (this.isFileLoggingActive()) {
2646
+ this.writeToFile(formatted);
2647
+ } else {
2648
+ getOutputSink().writeErr(formatted);
2649
+ }
2650
+ }
2651
+ error(message, ...args) {
2652
+ if (this.level > 3 /* ERROR */)
2653
+ return;
2654
+ const formatted = this.format(`[ERROR] ${message}`, args);
2655
+ if (this.isFileLoggingActive()) {
2656
+ this.writeToFile(formatted);
2657
+ } else {
2658
+ getOutputSink().writeErr(formatted);
2659
+ }
2660
+ }
2661
+ getLevel() {
2662
+ return this.level;
2663
+ }
2664
+ setLevel(level) {
2665
+ this.level = level;
2666
+ }
2667
+ setFileLogging(enabled) {
2668
+ this.fileLoggingEnabled = enabled;
2669
+ if (!enabled) {
2670
+ this.logFilePath = "";
2671
+ setGlobalLogFilePath("");
2672
+ }
2673
+ }
2674
+ setLogFile(path) {
2675
+ this.logFilePath = path;
2676
+ setGlobalLogFilePath(path);
2677
+ if (!path)
2678
+ return;
2679
+ this.fileLoggingEnabled = true;
2680
+ const fs = getFileSystem();
2681
+ this.pendingInit = (async () => {
2682
+ const [error] = await catchError((async () => {
2683
+ await fs.mkdir(fs.path.dirname(path));
2684
+ await fs.writeFile(path, "");
2685
+ })());
2686
+ if (error)
2687
+ this.fileLoggingEnabled = false;
2688
+ })();
2689
+ }
2690
+ async flushFile() {
2691
+ await this.pendingInit;
2692
+ await this.pendingWrites;
2693
+ }
2694
+ getLogFilePath() {
2695
+ return this.logFilePath || getGlobalLogFilePath();
2696
+ }
2697
+ handleLog = (logMessage) => {
2698
+ const parts = [];
2699
+ if (logMessage.source) {
2700
+ parts.push(`[${logMessage.source}]`);
2701
+ }
2702
+ if (logMessage.sourceTarget) {
2703
+ parts.push(`[${logMessage.sourceTarget}]`);
2704
+ }
2705
+ parts.push(logMessage.message);
2706
+ const msg = parts.join(" ");
2707
+ switch (logMessage.logLevel) {
2708
+ case "Debug":
2709
+ this.debug(msg);
2710
+ break;
2711
+ case "Information":
2712
+ this.info(msg);
2713
+ break;
2714
+ case "Warning":
2715
+ this.warn(msg);
2716
+ break;
2717
+ case "Error":
2718
+ this.error(msg);
2719
+ break;
2720
+ default:
2721
+ this.info(msg);
2722
+ break;
2723
+ }
2724
+ };
2725
+ }
2726
+ var loggerSingleton = singleton(SimpleLogger);
2727
+ var logger = SimpleLogger.getInstance();
2728
+ function getLogFilePath() {
2729
+ return logger.getLogFilePath();
2730
+ }
2731
+
2732
+ // ../common/src/output-codecs.ts
2733
+ var yamlSlot = singleton("YamlCodec");
2734
+ var jmespathSlot = singleton("JmespathCodec");
2735
+ async function loadOutputCodecsAsync(needed) {
2736
+ const loads = [];
2737
+ if (needed.yaml && yamlSlot.get() === undefined) {
2738
+ loads.push(import("./js-yaml-cggj6w7q.js").then((mod) => {
2739
+ yamlSlot.set(mod);
2740
+ }));
2741
+ }
2742
+ if (needed.filter && jmespathSlot.get() === undefined) {
2743
+ loads.push(import("./index-9f8q2ege.js").then((mod) => {
2744
+ jmespathSlot.set(mod);
2745
+ }));
2746
+ }
2747
+ await Promise.all(loads);
2748
+ }
2749
+ function getYamlCodec() {
2750
+ return yamlSlot.get();
2751
+ }
2752
+ function getJmespathCodec() {
2753
+ return jmespathSlot.get();
2754
+ }
2755
+
2756
+ // ../common/src/output-format-context.ts
2757
+ var formatSlot = singleton("OutputFormat");
2758
+ var formatExplicitSlot = singleton("OutputFormatExplicit");
2759
+ var helpRequestedSlot = singleton("HelpRequested");
2760
+ var filterSlot = singleton("OutputFilter");
2761
+ function getOutputFormat() {
2762
+ return formatSlot.get("json");
2763
+ }
2764
+ function getOutputFormatExplicit() {
2765
+ return formatExplicitSlot.get(false) ?? false;
2766
+ }
2767
+ function getOutputFilter() {
2768
+ return filterSlot.get();
2769
+ }
2770
+
2771
+ // ../common/src/telemetry/command-terminal.ts
2772
+ var recordedFailureSlot = singleton("CommandTelemetryFailure");
2773
+ var AUTH_ERROR_CODES = new Set([
2774
+ "authentication_required",
2775
+ "permission_denied"
2776
+ ]);
2777
+ var VALIDATION_ERROR_CODES = new Set(["invalid_argument"]);
2778
+ var NETWORK_HTTP_ERROR_CODES = new Set([
2779
+ "network_error",
2780
+ "rate_limited",
2781
+ "server_error",
2782
+ "not_found",
2783
+ "method_not_allowed"
2784
+ ]);
2785
+ var TIMEOUT_ERROR_CODES = new Set(["timeout"]);
2786
+ var NETWORK_OS_ERROR_CODES = new Set([
2787
+ "ECONNREFUSED",
2788
+ "ECONNRESET",
2789
+ "ENOTFOUND",
2790
+ "EAI_AGAIN",
2791
+ "EPIPE",
2792
+ "EHOSTUNREACH",
2793
+ "ENETUNREACH",
2794
+ "EAI_FAIL"
2795
+ ]);
2796
+ var TIMEOUT_OS_ERROR_CODES = new Set(["ETIMEDOUT", "ESOCKETTIMEDOUT"]);
2797
+ var TLS_ERROR_CODES2 = new Set([
2798
+ "SELF_SIGNED_CERT_IN_CHAIN",
2799
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2800
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2801
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2802
+ "UNABLE_TO_GET_ISSUER_CERT",
2803
+ "CERT_HAS_EXPIRED",
2804
+ "CERT_UNTRUSTED",
2805
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2806
+ ]);
2807
+ var MISSING_DEPENDENCY_CODES = new Set([
2808
+ "MODULE_NOT_FOUND",
2809
+ "ERR_MODULE_NOT_FOUND"
2810
+ ]);
2811
+ var INTERNAL_ERROR_NAMES = new Set([
2812
+ "TypeError",
2813
+ "ReferenceError",
2814
+ "SyntaxError",
2815
+ "RangeError"
2816
+ ]);
2817
+ function isRecord(value) {
2818
+ return value !== null && typeof value === "object";
2819
+ }
2820
+ function stringField(value, field) {
2821
+ if (!isRecord(value)) {
2822
+ return;
2823
+ }
2824
+ const raw = value[field];
2825
+ return typeof raw === "string" ? raw : undefined;
2826
+ }
2827
+ function numberField(value, field) {
2828
+ if (!isRecord(value)) {
2829
+ return;
2830
+ }
2831
+ const raw = value[field];
2832
+ return typeof raw === "number" ? raw : undefined;
2833
+ }
2834
+ function findStringInCauseChain(error, field) {
2835
+ let current = error;
2836
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
2837
+ const value = stringField(current, field);
2838
+ if (value) {
2839
+ return value;
2840
+ }
2841
+ current = current.cause;
2842
+ }
2843
+ return;
2844
+ }
2845
+ function findCodeInCauseChain(error) {
2846
+ return findStringInCauseChain(error, "code");
2847
+ }
2848
+ function isSpawnEnoent(error) {
2849
+ const code = findCodeInCauseChain(error);
2850
+ if (code !== "ENOENT") {
2851
+ return false;
2852
+ }
2853
+ const syscall = findStringInCauseChain(error, "syscall");
2854
+ return syscall?.startsWith("spawn") === true;
2855
+ }
2856
+ function isCancellationError(error, exitCode, pollSignal) {
2857
+ if (exitCode === 130) {
2858
+ return true;
2859
+ }
2860
+ if (!isRecord(error)) {
2861
+ return false;
2862
+ }
2863
+ if (numberField(error, "exitCode") === 130) {
2864
+ return true;
2865
+ }
2866
+ const name = stringField(error, "name");
2867
+ if (name === "ExitPromptError") {
2868
+ return true;
2869
+ }
2870
+ if (name === "AbortError" && pollSignal?.aborted) {
2871
+ return true;
2872
+ }
2873
+ const message = stringField(error, "message");
2874
+ return message?.includes("SIGINT") === true;
2875
+ }
2876
+ function terminalSignalFor(input, outcome) {
2877
+ if (input.recordedFailure?.terminalSignal) {
2878
+ return input.recordedFailure.terminalSignal;
2879
+ }
2880
+ const explicit = findStringInCauseChain(input.error, "terminalSignal") ?? findStringInCauseChain(input.error, "signal");
2881
+ if (explicit) {
2882
+ return explicit;
2883
+ }
2884
+ return outcome === "cancelled" ? "SIGINT" : undefined;
2885
+ }
2886
+ function classifyHttpStatus(status) {
2887
+ if (status === 401 || status === 403) {
2888
+ return "auth";
2889
+ }
2890
+ if (status === 400 || status === 409 || status === 422) {
2891
+ return "validation";
2892
+ }
2893
+ if (status === 408) {
2894
+ return "timeout";
2895
+ }
2896
+ return "network_http";
2897
+ }
2898
+ function classifyFromResult(result) {
2899
+ switch (result) {
2900
+ case "AuthenticationError":
2901
+ return "auth";
2902
+ case "ValidationError":
2903
+ return "validation";
2904
+ case "TimeoutError":
2905
+ return "timeout";
2906
+ default:
2907
+ return;
2908
+ }
2909
+ }
2910
+ function classifyFromErrorCode(errorCode) {
2911
+ if (!errorCode) {
2912
+ return;
2913
+ }
2914
+ if (AUTH_ERROR_CODES.has(errorCode)) {
2915
+ return "auth";
2916
+ }
2917
+ if (VALIDATION_ERROR_CODES.has(errorCode)) {
2918
+ return "validation";
2919
+ }
2920
+ if (TIMEOUT_ERROR_CODES.has(errorCode)) {
2921
+ return "timeout";
2922
+ }
2923
+ if (NETWORK_HTTP_ERROR_CODES.has(errorCode)) {
2924
+ return "network_http";
2925
+ }
2926
+ return;
2927
+ }
2928
+ function classifyFromError(error) {
2929
+ const code = findCodeInCauseChain(error);
2930
+ if (code) {
2931
+ if (code.startsWith("commander.")) {
2932
+ return "validation";
2933
+ }
2934
+ if (NETWORK_OS_ERROR_CODES.has(code) || TLS_ERROR_CODES2.has(code)) {
2935
+ return "network_http";
2936
+ }
2937
+ if (TIMEOUT_OS_ERROR_CODES.has(code)) {
2938
+ return "timeout";
2939
+ }
2940
+ if (MISSING_DEPENDENCY_CODES.has(code) || isSpawnEnoent(error)) {
2941
+ return "missing_dependency";
2942
+ }
2943
+ }
2944
+ const message = stringField(error, "message");
2945
+ if (message?.includes("fetch failed") === true) {
2946
+ return "network_http";
2947
+ }
2948
+ const name = stringField(error, "name");
2949
+ if (name && INTERNAL_ERROR_NAMES.has(name)) {
2950
+ return "internal";
2951
+ }
2952
+ return;
2953
+ }
2954
+ function classifyError2(input) {
2955
+ const recorded = input.recordedFailure;
2956
+ if (recorded?.errorClass) {
2957
+ return recorded.errorClass;
2958
+ }
2959
+ const status = recorded?.context?.httpStatus;
2960
+ if (status !== undefined) {
2961
+ return classifyHttpStatus(status);
2962
+ }
2963
+ return classifyFromResult(recorded?.result) ?? classifyFromErrorCode(recorded?.errorCode) ?? classifyFromError(input.error) ?? "unknown";
2964
+ }
2965
+ function recordCommandFailureTelemetry(failure) {
2966
+ recordedFailureSlot.set(failure);
2967
+ }
2968
+ function clearRecordedCommandFailureTelemetry() {
2969
+ recordedFailureSlot.clear();
2970
+ }
2971
+ function takeRecordedCommandFailureTelemetry() {
2972
+ const failure = recordedFailureSlot.get();
2973
+ recordedFailureSlot.clear();
2974
+ return failure;
2975
+ }
2976
+ function buildCommandTerminalTelemetryProperties(input) {
2977
+ const cancelled = isCancellationError(input.error, input.exitCode, input.pollSignal);
2978
+ const outcome = input.recordedFailure?.terminalOutcome ?? (input.exitCode === 0 ? "success" : cancelled ? "cancelled" : "failure");
2979
+ const errorClass = outcome === "success" || outcome === "no_op" ? undefined : outcome === "cancelled" ? "user_cancelled" : classifyError2(input);
2980
+ const terminalSignal = terminalSignalFor(input, outcome);
2981
+ return {
2982
+ exit_code: input.exitCode,
2983
+ terminal_outcome: outcome,
2984
+ ...errorClass ? { error_class: errorClass } : {},
2985
+ ...terminalSignal ? { terminal_signal: terminalSignal } : {}
2986
+ };
2987
+ }
2988
+
2989
+ // ../common/src/telemetry/telemetry-events.ts
2990
+ var CommonTelemetryEvents = {
2991
+ Error: "uip.error",
2992
+ ShipSucceeded: "uip.ship.succeeded"
2993
+ };
2994
+
2995
+ // ../common/src/registry.ts
2996
+ import { execFileSync } from "node:child_process";
2997
+ function readRegistryValue(keyPath, valueName) {
2998
+ if (process.platform !== "win32") {
2999
+ return "";
3000
+ }
3001
+ const [error, output] = catchError(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
3002
+ encoding: "utf-8",
3003
+ stdio: ["pipe", "pipe", "pipe"]
3004
+ }));
3005
+ if (error) {
3006
+ return "";
3007
+ }
3008
+ const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
3009
+ return match?.[1]?.trim() ?? "";
3010
+ }
3011
+
3012
+ // ../common/src/telemetry/logger-telemetry-provider.ts
3013
+ class LoggerTelemetryProvider {
3014
+ analyticsUniqueId;
3015
+ constructor() {
3016
+ this.analyticsUniqueId = readRegistryValue("HKCU\\Software\\UiPath", "AnalyticsUniqueId");
3017
+ }
3018
+ enrich(properties) {
3019
+ return {
3020
+ ...properties,
3021
+ ...this.analyticsUniqueId ? { analyticsUniqueId: this.analyticsUniqueId } : {}
3022
+ };
3023
+ }
3024
+ async trackEvent(eventName, properties) {
3025
+ logger.debug(formatMessage("Event", eventName, this.enrich(properties)));
3026
+ }
3027
+ async trackException(error, properties) {
3028
+ logger.error(formatMessage("Exception", error.message, this.enrich({
3029
+ ...properties,
3030
+ stack: error.stack
3031
+ })));
3032
+ }
3033
+ async trackRequest(name, duration, success, properties) {
3034
+ logger.debug(formatMessage("Request", name, this.enrich({
3035
+ ...properties,
3036
+ duration: `${duration}ms`,
3037
+ success
3038
+ })));
3039
+ }
3040
+ async trackDependency(name, type, duration, success, properties) {
3041
+ logger.debug(formatMessage("Dependency", name, this.enrich({
3042
+ ...properties,
3043
+ type,
3044
+ duration: `${duration}ms`,
3045
+ success
3046
+ })));
3047
+ }
3048
+ }
3049
+ function formatMessage(category, name, properties) {
3050
+ let message = `[Telemetry] [${category}] ${name}`;
3051
+ if (properties && Object.keys(properties).length > 0) {
3052
+ const propsStr = Object.entries(properties).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}=${value}`).join(", ");
3053
+ if (propsStr) {
3054
+ message += ` | ${propsStr}`;
3055
+ }
3056
+ }
3057
+ return message;
3058
+ }
3059
+ // ../common/src/telemetry/detect-agent.ts
3060
+ var KNOWN_AGENTS = [
3061
+ { envVar: "CLAUDECODE", value: "1", id: "claude-code" },
3062
+ { envVar: "CURSOR_AGENT", value: "1", id: "cursor" },
3063
+ { envVar: "GEMINI_CLI", value: "1", id: "gemini-cli" },
3064
+ { envVar: "CODEX_THREAD_ID", id: "codex" },
3065
+ { envVar: "CODEX_SANDBOX", id: "codex" },
3066
+ { envVar: "AUGMENT_AGENT", value: "1", id: "augment" },
3067
+ { envVar: "CLINE_ACTIVE", value: "true", id: "cline" }
3068
+ ];
3069
+ function detectAgentFromEnv(env) {
3070
+ for (const agent of KNOWN_AGENTS) {
3071
+ const envValue = env[agent.envVar];
3072
+ if (agent.value !== undefined) {
3073
+ if (envValue === agent.value)
3074
+ return agent.id;
3075
+ } else {
3076
+ if (envValue)
3077
+ return agent.id;
3078
+ }
3079
+ }
3080
+ const agentEnv = env.AGENT;
3081
+ if (agentEnv) {
3082
+ if (agentEnv === "1" || agentEnv === "true")
3083
+ return "unknown";
3084
+ if (agentEnv.length <= 32)
3085
+ return agentEnv.toLowerCase();
3086
+ }
3087
+ return;
3088
+ }
3089
+ // ../common/src/telemetry/environment-info.ts
3090
+ var LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
3091
+ // ../common/src/telemetry/execution-context.ts
3092
+ var authSignalSlot = singleton("TelemetryExecutionContextAuthSignal");
3093
+ var isTruthy = (value) => value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
3094
+ var isEqual = (value, expected) => value?.toLowerCase() === expected;
3095
+ var CI_SIGNATURES = [
3096
+ {
3097
+ provider: "github_actions",
3098
+ matches: (env) => isTruthy(env.GITHUB_ACTIONS),
3099
+ isScheduler: (env) => env.GITHUB_EVENT_NAME === "schedule"
3100
+ },
3101
+ {
3102
+ provider: "azure_devops",
3103
+ matches: (env) => isTruthy(env.TF_BUILD),
3104
+ isScheduler: (env) => isEqual(env.BUILD_REASON, "schedule")
3105
+ },
3106
+ {
3107
+ provider: "gitlab",
3108
+ matches: (env) => isTruthy(env.GITLAB_CI),
3109
+ isScheduler: (env) => env.CI_PIPELINE_SOURCE === "schedule"
3110
+ },
3111
+ {
3112
+ provider: "circleci",
3113
+ matches: (env) => isTruthy(env.CIRCLECI),
3114
+ isScheduler: (env) => env.CIRCLE_PIPELINE_TRIGGER_SOURCE === "scheduled_pipeline"
3115
+ },
3116
+ {
3117
+ provider: "jenkins",
3118
+ matches: (env) => isTruthy(env.JENKINS_URL) || isTruthy(env.JENKINS_HOME)
3119
+ },
3120
+ {
3121
+ provider: "teamcity",
3122
+ matches: (env) => isTruthy(env.TEAMCITY_VERSION)
3123
+ },
3124
+ {
3125
+ provider: "buildkite",
3126
+ matches: (env) => isTruthy(env.BUILDKITE),
3127
+ isScheduler: (env) => env.BUILDKITE_SOURCE === "schedule"
3128
+ },
3129
+ {
3130
+ provider: "bitbucket",
3131
+ matches: (env) => isTruthy(env.BITBUCKET_BUILD_NUMBER)
3132
+ },
3133
+ {
3134
+ provider: "travis",
3135
+ matches: (env) => isTruthy(env.TRAVIS)
3136
+ },
3137
+ {
3138
+ provider: "appveyor",
3139
+ matches: (env) => isTruthy(env.APPVEYOR)
3140
+ },
3141
+ {
3142
+ provider: "generic",
3143
+ matches: (env) => isTruthy(env.CI)
3144
+ }
3145
+ ];
3146
+ function currentEnv() {
3147
+ return typeof process === "undefined" ? {} : process.env;
3148
+ }
3149
+ function currentTtyState() {
3150
+ if (typeof process === "undefined")
3151
+ return false;
3152
+ return Boolean(process.stdout?.isTTY || process.stdin?.isTTY || process.stderr?.isTTY);
3153
+ }
3154
+ function detectCi(env) {
3155
+ const signature = CI_SIGNATURES.find((candidate) => candidate.matches(env));
3156
+ if (!signature)
3157
+ return;
3158
+ return {
3159
+ executionContext: signature.isScheduler?.(env) ? "scheduler" : "ci",
3160
+ ciProvider: signature.provider
3161
+ };
3162
+ }
3163
+ function detectExecutionContext(options = {}) {
3164
+ const env = options.env ?? currentEnv();
3165
+ const ci = detectCi(env);
3166
+ if (ci)
3167
+ return ci;
3168
+ const agent = options.agent ?? detectAgentFromEnv(env);
3169
+ if (agent) {
3170
+ return { executionContext: "agent" };
3171
+ }
3172
+ const authSignal = options.authSignal ?? authSignalSlot.get();
3173
+ if (authSignal === "service_account") {
3174
+ return { executionContext: "service_account" };
3175
+ }
3176
+ const isTty = options.isTty ?? currentTtyState();
3177
+ if (isTty) {
3178
+ return { executionContext: "manual" };
3179
+ }
3180
+ return { executionContext: "unknown" };
3181
+ }
3182
+ function getExecutionContextTelemetryProperties() {
3183
+ const detected = detectExecutionContext();
3184
+ return {
3185
+ execution_context: detected.executionContext,
3186
+ ...detected.ciProvider ? { ci_provider: detected.ciProvider } : {}
3187
+ };
3188
+ }
3189
+ // ../common/src/telemetry/node-context-storage.ts
3190
+ import { AsyncLocalStorage } from "node:async_hooks";
3191
+
3192
+ class NodeContextStorage {
3193
+ storage = new AsyncLocalStorage;
3194
+ run(context, fn) {
3195
+ return this.storage.run(context, fn);
3196
+ }
3197
+ getContext() {
3198
+ return this.storage.getStore();
3199
+ }
3200
+ }
3201
+ // ../common/src/telemetry/trace-context.ts
3202
+ var TELEMETRY_TRACEPARENT_ENV = "TRACEPARENT";
3203
+ var TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/;
3204
+ function getProcessEnv() {
3205
+ return globalThis.process?.env;
3206
+ }
3207
+ function parseInboundTraceparent(value) {
3208
+ if (!value) {
3209
+ return;
3210
+ }
3211
+ const match = TRACEPARENT_PATTERN.exec(value.trim().toLowerCase());
3212
+ if (!match) {
3213
+ return;
3214
+ }
3215
+ const [, traceId, parentSpanId] = match;
3216
+ if (/^0+$/.test(traceId) || /^0+$/.test(parentSpanId)) {
3217
+ return;
3218
+ }
3219
+ return { traceId, parentSpanId };
3220
+ }
3221
+ function getInboundTraceContext() {
3222
+ return parseInboundTraceparent(getProcessEnv()?.[TELEMETRY_TRACEPARENT_ENV]);
3223
+ }
3224
+
3225
+ // ../common/src/telemetry/session-id.ts
3226
+ var TELEMETRY_SESSION_ID_ENV = "UIPATH_SESSION_ID";
3227
+ var SESSION_ID_MAX_LENGTH = 64;
3228
+ var RANDOM_SESSION_ID_LENGTH = 32;
3229
+ var TELEMETRY_SESSION_SOURCE_PROPERTY = "session_id_source";
3230
+ var CONTROL_CHARACTERS = /\p{Cc}/gu;
3231
+ var INHERITED_SESSION_SOURCES = [
3232
+ { envVar: "CLAUDE_CODE_SESSION_ID", source: "claude-code" },
3233
+ { envVar: "CODEX_THREAD_ID", source: "codex" },
3234
+ { envVar: "ANTIGRAVITY_TRAJECTORY_ID", source: "antigravity" },
3235
+ { envVar: "TERM_SESSION_ID", source: "terminal" },
3236
+ { envVar: "WT_SESSION", source: "terminal" }
3237
+ ];
3238
+ var telemetrySessionSlot = singleton("TelemetrySession");
3239
+ var telemetryOperationIdSlot = singleton("TelemetryOperationId");
3240
+ function getProcessEnv2() {
3241
+ return globalThis.process?.env;
3242
+ }
3243
+ function normalizeSessionId(value) {
3244
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
3245
+ return;
3246
+ }
3247
+ const cleaned = String(value).replace(CONTROL_CHARACTERS, "").trim().slice(0, SESSION_ID_MAX_LENGTH);
3248
+ return cleaned || undefined;
3249
+ }
3250
+ function getConfiguredTelemetrySessionId() {
3251
+ return normalizeSessionId(getProcessEnv2()?.[TELEMETRY_SESSION_ID_ENV]);
3252
+ }
3253
+ function getInheritedSession(env) {
3254
+ for (const candidate of INHERITED_SESSION_SOURCES) {
3255
+ const handle = normalizeSessionId(env[candidate.envVar]);
3256
+ if (handle) {
3257
+ return { id: handle, source: candidate.source };
3258
+ }
3259
+ }
3260
+ return;
3261
+ }
3262
+ function generateRandomSession() {
3263
+ const bytes = new Uint8Array(RANDOM_SESSION_ID_LENGTH / 2);
3264
+ crypto.getRandomValues(bytes);
3265
+ let hex = "";
3266
+ for (const byte of bytes) {
3267
+ hex += byte.toString(16).padStart(2, "0");
3268
+ }
3269
+ return { id: hex, source: "random" };
3270
+ }
3271
+ function resolveTelemetrySession() {
3272
+ const existing = telemetrySessionSlot.get();
3273
+ if (existing) {
3274
+ return existing;
3275
+ }
3276
+ const declaredHandle = getConfiguredTelemetrySessionId();
3277
+ const resolved = declaredHandle ? { id: declaredHandle, source: "declared" } : getInheritedSession(getProcessEnv2() ?? {}) ?? generateRandomSession();
3278
+ telemetrySessionSlot.set(resolved);
3279
+ return resolved;
3280
+ }
3281
+ function getTelemetrySessionSource() {
3282
+ return resolveTelemetrySession().source;
3283
+ }
3284
+ function getTelemetryOperationId() {
3285
+ const existing = telemetryOperationIdSlot.get();
3286
+ if (existing) {
3287
+ return existing;
3288
+ }
3289
+ const inboundTraceId = getInboundTraceContext()?.traceId;
3290
+ const generated = inboundTraceId ?? crypto.randomUUID().replaceAll("-", "");
3291
+ telemetryOperationIdSlot.set(generated);
3292
+ return generated;
3293
+ }
3294
+ // ../common/src/telemetry/global-telemetry-properties.ts
3295
+ var telemetryPropsSlot = singleton("TelemetryDefaultProps");
3296
+ function getGlobalTelemetryProperties() {
3297
+ return telemetryPropsSlot.get();
3298
+ }
3299
+
3300
+ // ../common/src/telemetry/pii-redactor.ts
3301
+ var REDACTED = "[REDACTED]";
3302
+ var MAX_VALUE_LENGTH = 200;
3303
+ var SENSITIVE_NAME_TOKENS = new Set([
3304
+ "token",
3305
+ "tokens",
3306
+ "secret",
3307
+ "secrets",
3308
+ "password",
3309
+ "passwords",
3310
+ "pwd",
3311
+ "credential",
3312
+ "credentials",
3313
+ "auth",
3314
+ "authentication",
3315
+ "authorization",
3316
+ "authority",
3317
+ "cert",
3318
+ "certificate",
3319
+ "certificates"
3320
+ ]);
3321
+ var SENSITIVE_KEY_PREFIXES = new Set([
3322
+ "api",
3323
+ "access",
3324
+ "client",
3325
+ "private",
3326
+ "public",
3327
+ "signing",
3328
+ "encryption",
3329
+ "session",
3330
+ "master",
3331
+ "shared",
3332
+ "root",
3333
+ "ssh",
3334
+ "rsa",
3335
+ "aes",
3336
+ "hmac",
3337
+ "oauth"
3338
+ ]);
3339
+ 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;
3340
+ var EMAIL_PATTERN = /\b[^\s@]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
3341
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
3342
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
3343
+ var USER_HOME_PATTERN = /([/\\])(Users|home)([/\\])([^/\\]+)/gi;
3344
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
3345
+ var URL_TRAILING_PUNCT = /[.,;:!?)\]}>'"]+$/;
3346
+ function shortHash(input) {
3347
+ let hash = 2166136261;
3348
+ for (let i = 0;i < input.length; i++) {
3349
+ hash ^= input.charCodeAt(i);
3350
+ hash = Math.imul(hash, 16777619);
3351
+ }
3352
+ return (hash >>> 0).toString(16).padStart(8, "0");
3353
+ }
3354
+ function redactUrl(raw) {
3355
+ try {
3356
+ const url = new URL(raw);
3357
+ return `${url.protocol}//${url.host}`;
3358
+ } catch {
3359
+ return `url#${shortHash(raw)}`;
3360
+ }
3361
+ }
3362
+ function redactValueDetectors(value) {
3363
+ let out = value;
3364
+ out = out.replace(JWT_PATTERN, () => REDACTED);
3365
+ out = out.replace(URL_PATTERN, (match) => {
3366
+ const trailing = match.match(URL_TRAILING_PUNCT)?.[0] ?? "";
3367
+ const core = trailing ? match.slice(0, -trailing.length) : match;
3368
+ return `${redactUrl(core)}${trailing}`;
3369
+ });
3370
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
3371
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${shortHash(match)}`);
3372
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${shortHash(match)}`);
3373
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
3374
+ if (out.length > MAX_VALUE_LENGTH) {
3375
+ out = `${out.slice(0, MAX_VALUE_LENGTH)}…`;
3376
+ }
3377
+ return out;
3378
+ }
3379
+ function redactValue(value) {
3380
+ return redactValueDetectors(value);
3381
+ }
3382
+ function redactError(error) {
3383
+ const safe = new Error(redactValueDetectors(error.message ?? ""));
3384
+ safe.name = error.name;
3385
+ safe.stack = typeof error.stack === "string" ? redactValueDetectors(error.stack) : undefined;
3386
+ return safe;
3387
+ }
3388
+ function nameTokens(name) {
3389
+ 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);
3390
+ }
3391
+ function isSensitiveName(name) {
3392
+ const tokens = nameTokens(name);
3393
+ for (let i = 0;i < tokens.length; i++) {
3394
+ const token = tokens[i];
3395
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
3396
+ return true;
3397
+ }
3398
+ if (token === "key" || token === "keys") {
3399
+ const prev = tokens[i - 1];
3400
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
3401
+ return true;
3402
+ }
3403
+ }
3404
+ }
3405
+ return false;
3406
+ }
3407
+ function redactProperty(name, value) {
3408
+ if (value === undefined || value === null) {
3409
+ return;
3410
+ }
3411
+ if (isSensitiveName(name)) {
3412
+ return REDACTED;
3413
+ }
3414
+ if (typeof value === "boolean" || typeof value === "number") {
3415
+ return value;
3416
+ }
3417
+ if (typeof value !== "string") {
3418
+ return "[OBJECT]";
3419
+ }
3420
+ return redactValueDetectors(value);
3421
+ }
3422
+ function redactProperties(properties) {
3423
+ const out = {};
3424
+ for (const [name, value] of Object.entries(properties)) {
3425
+ const redacted = redactProperty(name, value);
3426
+ if (redacted !== undefined) {
3427
+ out[name] = redacted;
3428
+ }
3429
+ }
3430
+ return out;
3431
+ }
3432
+
3433
+ // ../common/src/telemetry/telemetry-service.ts
3434
+ var TELEMETRY_OPERATION_ID_PROPERTY = "uip.trace.operation_id";
3435
+ var TELEMETRY_PARENT_ID_PROPERTY = "uip.trace.parent_id";
3436
+ var TELEMETRY_SPAN_ID_PROPERTY = "uip.trace.span_id";
3437
+
3438
+ class TelemetryService {
3439
+ telemetryProvider;
3440
+ contextStorage;
3441
+ operationId;
3442
+ defaultProperties;
3443
+ constructor(telemetryProvider, contextStorage) {
3444
+ this.telemetryProvider = telemetryProvider;
3445
+ this.contextStorage = contextStorage;
3446
+ }
3447
+ setOperationId(operationId) {
3448
+ this.operationId = operationId;
3449
+ }
3450
+ setProvider(provider) {
3451
+ this.telemetryProvider = provider;
3452
+ }
3453
+ setDefaultProperties(properties) {
3454
+ this.defaultProperties = properties === undefined ? undefined : { ...this.defaultProperties, ...properties };
3455
+ }
3456
+ trackEvent(name, properties) {
3457
+ const context = this.getCurrentContext();
3458
+ const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3459
+ this.telemetryProvider.trackEvent(name, enrichedProperties);
3460
+ }
3461
+ trackException(error, properties) {
3462
+ const context = this.getCurrentContext();
3463
+ const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3464
+ this.telemetryProvider.trackException(redactError(error), enrichedProperties);
3465
+ }
3466
+ async trackRequest(name, fn, properties) {
3467
+ const parentContext = this.getCurrentContext();
3468
+ const operationId = parentContext?.operationId ?? this.operationId ?? getTelemetryOperationId();
3469
+ const parentId = parentContext ? parentContext.id : this.inboundParentIdFor(operationId);
3470
+ const context = {
3471
+ operationId,
3472
+ ...parentId !== undefined ? { parentId } : {},
3473
+ id: this.generateId()
3474
+ };
3475
+ const startTime = performance.now();
3476
+ try {
3477
+ const result = await this.contextStorage.run(context, fn);
3478
+ const durationMs = performance.now() - startTime;
3479
+ const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3480
+ await this.telemetryProvider.trackRequest(name, durationMs, true, enrichedProperties);
3481
+ return result;
3482
+ } catch (error) {
3483
+ const durationMs = performance.now() - startTime;
3484
+ const err = error instanceof Error ? error : new Error(String(error));
3485
+ const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, context);
3486
+ await this.telemetryProvider.trackRequest(name, durationMs, false, enrichedProperties);
3487
+ throw error;
3488
+ }
3489
+ }
3490
+ trackRequestResult(name, durationMs, success, properties, context) {
3491
+ const requestContext = context ?? {
3492
+ operationId: this.operationId ?? getTelemetryOperationId(),
3493
+ id: this.generateId()
3494
+ };
3495
+ const enrichedProperties = this.enrichPropertiesWithContext(properties, requestContext);
3496
+ this.telemetryProvider.trackRequest(name, durationMs, success, enrichedProperties);
3497
+ }
3498
+ createRequestContext() {
3499
+ const operationId = this.operationId ?? getTelemetryOperationId();
3500
+ const parentId = this.inboundParentIdFor(operationId);
3501
+ return {
3502
+ operationId,
3503
+ ...parentId !== undefined ? { parentId } : {},
3504
+ id: this.generateId()
3505
+ };
3506
+ }
3507
+ inboundParentIdFor(operationId) {
3508
+ const inbound = getInboundTraceContext();
3509
+ return inbound && inbound.traceId === operationId ? inbound.parentSpanId : undefined;
3510
+ }
3511
+ runWithContext(context, fn) {
3512
+ return this.contextStorage.run(context, fn);
3513
+ }
3514
+ createDependencyContext() {
3515
+ const parentContext = this.getCurrentContext();
3516
+ if (!parentContext) {
3517
+ return;
3518
+ }
3519
+ return {
3520
+ operationId: parentContext.operationId,
3521
+ parentId: parentContext.id,
3522
+ id: this.generateId()
3523
+ };
3524
+ }
3525
+ trackDependencyResult(name, type, durationMs, success, properties, context, resultCode) {
3526
+ const enrichedProperties = this.enrichPropertiesWithContext(properties, context);
3527
+ this.telemetryProvider.trackDependency(redactValue(name), type, durationMs, success, enrichedProperties, resultCode);
3528
+ }
3529
+ async trackDependencyOperation(name, type, fn, properties) {
3530
+ const parentContext = this.getCurrentContext();
3531
+ const childContext = parentContext !== undefined ? {
3532
+ operationId: parentContext.operationId,
3533
+ parentId: parentContext.id,
3534
+ id: this.generateId()
3535
+ } : this.createRequestContext();
3536
+ const startTime = performance.now();
3537
+ try {
3538
+ const result = await this.contextStorage.run(childContext, fn);
3539
+ const durationMs = performance.now() - startTime;
3540
+ const enrichedProperties = this.enrichPropertiesWithContext(properties, childContext);
3541
+ await this.telemetryProvider.trackDependency(name, type, durationMs, true, enrichedProperties);
3542
+ return result;
3543
+ } catch (error) {
3544
+ const durationMs = performance.now() - startTime;
3545
+ const err = error instanceof Error ? error : new Error(String(error));
3546
+ const enrichedProperties = this.enrichPropertiesWithContext({ ...properties, errorMessage: err.message }, childContext);
3547
+ await this.telemetryProvider.trackDependency(name, type, durationMs, false, enrichedProperties);
3548
+ throw error;
3549
+ }
3550
+ }
3551
+ getCurrentContext() {
3552
+ return this.contextStorage.getContext();
3553
+ }
3554
+ enrichPropertiesWithContext(properties, context) {
3555
+ const globalProperties = getGlobalTelemetryProperties();
3556
+ const enriched = {
3557
+ ...getExecutionContextTelemetryProperties(),
3558
+ ...globalProperties,
3559
+ ...this.defaultProperties,
3560
+ ...redactProperties(properties ?? {}),
3561
+ [TELEMETRY_SESSION_SOURCE_PROPERTY]: getTelemetrySessionSource(),
3562
+ ...context ? {
3563
+ [TELEMETRY_OPERATION_ID_PROPERTY]: context.operationId,
3564
+ ...context.parentId !== undefined ? { [TELEMETRY_PARENT_ID_PROPERTY]: context.parentId } : {},
3565
+ [TELEMETRY_SPAN_ID_PROPERTY]: context.id
3566
+ } : {}
3567
+ };
3568
+ return enriched;
3569
+ }
3570
+ generateId() {
3571
+ const bytes = new Uint8Array(8);
3572
+ let hex = "";
3573
+ do {
3574
+ crypto.getRandomValues(bytes);
3575
+ hex = "";
3576
+ for (const byte of bytes) {
3577
+ hex += byte.toString(16).padStart(2, "0");
3578
+ }
3579
+ } while (/^0+$/.test(hex));
3580
+ return hex;
3581
+ }
3582
+ }
3583
+ // ../common/src/telemetry/proxy-http-agent.ts
3584
+ var slot = singleton("ProxyAuthHttpsAgent");
3585
+
3586
+ // ../common/src/telemetry/node-appinsights-telemetry-provider.ts
3587
+ var providerSlot = singleton("TelemetryProvider");
3588
+
3589
+ // ../common/src/telemetry/telemetry-spool.ts
3590
+ var sidecarEntrySlot = singleton("TelemetrySidecarEntry");
3591
+ var MAX_SPOOL_AGE_MS = 72 * 60 * 60 * 1000;
3592
+
3593
+ // ../common/src/telemetry/telemetry-init.ts
3594
+ var telemetryInstanceSlot = singleton("TelemetryService");
3595
+ var DEFAULT_AI_CONNECTION_STRING = atob("SW5zdHJ1bWVudGF0aW9uS2V5PTliZDM3NDgyLTgxMGUtNDQyYS1hYWE2LWQzOGVmNjVjNjY3NDtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9MzU2OTdlZjEtOGJkMC00ZjE5LWEyN2MtZDg3Y2NhYzY2ZDJj");
3596
+ function getGlobalTelemetryInstance() {
3597
+ const existing = telemetryInstanceSlot.get();
3598
+ if (existing && typeof existing === "object" && "trackEvent" in existing && typeof existing.trackEvent === "function") {
3599
+ return existing;
3600
+ }
3601
+ return;
3602
+ }
3603
+ var _localTelemetryInstance;
3604
+ function getTelemetryInstance() {
3605
+ const global = getGlobalTelemetryInstance();
3606
+ if (global)
3607
+ return global;
3608
+ if (!_localTelemetryInstance) {
3609
+ _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
3610
+ }
3611
+ return _localTelemetryInstance;
3612
+ }
3613
+ var telemetry = new Proxy({}, {
3614
+ get(_, prop) {
3615
+ const instance = getTelemetryInstance();
3616
+ const value = instance[prop];
3617
+ return typeof value === "function" ? value.bind(instance) : value;
3618
+ }
3619
+ });
3620
+
3621
+ // ../common/src/formatter.ts
3622
+ var CLI_ERROR_CODES = [
3623
+ "invalid_argument",
3624
+ "authentication_required",
3625
+ "permission_denied",
3626
+ "not_found",
3627
+ "rate_limited",
3628
+ "network_error",
3629
+ "timeout",
3630
+ "server_error",
3631
+ "method_not_allowed",
3632
+ "configuration_error",
3633
+ "unknown_error"
3634
+ ];
3635
+ var RETRY_HINTS = [
3636
+ "RetryWillNotFix",
3637
+ "RetryLater",
3638
+ "RetryAfter1Second",
3639
+ "RetryAfter10Seconds",
3640
+ "RetryAfter30Seconds",
3641
+ "RetryAfter60Seconds"
3642
+ ];
3643
+ var RESULTS = {
3644
+ Success: "Success",
3645
+ Failure: "Failure",
3646
+ ConfigError: "ConfigError",
3647
+ AuthenticationError: "AuthenticationError",
3648
+ ValidationError: "ValidationError",
3649
+ TimeoutError: "TimeoutError"
3650
+ };
3651
+ var EXIT_CODES = {
3652
+ Success: 0,
3653
+ Failure: 1,
3654
+ ConfigError: 1,
3655
+ AuthenticationError: 2,
3656
+ ValidationError: 3,
3657
+ TimeoutError: 4
3658
+ };
3659
+ class SuccessOutput {
3660
+ Result = RESULTS.Success;
3661
+ Code;
3662
+ Data;
3663
+ Pagination;
3664
+ Instructions;
3665
+ Log;
3666
+ constructor(code, data) {
3667
+ this.Code = code;
3668
+ this.Data = data;
3669
+ const logPath = getLogFilePath();
3670
+ if (logPath) {
3671
+ this.Log = logPath;
3672
+ }
3673
+ }
3674
+ }
3675
+ function escapeNonAscii(jsonText) {
3676
+ return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
3677
+ const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
3678
+ return `\\u${hex}`;
3679
+ });
3680
+ }
3681
+ function needsAsciiSafeJson(sink) {
3682
+ return process.platform === "win32" && !sink.capabilities.isInteractive;
3683
+ }
3684
+ function isPlainRecord(value) {
3685
+ if (value === null || typeof value !== "object")
3686
+ return false;
3687
+ const prototype = Object.getPrototypeOf(value);
3688
+ return prototype === Object.prototype || prototype === null;
3689
+ }
3690
+ function extractPagedRows(value) {
3691
+ if (Array.isArray(value) || !isPlainRecord(value))
3692
+ return null;
3693
+ const entries = Object.values(value);
3694
+ if (entries.length === 0)
3695
+ return null;
3696
+ let rows = null;
3697
+ let hasScalarSibling = false;
3698
+ for (const entry of entries) {
3699
+ if (Array.isArray(entry)) {
3700
+ if (rows !== null)
3701
+ return null;
3702
+ rows = entry;
3703
+ } else if (entry !== null && typeof entry === "object") {
3704
+ return null;
3705
+ } else {
3706
+ hasScalarSibling = true;
3707
+ }
3708
+ }
3709
+ if (rows === null || !hasScalarSibling)
3710
+ return null;
3711
+ return rows;
3712
+ }
3713
+ function toLowerCamelCaseKey(key) {
3714
+ if (!key)
3715
+ return key;
3716
+ if (/[_\-\s]/.test(key)) {
3717
+ const [firstPart, ...restParts] = key.split(/[_\-\s]+/).filter(Boolean);
3718
+ if (!firstPart)
3719
+ return key;
3720
+ return [
3721
+ toLowerCamelCaseSimpleKey(firstPart),
3722
+ ...restParts.map((part) => {
3723
+ const normalized = toLowerCamelCaseSimpleKey(part);
3724
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
3725
+ })
3726
+ ].join("");
3727
+ }
3728
+ return toLowerCamelCaseSimpleKey(key);
3729
+ }
3730
+ function toLowerCamelCaseSimpleKey(key) {
3731
+ if (/^[A-Z0-9]+$/.test(key))
3732
+ return key.toLowerCase();
3733
+ return key.replace(/^[A-Z]+(?=[A-Z][a-z]|\d|$)|^[A-Z]/, (match) => match.toLowerCase());
3734
+ }
3735
+ function toPascalCaseKey(key) {
3736
+ const lowerCamelKey = toLowerCamelCaseKey(key);
3737
+ return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
3738
+ }
3739
+ function toPascalCaseData(value) {
3740
+ if (Array.isArray(value))
3741
+ return value.map(toPascalCaseData);
3742
+ if (!isPlainRecord(value))
3743
+ return value;
3744
+ const result = {};
3745
+ for (const [key, nestedValue] of Object.entries(value)) {
3746
+ result[toPascalCaseKey(key)] = toPascalCaseData(nestedValue);
3747
+ }
3748
+ return result;
3749
+ }
3750
+ function normalizeDataKeys(data) {
3751
+ return toPascalCaseData(data);
3752
+ }
3753
+ function normalizeOutputKeys(data) {
3754
+ const result = {};
3755
+ for (const [key, value] of Object.entries(data)) {
3756
+ const pascalKey = toPascalCaseKey(key);
3757
+ result[pascalKey] = pascalKey === "Data" ? value : toPascalCaseData(value);
3758
+ }
3759
+ return result;
3760
+ }
3761
+ function printOutput(data, format = "json", logFn, asciiSafe = false) {
3762
+ if (!data) {
3763
+ logFn("Empty response object. No data to display.");
3764
+ return;
3765
+ }
3766
+ switch (format) {
3767
+ case "json": {
3768
+ const json = JSON.stringify(data, null, 2);
3769
+ logFn(asciiSafe ? escapeNonAscii(json) : json);
3770
+ break;
3771
+ }
3772
+ case "yaml":
3773
+ logFn(toYaml(data));
3774
+ break;
3775
+ case "plain": {
3776
+ if ("Data" in data && data.Data != null) {
3777
+ const pagedRows = extractPagedRows(data.Data);
3778
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
3779
+ items.forEach((item) => {
3780
+ const values = Object.values(item).map((v) => v ?? "").join("\t");
3781
+ logFn(values);
3782
+ });
3783
+ } else {
3784
+ const values = Object.values(data).map((v) => v ?? "").join("\t");
3785
+ logFn(values);
3786
+ }
3787
+ break;
3788
+ }
3789
+ default: {
3790
+ const hasData = "Data" in data && data.Data != null;
3791
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
3792
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
3793
+ if (hasData && !(rows !== null && rows.length === 0)) {
3794
+ const logValue = data.Log;
3795
+ if (rows !== null) {
3796
+ printResizableTable(rows, logFn, logValue);
3797
+ } else {
3798
+ printVerticalTable(data.Data, logFn, logValue);
3799
+ }
3800
+ } else {
3801
+ printTable([{ ...data }], logFn);
3802
+ }
3803
+ break;
3804
+ }
3805
+ }
3806
+ }
3807
+ function logOutput(data, format = "json") {
3808
+ const sink = getOutputSink();
3809
+ printOutput(data, format, (msg) => sink.writeOut(`${msg}
3810
+ `), needsAsciiSafeJson(sink));
3811
+ }
3812
+ function cellToString(val) {
3813
+ return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
3814
+ }
3815
+ function wrapText(text, width) {
3816
+ if (text.length <= width)
3817
+ return [text];
3818
+ const lines = [];
3819
+ for (let pos = 0;pos < text.length; pos += width) {
3820
+ lines.push(text.substring(pos, pos + width));
3821
+ }
3822
+ return lines;
3823
+ }
3824
+ function printTable(data, logFn, externalLogValue) {
3825
+ if (data.length === 0)
3826
+ return;
3827
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
3828
+ const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
3829
+ const header = keys.map((key, i) => key.padEnd(maxWidths[i])).join(" | ");
3830
+ logFn(header);
3831
+ logFn(keys.map((_, i) => "-".repeat(maxWidths[i])).join("-|-"));
3832
+ data.forEach((item) => {
3833
+ const row = keys.map((key, i) => cellToString(item[key]).padEnd(maxWidths[i])).join(" | ");
3834
+ logFn(row);
3835
+ });
3836
+ if (externalLogValue) {
3837
+ logFn("");
3838
+ logFn(`Log: ${externalLogValue}`);
3839
+ }
3840
+ }
3841
+ function isPlainObjectArray(value) {
3842
+ return Array.isArray(value) && value.length > 0 && value.every(isPlainRecord);
3843
+ }
3844
+ function isNonEmptyPlainObject(value) {
3845
+ return isPlainRecord(value) && Object.keys(value).length > 0;
3846
+ }
3847
+ var NESTED_INDENT = " ";
3848
+ function printVerticalTable(data, logFn = console.log, externalLogValue) {
3849
+ const keys = Object.keys(data).filter((key) => !["code", "log"].includes(key.toLowerCase()));
3850
+ if (keys.length === 0)
3851
+ return;
3852
+ const isBlockValue = (value) => isPlainObjectArray(value) || isNonEmptyPlainObject(value);
3853
+ const scalarKeys = keys.filter((key) => !isBlockValue(data[key]));
3854
+ const maxKeyWidth = scalarKeys.length > 0 ? Math.max(...scalarKeys.map((key) => key.length)) : 0;
3855
+ const termWidth = process.stdout.columns || 120;
3856
+ const nestedWidth = Math.max(termWidth - NESTED_INDENT.length, 1);
3857
+ keys.forEach((key) => {
3858
+ const value = data[key];
3859
+ if (isPlainObjectArray(value)) {
3860
+ logFn(`${key}:`);
3861
+ printResizableTable(value, (line) => logFn(`${NESTED_INDENT}${line}`), undefined, nestedWidth);
3862
+ return;
3863
+ }
3864
+ if (isNonEmptyPlainObject(value)) {
3865
+ logFn(`${key}:`);
3866
+ printVerticalTable(value, (line) => logFn(`${NESTED_INDENT}${line}`));
3867
+ return;
3868
+ }
3869
+ const keyCol = key.padEnd(maxKeyWidth);
3870
+ logFn(`${keyCol} | ${cellToString(value)}`);
3871
+ });
3872
+ if (externalLogValue) {
3873
+ logFn("");
3874
+ logFn(`Log: ${externalLogValue}`);
3875
+ }
3876
+ }
3877
+ function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth) {
3878
+ if (data.length === 0)
3879
+ return;
3880
+ const keys = Object.keys(data[0]).filter((key) => !["code", "log"].includes(key.toLowerCase()));
3881
+ if (keys.length === 0)
3882
+ return;
3883
+ if (!process.stdout.isTTY) {
3884
+ printTable(data, logFn, externalLogValue);
3885
+ return;
3886
+ }
3887
+ const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
3888
+ const separatorTotal = (keys.length - 1) * 3;
3889
+ const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
3890
+ const termWidth = availableWidth ?? (process.stdout.columns || 120);
3891
+ if (totalWidth <= termWidth) {
3892
+ printTable(data, logFn, externalLogValue);
3893
+ return;
3894
+ }
3895
+ const overflow = totalWidth - termWidth;
3896
+ const MIN_COL_WIDTH = 10;
3897
+ const minWidths = keys.map((key) => Math.max(key.length, MIN_COL_WIDTH));
3898
+ let bestCol = -1;
3899
+ let bestCost = Infinity;
3900
+ for (let i = 0;i < keys.length; i++) {
3901
+ const maxShrink = naturalWidths[i] - minWidths[i];
3902
+ if (maxShrink < overflow)
3903
+ continue;
3904
+ const newWidth = naturalWidths[i] - overflow;
3905
+ let extraRows = 0;
3906
+ for (const item of data) {
3907
+ const cellLen = cellToString(item[keys[i]]).length;
3908
+ if (cellLen > newWidth) {
3909
+ extraRows += Math.ceil(cellLen / newWidth) - 1;
3910
+ }
3911
+ }
3912
+ if (extraRows < bestCost) {
3913
+ bestCost = extraRows;
3914
+ bestCol = i;
3915
+ }
3916
+ }
3917
+ const finalWidths = [...naturalWidths];
3918
+ if (bestCol !== -1) {
3919
+ finalWidths[bestCol] = naturalWidths[bestCol] - overflow;
3920
+ } else {
3921
+ let remaining = overflow;
3922
+ const colsByShrinkPotential = keys.map((_, i) => ({
3923
+ index: i,
3924
+ potential: naturalWidths[i] - minWidths[i]
3925
+ })).filter((c) => c.potential > 0).sort((a, b) => b.potential - a.potential);
3926
+ for (const col of colsByShrinkPotential) {
3927
+ if (remaining <= 0)
3928
+ break;
3929
+ const shrink = Math.min(remaining, col.potential);
3930
+ finalWidths[col.index] -= shrink;
3931
+ remaining -= shrink;
3932
+ }
3933
+ }
3934
+ const header = keys.map((key, i) => key.padEnd(finalWidths[i])).join(" | ");
3935
+ logFn(header);
3936
+ logFn(keys.map((_, i) => "-".repeat(finalWidths[i])).join("-|-"));
3937
+ data.forEach((item) => {
3938
+ const cellLines = keys.map((key, i) => wrapText(cellToString(item[key]), finalWidths[i]));
3939
+ const lineCount = Math.max(...cellLines.map((l) => l.length));
3940
+ for (let line = 0;line < lineCount; line++) {
3941
+ const row = keys.map((_, i) => {
3942
+ const val = line < cellLines[i].length ? cellLines[i][line] : "";
3943
+ return val.padEnd(finalWidths[i]);
3944
+ }).join(" | ");
3945
+ logFn(row);
3946
+ }
3947
+ });
3948
+ if (externalLogValue) {
3949
+ logFn("");
3950
+ logFn(`Log: ${externalLogValue}`);
3951
+ }
3952
+ }
3953
+ function toYaml(data) {
3954
+ const codec = getYamlCodec();
3955
+ if (!codec) {
3956
+ throw new Error("YAML output requested before the YAML codec was loaded. " + "Call loadOutputCodecsAsync({ yaml: true }) first.");
3957
+ }
3958
+ return codec.dump(data);
3959
+ }
3960
+ function requireJmespath() {
3961
+ const codec = getJmespathCodec();
3962
+ if (!codec) {
3963
+ throw new Error("An --output-filter was applied before the JMESPath codec was loaded. " + "Call loadOutputCodecsAsync({ filter: true }) first.");
3964
+ }
3965
+ return codec;
3966
+ }
3967
+
3968
+ class FilterEvaluationError extends Error {
3969
+ __brand = "FilterEvaluationError";
3970
+ filter;
3971
+ errorCode = "invalid_argument";
3972
+ instructions;
3973
+ retry = "RetryWillNotFix";
3974
+ result = RESULTS.ValidationError;
3975
+ constructor(filter, cause) {
3976
+ const underlying = cause instanceof Error ? cause.message : String(cause);
3977
+ super(`Filter '${filter}' failed to evaluate: ${underlying}`);
3978
+ this.name = "FilterEvaluationError";
3979
+ this.filter = filter;
3980
+ this.instructions = `The --output-filter expression '${filter}' failed at evaluation time. ` + "Note that --output-filter operates on the 'Data' field of the envelope, not the full object. " + "For example, on a list result use 'length(@)' instead of 'Data | length(@)'.";
3981
+ }
3982
+ }
3983
+
3984
+ class FilterImplicitLimitError extends Error {
3985
+ __brand = "FilterImplicitLimitError";
3986
+ errorCode = "invalid_argument";
3987
+ instructions;
3988
+ retry = "RetryWillNotFix";
3989
+ result = RESULTS.ValidationError;
3990
+ constructor(defaultLimit) {
3991
+ super(`--output-filter requires an explicit --limit: this command defaults to --limit ${defaultLimit}, ` + `so the filter would silently apply to only the first ${defaultLimit} records.`);
3992
+ this.name = "FilterImplicitLimitError";
3993
+ this.instructions = "Pass --limit <n> to choose how many records the filter applies to. " + "To filter over all records, pass the command's maximum accepted --limit (see the option's description in --help).";
3994
+ }
3995
+ }
3996
+ function applyFilter(data, filter) {
3997
+ const codec = requireJmespath();
3998
+ let result;
3999
+ try {
4000
+ result = codec.search(data, filter);
4001
+ } catch (err) {
4002
+ throw new FilterEvaluationError(filter, err);
4003
+ }
4004
+ if (result == null)
4005
+ return [];
4006
+ if (Array.isArray(result)) {
4007
+ if (result.length > 0 && typeof result[0] !== "object") {
4008
+ const fieldMatch = filter.match(/\.(\w+)$/);
4009
+ const key = fieldMatch ? fieldMatch[1] : "Value";
4010
+ return result.map((v) => ({ [key]: v }));
4011
+ }
4012
+ return result;
4013
+ }
4014
+ if (typeof result === "object")
4015
+ return result;
4016
+ return { Value: result };
4017
+ }
4018
+ function defaultErrorCodeForResult(result) {
4019
+ switch (result) {
4020
+ case RESULTS.AuthenticationError:
4021
+ return "authentication_required";
4022
+ case RESULTS.ConfigError:
4023
+ return "configuration_error";
4024
+ case RESULTS.ValidationError:
4025
+ return "invalid_argument";
4026
+ case RESULTS.TimeoutError:
4027
+ return "timeout";
4028
+ default:
4029
+ return "unknown_error";
4030
+ }
4031
+ }
4032
+ function parseHttpStatusFromMessage2(message) {
4033
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
4034
+ if (!match)
4035
+ return;
4036
+ const status = Number(match[1]);
4037
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
4038
+ }
4039
+ function defaultErrorCodeForHttpStatus(status) {
4040
+ if (status === undefined)
4041
+ return;
4042
+ if (status === 400 || status === 409 || status === 422) {
4043
+ return "invalid_argument";
4044
+ }
4045
+ if (status === 401)
4046
+ return "authentication_required";
4047
+ if (status === 403)
4048
+ return "permission_denied";
4049
+ if (status === 404)
4050
+ return "not_found";
4051
+ if (status === 405)
4052
+ return "method_not_allowed";
4053
+ if (status === 408)
4054
+ return "timeout";
4055
+ if (status === 429)
4056
+ return "rate_limited";
4057
+ if (status >= 500 && status < 600)
4058
+ return "server_error";
4059
+ return;
4060
+ }
4061
+ function defaultErrorCodeForFailure(data) {
4062
+ if (data.Result === RESULTS.Failure) {
4063
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage2(data.Message);
4064
+ const errorCode = defaultErrorCodeForHttpStatus(status);
4065
+ if (errorCode)
4066
+ return errorCode;
4067
+ }
4068
+ return defaultErrorCodeForResult(data.Result);
4069
+ }
4070
+ function defaultRetryForErrorCode(errorCode) {
4071
+ switch (errorCode) {
4072
+ case "network_error":
4073
+ case "rate_limited":
4074
+ case "server_error":
4075
+ case "timeout":
4076
+ return "RetryLater";
4077
+ default:
4078
+ return "RetryWillNotFix";
4079
+ }
4080
+ }
4081
+ var OutputFormatter;
4082
+ ((OutputFormatter) => {
4083
+ function success(data, options) {
4084
+ data.Log ??= getLogFilePath() || undefined;
4085
+ const normalize = !options?.preserveDataKeys;
4086
+ if (normalize) {
4087
+ data.Data = normalizeDataKeys(data.Data);
4088
+ }
4089
+ const filter = getOutputFilter();
4090
+ if (filter) {
4091
+ const filtered = applyFilter(data.Data, filter);
4092
+ data.Data = normalize ? normalizeDataKeys(filtered) : filtered;
4093
+ }
4094
+ logOutput(normalizeOutputKeys(data), getOutputFormat());
4095
+ }
4096
+ OutputFormatter.success = success;
4097
+ function error(data) {
4098
+ data.Log ??= getLogFilePath() || undefined;
4099
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
4100
+ data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
4101
+ process.exitCode = EXIT_CODES[data.Result] ?? 1;
4102
+ recordCommandFailureTelemetry({
4103
+ result: data.Result,
4104
+ errorCode: data.ErrorCode,
4105
+ retry: data.Retry,
4106
+ message: data.Message,
4107
+ context: data.Context,
4108
+ exitCode: process.exitCode,
4109
+ errorClass: data.TelemetryErrorClass,
4110
+ terminalOutcome: data.TelemetryTerminalOutcome,
4111
+ terminalSignal: data.TelemetryTerminalSignal
4112
+ });
4113
+ const suppressTelemetry = data.SuppressTelemetry === true;
4114
+ const envelope = { ...data };
4115
+ delete envelope.SuppressTelemetry;
4116
+ delete envelope.TelemetryErrorClass;
4117
+ delete envelope.TelemetryTerminalOutcome;
4118
+ delete envelope.TelemetryTerminalSignal;
4119
+ if (!suppressTelemetry) {
4120
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
4121
+ result: data.Result,
4122
+ errorCode: data.ErrorCode,
4123
+ retry: data.Retry,
4124
+ message: data.Message
4125
+ });
4126
+ }
4127
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
4128
+ }
4129
+ OutputFormatter.error = error;
4130
+ function emitList(code, items, opts) {
4131
+ const data = {
4132
+ Result: RESULTS.Success,
4133
+ Code: code,
4134
+ Data: items
4135
+ };
4136
+ if (items.length === 0 && opts?.emptyInstructions) {
4137
+ data.Instructions = opts.emptyInstructions;
4138
+ }
4139
+ if (opts?.warning) {
4140
+ data.Warning = opts.warning;
4141
+ }
4142
+ if (opts?.pagination) {
4143
+ data.Pagination = opts.pagination;
4144
+ }
4145
+ success(data);
4146
+ }
4147
+ OutputFormatter.emitList = emitList;
4148
+ function log(data) {
4149
+ const format = getOutputFormat();
4150
+ const sink = getOutputSink();
4151
+ const normalized = toPascalCaseData(data);
4152
+ if (format === "json") {
4153
+ const json = JSON.stringify(normalized);
4154
+ const safe = needsAsciiSafeJson(sink) ? escapeNonAscii(json) : json;
4155
+ sink.writeErr(`${safe}
4156
+ `);
4157
+ } else {
4158
+ for (const [key, value] of Object.entries(normalized)) {
4159
+ sink.writeErr(`${key}: ${value}
4160
+ `);
4161
+ }
4162
+ }
4163
+ }
4164
+ OutputFormatter.log = log;
4165
+ function formatToString(data) {
4166
+ const filter = getOutputFilter();
4167
+ if ("Data" in data && data.Data != null) {
4168
+ data.Data = normalizeDataKeys(data.Data);
4169
+ if (filter) {
4170
+ data.Data = normalizeDataKeys(applyFilter(data.Data, filter));
4171
+ }
4172
+ }
4173
+ const output = normalizeOutputKeys(data);
4174
+ const lines = [];
4175
+ const sink = getOutputSink();
4176
+ printOutput(output, getOutputFormat(), (msg) => {
4177
+ lines.push(msg);
4178
+ }, needsAsciiSafeJson(sink));
4179
+ return lines.join(`
4180
+ `);
4181
+ }
4182
+ OutputFormatter.formatToString = formatToString;
4183
+ })(OutputFormatter ||= {});
4184
+
4185
+ // ../common/src/telemetry/command-attribution.ts
4186
+ var LEGACY_SKILL_NAMESPACE = "uipath:";
4187
+ var MAX_SKILL_NAME_LENGTH = 80;
4188
+ var SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
4189
+ function productMode(productArea, mode) {
4190
+ return { product_area: productArea, mode };
4191
+ }
4192
+ function attributionRecord(groups) {
4193
+ const record = {};
4194
+ for (const [productArea, mode, names] of groups) {
4195
+ const attribution = productMode(productArea, mode);
4196
+ for (const name of names) {
4197
+ record[name] = attribution;
4198
+ }
4199
+ }
4200
+ return record;
4201
+ }
4202
+ function commandAttribution(groups) {
4203
+ const entries = [];
4204
+ for (const [productArea, mode, prefixes] of groups) {
4205
+ const attribution = productMode(productArea, mode);
4206
+ for (const prefix of prefixes) {
4207
+ entries.push({ prefix, attribution });
4208
+ }
4209
+ }
4210
+ return entries;
4211
+ }
4212
+ var SKILL_ATTRIBUTION = attributionRecord([
4213
+ ["admin", "operate", ["uipath-admin"]],
4214
+ ["agents", "build", ["uipath-agents"]],
4215
+ ["api-workflow", "build", ["uipath-api-workflow"]],
4216
+ ["automation-discovery", "build", ["uipath-automation-discovery"]],
4217
+ ["coded-apps", "build", ["uipath-coded-apps"]],
4218
+ ["data-fabric", "operate", ["uipath-data-fabric"]],
4219
+ ["cli", "troubleshoot", ["uipath-feedback"]],
4220
+ ["governance", "operate", ["uipath-governance"]],
4221
+ ["action-center", "build", ["uipath-human-in-the-loop"]],
4222
+ ["document-understanding", "build", ["uipath-ixp"]],
4223
+ [
4224
+ "maestro",
4225
+ "build",
4226
+ ["uipath-maestro-bpmn", "uipath-maestro-case", "uipath-maestro-flow"]
4227
+ ],
4228
+ ["agenthub", "build", ["uipath-mcp-servers"]],
4229
+ ["solution", "build", ["uipath-planner", "uipath-solution"]],
4230
+ ["platform", "operate", ["uipath-platform"]],
4231
+ ["quality", "troubleshoot", ["uipath-review"]],
4232
+ ["rpa", "build", ["uipath-rpa"]],
4233
+ ["cli", "operate", ["uipath-skill-catalog"]],
4234
+ ["action-center", "operate", ["uipath-tasks"]],
4235
+ ["test-manager", "operate", ["uipath-test"]],
4236
+ ["platform", "troubleshoot", ["uipath-troubleshoot"]]
4237
+ ]);
4238
+ var KNOWN_SKILL_NAMES = new Set(Object.keys(SKILL_ATTRIBUTION));
4239
+ var COMMAND_ATTRIBUTION = commandAttribution([
4240
+ ["cli", "troubleshoot", ["uip.feedback"]],
4241
+ ["llm-gateway", "operate", ["uip.llm-gateway"]],
4242
+ ["llm-gateway", "operate", ["uip.llm-configuration", "uip.model-hub"]],
4243
+ ["context-grounding", "build", ["uip.context-grounding"]],
4244
+ ["api-workflow", "build", ["uip.api-workflow"]],
4245
+ ["rpa", "build", ["uip.rpa-legacy"]],
4246
+ ["conversational", "operate", ["uip.conversational"]],
4247
+ ["agents", "build", ["uip.codedagent", "uip.agent"]],
4248
+ ["agenthub", "build", ["uip.agenthub"]],
4249
+ ["coded-apps", "build", ["uip.codedapp"]],
4250
+ ["functions", "build", ["uip.function", "uip.functions"]],
4251
+ ["solution", "build", ["uip.solution"]],
4252
+ ["maestro", "build", ["uip.maestro", "uip.case", "uip.flow"]],
4253
+ ["llm-observability", "troubleshoot", ["uip.traces"]],
4254
+ ["platform", "operate", ["uip.platform"]],
4255
+ ["admin", "operate", ["uip.admin"]],
4256
+ ["automation-ops", "operate", ["uip.aops"]],
4257
+ ["documentation", "troubleshoot", ["uip.docsai"]],
4258
+ ["governance", "operate", ["uip.gov"]],
4259
+ ["insights", "operate", ["uip.insights"]],
4260
+ ["document-understanding", "build", ["uip.ixp"]],
4261
+ ["process-mining", "operate", ["uip.pm"]],
4262
+ ["action-center", "operate", ["uip.tasks"]],
4263
+ ["test-manager", "operate", ["uip.tm"]],
4264
+ ["vertical-solutions", "build", ["uip.vss"]],
4265
+ ["data-fabric", "operate", ["uip.df"]],
4266
+ ["integration-service", "build", ["uip.is"]],
4267
+ ["orchestrator", "operate", ["uip.or"]],
4268
+ [
4269
+ "cli",
4270
+ "operate",
4271
+ [
4272
+ "uip.login",
4273
+ "uip.logout",
4274
+ "uip.user",
4275
+ "uip.config",
4276
+ "uip.tools",
4277
+ "uip.skills",
4278
+ "uip.completion",
4279
+ "uip.update",
4280
+ "uip.mcp",
4281
+ "uip.track"
4282
+ ]
4283
+ ]
4284
+ ]).sort((a, b) => b.prefix.length - a.prefix.length);
4285
+ function normalizeCommandPath(value) {
4286
+ if (typeof value !== "string") {
4287
+ return;
4288
+ }
4289
+ const trimmed = value.trim().toLowerCase();
4290
+ if (!trimmed) {
4291
+ return;
4292
+ }
4293
+ const tokens = trimmed.includes(" ") ? trimmed.split(/\s+/).filter((token) => token.length > 0).filter((token) => !token.startsWith("-")) : trimmed.split(".").filter((token) => token.length > 0);
4294
+ if (tokens.length === 0) {
4295
+ return;
4296
+ }
4297
+ const commandTokens = tokens[0] === "uip" ? tokens : ["uip", ...tokens];
4298
+ return commandTokens.join(".");
4299
+ }
4300
+ function getCommandProductModeAttribution(commandPath) {
4301
+ const normalized = normalizeCommandPath(commandPath);
4302
+ if (!normalized) {
4303
+ return;
4304
+ }
4305
+ return COMMAND_ATTRIBUTION.find(({ prefix }) => normalized === prefix || normalized.startsWith(`${prefix}.`))?.attribution;
4306
+ }
4307
+ function normalizeSkillNameWithOptions(value, options) {
4308
+ if (typeof value !== "string") {
4309
+ return;
4310
+ }
4311
+ const normalized = value.trim().toLowerCase();
4312
+ if (!normalized) {
4313
+ return;
4314
+ }
4315
+ const hasLegacyNamespace = normalized.startsWith(LEGACY_SKILL_NAMESPACE);
4316
+ if (hasLegacyNamespace && !options.allowLegacyNamespace) {
4317
+ return;
4318
+ }
4319
+ const skillName = hasLegacyNamespace ? normalized.slice(LEGACY_SKILL_NAMESPACE.length) : normalized;
4320
+ if (skillName.length > MAX_SKILL_NAME_LENGTH || !SKILL_NAME_PATTERN.test(skillName) || !KNOWN_SKILL_NAMES.has(skillName)) {
4321
+ return;
4322
+ }
4323
+ return skillName;
4324
+ }
4325
+ function normalizeSkillName(value) {
4326
+ return normalizeSkillNameWithOptions(value, {
4327
+ allowLegacyNamespace: false
4328
+ });
4329
+ }
4330
+ function buildCommandTelemetryAttribution(commandPath, skillSource) {
4331
+ const skillName = normalizeSkillName(skillSource);
4332
+ return {
4333
+ ...skillName ? { skill_name: skillName } : {},
4334
+ ...getCommandProductModeAttribution(commandPath)
4335
+ };
4336
+ }
4337
+
4338
+ // ../common/src/trackedAction.ts
4339
+ var pollSignalSlot = singleton("PollSignal");
4340
+ var cliErrorCodeValues = new Set(CLI_ERROR_CODES);
4341
+ var retryHintValues = new Set(RETRY_HINTS);
4342
+ var TELEMETRY_COMMAND_ARG_PREFIX = "uip.cmd.arg.";
4343
+ var processContext = {
4344
+ exit: (code) => {
4345
+ process.exitCode = code;
4346
+ },
4347
+ get pollSignal() {
4348
+ return pollSignalSlot.get();
4349
+ }
4350
+ };
4351
+ function extractCommandParams(cmd) {
4352
+ const params = {};
4353
+ const add = (name, value) => {
4354
+ if (name && value !== undefined) {
4355
+ params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = value;
4356
+ }
4357
+ };
4358
+ const registered = cmd.registeredArguments ?? [];
4359
+ const processed = cmd.processedArgs ?? [];
4360
+ for (let i = 0;i < registered.length; i++) {
4361
+ add(registered[i].name(), processed[i]);
4362
+ }
4363
+ for (const [key, value] of Object.entries(cmd.opts())) {
4364
+ add(key, value);
4365
+ }
4366
+ return params;
4367
+ }
4368
+ function deriveCommandPath(cmd) {
4369
+ const parts = [];
4370
+ let current = cmd;
4371
+ while (current) {
4372
+ const name = current.name();
4373
+ if (name) {
4374
+ parts.unshift(name);
4375
+ }
4376
+ current = current.parent;
4377
+ }
4378
+ if (parts.length > 1) {
4379
+ parts.shift();
4380
+ }
4381
+ return ["uip", ...parts.filter((p) => p !== "uip")].join(".");
4382
+ }
4383
+ function isCliErrorCode(value) {
4384
+ return typeof value === "string" && cliErrorCodeValues.has(value);
4385
+ }
4386
+ function isRetryHint(value) {
4387
+ return typeof value === "string" && retryHintValues.has(value);
4388
+ }
4389
+ function isErrorContext(value) {
4390
+ return value !== null && typeof value === "object";
4391
+ }
4392
+ function commandHelpHint(commandPath) {
4393
+ const command = commandPath.replace(/\./g, " ");
4394
+ return `An unexpected error occurred. Run '${command} --help' to verify command syntax, or run with --log-level debug for details.`;
4395
+ }
4396
+ function isPromptCancellation(error) {
4397
+ return error instanceof Error && error.name === "ExitPromptError";
4398
+ }
4399
+ function implicitLimitViolation(cmd) {
4400
+ if (getOutputFilter() === undefined) {
4401
+ return;
4402
+ }
4403
+ const hasLimit = cmd.options.some((o) => o.attributeName() === "limit");
4404
+ if (!hasLimit || cmd.getOptionValueSource("limit") !== "default") {
4405
+ return;
4406
+ }
4407
+ return new FilterImplicitLimitError(String(cmd.opts().limit));
4408
+ }
4409
+ function exitCodeFromProcess(fallback) {
4410
+ return typeof process.exitCode === "number" ? process.exitCode : fallback;
4411
+ }
4412
+ Command.prototype.trackedAction = function(context, fn, properties) {
4413
+ const command = this;
4414
+ return this.action(async (...args) => {
4415
+ await loadOutputCodecsAsync({
4416
+ yaml: getOutputFormat() === "yaml",
4417
+ filter: getOutputFilter() !== undefined
4418
+ });
4419
+ const telemetryName = deriveCommandPath(command);
4420
+ const props = typeof properties === "function" ? properties(...args) : properties;
4421
+ const requestContext = telemetry.createRequestContext();
4422
+ const startTime = performance.now();
4423
+ let errorMessage;
4424
+ let fallbackExitCode = EXIT_CODES.Success;
4425
+ clearRecordedCommandFailureTelemetry();
4426
+ const [error] = await catchError(telemetry.runWithContext(requestContext, () => {
4427
+ const violation = implicitLimitViolation(command);
4428
+ if (violation) {
4429
+ return Promise.reject(violation);
4430
+ }
4431
+ return fn(...args);
4432
+ }));
4433
+ if (error) {
4434
+ errorMessage = error instanceof Error ? error.message : String(error);
4435
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
4436
+ const typed = error;
4437
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
4438
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
4439
+ const finalResult = customResult ?? RESULTS.Failure;
4440
+ const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
4441
+ const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
4442
+ const typedRetry = typed.retry ?? typed.Retry;
4443
+ const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
4444
+ const typedContext = typed.context ?? typed.Context;
4445
+ const customContext = isErrorContext(typedContext) ? typedContext : undefined;
4446
+ const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
4447
+ fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
4448
+ OutputFormatter.error({
4449
+ Result: finalResult,
4450
+ ...customErrorCode ? { ErrorCode: customErrorCode } : {},
4451
+ Message: errorMessage,
4452
+ Instructions: customInstructions ?? commandHelpHint(telemetryName),
4453
+ ...customRetry ? { Retry: customRetry } : {},
4454
+ ...customContext ? { Context: customContext } : {}
4455
+ });
4456
+ context.exit(fallbackExitCode);
4457
+ }
4458
+ const durationMs = performance.now() - startTime;
4459
+ const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
4460
+ const recordedFailure = takeRecordedCommandFailureTelemetry();
4461
+ const success = !error && exitCode === 0;
4462
+ const terminalTelemetry = buildCommandTerminalTelemetryProperties({
4463
+ error,
4464
+ exitCode,
4465
+ recordedFailure,
4466
+ pollSignal: context.pollSignal
4467
+ });
4468
+ const commandParams = extractCommandParams(command);
4469
+ if (props) {
4470
+ for (const key of Object.keys(props)) {
4471
+ delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
4472
+ }
4473
+ }
4474
+ const baseProperties = redactProperties({
4475
+ ...commandParams,
4476
+ ...props,
4477
+ ...buildCommandTelemetryAttribution(telemetryName, process.env.UIPATH_SKILL),
4478
+ command: "true",
4479
+ ...terminalTelemetry,
4480
+ ...errorMessage ? { errorMessage } : {}
4481
+ });
4482
+ telemetry.trackRequestResult(telemetryName, durationMs, success, baseProperties, requestContext);
4483
+ });
4484
+ };
4485
+ // ../common/src/completer.ts
4486
+ var COMPLETER_SYMBOL = Symbol.for("@uipath/common/completer");
4487
+ // ../common/src/console-guard.ts
4488
+ var guardInstalledSlot = singleton("ConsoleGuardInstalled");
4489
+ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
4490
+ // ../common/src/constants.ts
4491
+ var DEFAULT_PAGE_SIZE = 50;
4492
+ var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
4493
+ // ../common/src/content-hash.ts
4494
+ function isBrowserRuntime() {
4495
+ const runtime = globalThis;
4496
+ return typeof runtime.window !== "undefined" && typeof runtime.document !== "undefined";
4497
+ }
4498
+ async function hashContent(content) {
4499
+ const encoder = new TextEncoder;
4500
+ const bytes = encoder.encode(content);
4501
+ if (globalThis.crypto?.subtle) {
4502
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
4503
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
4504
+ }
4505
+ if (!isBrowserRuntime()) {
4506
+ const crypto2 = await import("node:crypto");
4507
+ return crypto2.createHash("sha256").update(content, "utf-8").digest("hex");
4508
+ }
4509
+ throw new Error("Unable to compute SHA-256 hash in this environment.");
4510
+ }
4511
+ // ../common/src/error-instructions.ts
4512
+ function extractHttpStatus(err) {
4513
+ if (!err || typeof err !== "object")
4514
+ return;
4515
+ const e = err;
4516
+ return e.response?.status ?? e.status ?? e.statusCode;
4517
+ }
4518
+ var GENERIC = "Check authentication and parameters";
4519
+ function instructionsFor(ctx, err) {
4520
+ switch (ctx) {
4521
+ case "auth":
4522
+ return "Run 'uip login' to authenticate. To inspect the current session, run 'uip whoami'.";
4523
+ case "identity":
4524
+ return "Select an active tenant with 'uip login tenant set <tenant>' and ensure your login includes an organization";
4525
+ case "input-parse":
4526
+ return "Ensure --inputs is valid JSON or pipe JSON via stdin";
4527
+ case "input-validate":
4528
+ return "Fix the flagged input fields to match the process's input schema";
4529
+ case "flag-format":
4530
+ return "Check the flag value format — see --help for the expected shape";
4531
+ case "permissions":
4532
+ return "Confirm your user has the required permissions in this folder/tenant, or re-authenticate with 'uip login' if your session has lapsed";
4533
+ case "backend": {
4534
+ const status = extractHttpStatus(err);
4535
+ if (status === 401) {
4536
+ return "Re-authenticate with 'uip login' — your session is invalid or expired";
4537
+ }
4538
+ if (status === 403) {
4539
+ return "Confirm your user has access to the folder and the required permissions";
4540
+ }
4541
+ if (status === 404) {
4542
+ return "Verify the resource exists in the current folder/tenant";
4543
+ }
4544
+ if (status === 400) {
4545
+ return "Request was rejected — check flag values and inputs";
4546
+ }
4547
+ if (status !== undefined && status >= 500 && status < 600) {
4548
+ return "Orchestrator returned a server error — retry; if it persists, check service status";
4549
+ }
4550
+ const connectivity = describeConnectivityError(err);
4551
+ if (connectivity) {
4552
+ return connectivity.instructions;
4553
+ }
4554
+ return GENERIC;
4555
+ }
4556
+ }
4557
+ }
4558
+ // ../common/src/host-global-options.ts
4559
+ var HOST_GLOBAL_OPTIONS_WITH_VALUE = [
4560
+ "--output",
4561
+ "--output-filter",
4562
+ "--log-level",
4563
+ "--log-file",
4564
+ "--profile"
4565
+ ];
4566
+ var HOST_GLOBAL_FLAGS = [
4567
+ "--json",
4568
+ "--interactive",
4569
+ "--no-interactive"
4570
+ ];
4571
+ var VALUE_OPTIONS = new Set(HOST_GLOBAL_OPTIONS_WITH_VALUE);
4572
+ var BOOLEAN_FLAGS = new Set(HOST_GLOBAL_FLAGS);
4573
+ // ../common/src/interactivity-context.ts
4574
+ var modeSlot = singleton("InteractivityMode");
4575
+ var interactiveFlagSlot = singleton("InteractiveFlag");
4576
+ // ../common/src/option-aliases.ts
4577
+ function warnDeprecatedOptionAlias(deprecatedFlag, preferredFlag) {
4578
+ getOutputSink().writeErr(`[WARN] ${deprecatedFlag} is deprecated. Use ${preferredFlag} instead.
4579
+ `);
4580
+ }
4581
+ var TENANT_SWITCH_COMMAND = "uip login tenant set <tenant>";
4582
+ function createHiddenDeprecatedTenantOption(flags = "-t, --tenant <tenant-name>") {
4583
+ return new Option(flags, `Tenant name. Deprecated; use ${TENANT_SWITCH_COMMAND} to switch active tenants.`).hideHelp().argParser((tenant) => {
4584
+ warnDeprecatedTenantOption(tenant);
4585
+ return tenant;
4586
+ });
4587
+ }
4588
+ function warnDeprecatedTenantOption(tenant) {
4589
+ if (tenant === undefined)
4590
+ return;
4591
+ warnDeprecatedOptionAlias("--tenant", TENANT_SWITCH_COMMAND);
4592
+ }
4593
+ // ../common/src/option-validators.ts
4594
+ function parseLimit(raw, _previous) {
4595
+ return parseBoundedInt(raw, "--limit", { min: 1, max: 1e4 });
4596
+ }
4597
+ function parseOffset(raw, _previous) {
4598
+ return parseBoundedInt(raw, "--offset", { min: 0, max: 1e6 });
4599
+ }
4600
+ function parseBoundedInt(raw, optionName, bounds) {
4601
+ const normalized = raw.trim();
4602
+ if (normalized === "") {
4603
+ throw new InvalidArgumentError(`${optionName} requires a value (got empty).`);
4604
+ }
4605
+ if (!/^-?\d+$/.test(normalized)) {
4606
+ throw new InvalidArgumentError(`${optionName} must be an integer, got '${normalized}'.`);
4607
+ }
4608
+ const n = parseInt(normalized, 10);
4609
+ if (n < bounds.min || n > bounds.max) {
4610
+ throw new InvalidArgumentError(`${optionName} must be between ${bounds.min} and ${bounds.max}, got ${n}.`);
4611
+ }
4612
+ return n;
4613
+ }
4614
+ // ../common/src/package-metadata-options.ts
4615
+ function registerPackageMetadataOptions(command) {
4616
+ return command.option("--author <author>", "Package author").option("--description <text>", "Package description").option("--repository-url <url>", "Source repository URL (recorded in the package for traceability)").option("--repository-commit <sha>", "Source repository commit hash (recorded in the package for traceability)").option("--repository-branch <branch>", "Source repository branch").option("--repository-type <type>", "Source repository type (defaults to 'git' when --repository-url is set)").option("--release-notes <text>", "Release notes for the package").option("--project-url <url>", "Automation Hub idea URL");
4617
+ }
4618
+ function mapPackageMetadataOptions(opts) {
4619
+ const fields = {};
4620
+ if (opts.author !== undefined)
4621
+ fields.author = opts.author;
4622
+ if (opts.description !== undefined)
4623
+ fields.description = opts.description;
4624
+ if (opts.releaseNotes !== undefined)
4625
+ fields.releaseNotes = opts.releaseNotes;
4626
+ if (opts.projectUrl !== undefined)
4627
+ fields.projectUrl = opts.projectUrl;
4628
+ if (opts.repositoryUrl !== undefined)
4629
+ fields.repositoryUrl = opts.repositoryUrl;
4630
+ if (opts.repositoryCommit !== undefined)
4631
+ fields.repositoryCommit = opts.repositoryCommit;
4632
+ if (opts.repositoryBranch !== undefined)
4633
+ fields.repositoryBranch = opts.repositoryBranch;
4634
+ if (opts.repositoryType !== undefined)
4635
+ fields.repositoryType = opts.repositoryType;
4636
+ if (fields.repositoryUrl !== undefined && fields.repositoryType === undefined) {
4637
+ fields.repositoryType = "git";
4638
+ }
4639
+ return fields;
4640
+ }
4641
+ // ../common/src/polling/types.ts
4642
+ var PollOutcome = {
4643
+ Completed: "completed",
4644
+ Timeout: "timeout",
4645
+ Interrupted: "interrupted",
4646
+ Aborted: "aborted",
4647
+ Failed: "failed"
4648
+ };
4649
+
4650
+ // ../common/src/polling/poll-failure-mapping.ts
4651
+ var REASON_BY_OUTCOME = {
4652
+ [PollOutcome.Timeout]: "poll_timeout",
4653
+ [PollOutcome.Failed]: "poll_failed",
4654
+ [PollOutcome.Interrupted]: "poll_failed",
4655
+ [PollOutcome.Aborted]: "poll_aborted"
4656
+ };
4657
+ // ../common/src/polling/terminal-statuses.ts
4658
+ var TERMINAL_STATUSES = new Set([
4659
+ "completed",
4660
+ "successful",
4661
+ "faulted",
4662
+ "failed",
4663
+ "cancelled",
4664
+ "canceled",
4665
+ "stopped",
4666
+ "finished"
4667
+ ]);
4668
+ var FAILURE_STATUSES = new Set([
4669
+ "faulted",
4670
+ "failed",
4671
+ "cancelled",
4672
+ "canceled",
4673
+ "stopped"
4674
+ ]);
4675
+ // ../common/src/screen-logger.ts
4676
+ var ScreenLogger;
4677
+ ((ScreenLogger) => {
4678
+ function progress(message) {
4679
+ getOutputSink().writeErr(`${message}
4680
+ `);
4681
+ }
4682
+ ScreenLogger.progress = progress;
4683
+ })(ScreenLogger ||= {});
4684
+ // ../common/src/sdk-user-agent.ts
4685
+ var USER_AGENT_HEADER = "User-Agent";
4686
+ var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken");
4687
+ function userAgentPatchKey(userAgent) {
4688
+ return Symbol.for(`@uipath/common/sdk-user-agent/${userAgent}`);
4689
+ }
4690
+ function splitUserAgentTokens(value) {
4691
+ return value?.trim().split(/\s+/).filter(Boolean) ?? [];
4692
+ }
4693
+ function appendUserAgentToken(value, userAgent) {
4694
+ const tokens = splitUserAgentTokens(value);
4695
+ const seen = new Set(tokens);
4696
+ for (const token of splitUserAgentTokens(userAgent)) {
4697
+ if (!seen.has(token)) {
4698
+ tokens.push(token);
4699
+ seen.add(token);
4700
+ }
4701
+ }
4702
+ return tokens.join(" ");
4703
+ }
4704
+ function getEffectiveUserAgent(userAgent) {
4705
+ return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent);
4706
+ }
4707
+ function getHeaderName(headers, headerName) {
4708
+ return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase());
4709
+ }
4710
+ function getSdkUserAgentToken(pkg) {
4711
+ const packageName = pkg.name.replace(/^@uipath\//, "");
4712
+ return getEffectiveUserAgent(`${packageName}/${pkg.version}`);
4713
+ }
4714
+ function addSdkUserAgentHeader(headers, userAgent) {
4715
+ const result = { ...headers ?? {} };
4716
+ const headerName = getHeaderName(result, USER_AGENT_HEADER);
4717
+ result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent));
4718
+ return result;
4719
+ }
4720
+ function asHeaderRecord(headers) {
4721
+ return typeof headers === "object" && headers !== null ? { ...headers } : {};
4722
+ }
4723
+ function withForwardedHeadersInitOverride(initOverrides, forward) {
4724
+ return async (requestContext) => {
4725
+ const initWithHeaders = {
4726
+ ...requestContext.init,
4727
+ headers: forward(asHeaderRecord(requestContext.init.headers))
4728
+ };
4729
+ const override = typeof initOverrides === "function" ? await initOverrides({
4730
+ ...requestContext,
4731
+ init: initWithHeaders
4732
+ }) : initOverrides;
4733
+ return {
4734
+ ...override ?? {},
4735
+ headers: forward(asHeaderRecord(override?.headers ?? initWithHeaders.headers))
4736
+ };
4737
+ };
4738
+ }
4739
+ function installRequestHeaderForwarding(BaseApiClass, patchKey, forward) {
4740
+ const prototype = BaseApiClass.prototype;
4741
+ if (prototype[patchKey]) {
4742
+ return;
4743
+ }
4744
+ if (typeof prototype.request !== "function") {
4745
+ throw new Error("Generated BaseAPI request function not found.");
4746
+ }
4747
+ const originalRequest = prototype.request;
4748
+ prototype.request = function requestWithForwardedHeaders(context, initOverrides) {
4749
+ return originalRequest.call(this, context, withForwardedHeadersInitOverride(initOverrides, forward));
4750
+ };
4751
+ Object.defineProperty(prototype, patchKey, {
4752
+ value: true
4753
+ });
4754
+ }
4755
+ function installSdkUserAgentHeader(BaseApiClass, userAgent) {
4756
+ installRequestHeaderForwarding(BaseApiClass, userAgentPatchKey(userAgent), (headers) => addSdkUserAgentHeader(headers, userAgent));
4757
+ }
4758
+ // ../common/src/tool-module-import.ts
4759
+ async function importToolModule(specifier) {
4760
+ return await import(specifier);
4761
+ }
4762
+
4763
+ // ../common/src/tool-provider.ts
4764
+ var factorySlot = singleton("PackagerFactoryProvider");
4765
+ var moduleSlot = singleton("ToolModuleProvider");
4766
+ async function ensureToolModule(verb, packageName, moduleName) {
4767
+ if (!/^[a-z0-9-]+$/.test(moduleName)) {
4768
+ throw new Error(`Invalid tool module name '${moduleName}'.`);
4769
+ }
4770
+ const provider = moduleSlot.get();
4771
+ if (provider) {
4772
+ return provider(verb, moduleName);
4773
+ }
4774
+ const specifier = `${packageName}/${moduleName}`;
4775
+ const [importError, mod] = await catchError(importToolModule(specifier));
4776
+ if (importError) {
4777
+ logger.debug(`No tool-module provider registered; import of '${specifier}' failed: ${importError.message}`);
4778
+ throw new Error(`This command needs '${packageName}'. Install it.`, {
4779
+ cause: importError
4780
+ });
4781
+ }
4782
+ return mod;
4783
+ }
4784
+
4785
+ // ../common/src/solution-project-artifacts.ts
4786
+ async function ensureProjectArtifacts(args) {
4787
+ const [error, mod] = await catchError(ensureToolModule("solution", "@uipath/solution-tool", "init"));
4788
+ if (error) {
4789
+ logger.warn(`Solution artifact-resource generation skipped for project "${args.projectName}": ${error.message}. ` + "Run 'uip solution projects add' to finish setup.");
4790
+ return { Created: false, Error: error.message };
4791
+ }
4792
+ return mod.addProjectArtifactsToSolutionAsync(args);
4793
+ }
4794
+ // ../common/src/solution-project-types.ts
4795
+ var LIBRARY_NOT_A_PROJECT = "A library cannot be a project inside a solution — it is a reusable .nupkg that other projects consume as a NuGet dependency, not a deployable unit. Build and publish it on its own ('uip rpa pack <project-dir> <output-path>', then 'uip or libraries upload --file <nupkg-path>'), and reference it from a project's dependencies. To make the published library part of this solution, add it as a resource instead: 'uip solution resources add --source remote --kind Library --name <library-name>'.";
4796
+ function unsupportedSolutionProjectType(projectType) {
4797
+ if (typeof projectType !== "string") {
4798
+ return null;
4799
+ }
4800
+ return projectType.toLowerCase() === "library" ? LIBRARY_NOT_A_PROJECT : null;
4801
+ }
4802
+ // ../common/src/stdin.ts
4803
+ async function readStdin() {
4804
+ if (process.stdin.isTTY) {
4805
+ return null;
4806
+ }
4807
+ return new Promise((resolve, reject) => {
4808
+ let data = "";
4809
+ process.stdin.setEncoding("utf8");
4810
+ process.stdin.on("data", (chunk) => {
4811
+ data += chunk;
4812
+ });
4813
+ process.stdin.on("end", () => resolve(data.trim() || null));
4814
+ process.stdin.on("error", reject);
4815
+ });
4816
+ }
4817
+ // ../common/src/telemetry/ship-succeeded.ts
4818
+ var shippedKeysSlot = singleton("ShipSucceededDedupeKeys");
4819
+ export { catchError, extractErrorMessage, InvalidArgumentError, Command, Option, isPreviewBuild, logger, getOutputFormat, getOutputFormatExplicit, RESULTS, OutputFormatter, processContext, DEFAULT_PAGE_SIZE, hashContent, instructionsFor, createHiddenDeprecatedTenantOption, parseLimit, parseOffset, registerPackageMetadataOptions, mapPackageMetadataOptions, getSdkUserAgentToken, addSdkUserAgentHeader, installSdkUserAgentHeader, ensureProjectArtifacts, unsupportedSolutionProjectType, readStdin };
4820
+
4821
+ //# debugId=BCD21F8483FFD10664756E2164756E21