@tiledev/tile-push-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4469 @@
1
+ #!/usr/bin/env node
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ //#region \0rolldown/runtime.js
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
+ key = keys[i];
14
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
22
+ value: mod,
23
+ enumerable: true
24
+ }) : target, mod));
25
+ //#endregion
26
+ const require_apiClient = require("../apiClient-DiRjggqw.cjs");
27
+ let node_fs = require("node:fs");
28
+ node_fs = __toESM(node_fs);
29
+ let node_fs_promises = require("node:fs/promises");
30
+ node_fs_promises = __toESM(node_fs_promises);
31
+ let node_path = require("node:path");
32
+ node_path = __toESM(node_path);
33
+ let node_os = require("node:os");
34
+ node_os = __toESM(node_os);
35
+ let node_child_process = require("node:child_process");
36
+ node_child_process = __toESM(node_child_process);
37
+ let node_process = require("node:process");
38
+ node_process = __toESM(node_process);
39
+ let hot_updater_internal_commands = require("hot-updater/internal/commands");
40
+ let fs = require("fs");
41
+ fs = __toESM(fs);
42
+ let path = require("path");
43
+ path = __toESM(path);
44
+ let node_buffer = require("node:buffer");
45
+ let node_url = require("node:url");
46
+ let node_util = require("node:util");
47
+ let node_readline = require("node:readline");
48
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js
49
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
50
+ /**
51
+ * CommanderError class
52
+ */
53
+ var CommanderError = class extends Error {
54
+ /**
55
+ * Constructs the CommanderError class
56
+ * @param {number} exitCode suggested exit code which could be used with process.exit
57
+ * @param {string} code an id string representing the error
58
+ * @param {string} message human-readable description of the error
59
+ */
60
+ constructor(exitCode, code, message) {
61
+ super(message);
62
+ Error.captureStackTrace(this, this.constructor);
63
+ this.name = this.constructor.name;
64
+ this.code = code;
65
+ this.exitCode = exitCode;
66
+ this.nestedError = void 0;
67
+ }
68
+ };
69
+ /**
70
+ * InvalidArgumentError class
71
+ */
72
+ var InvalidArgumentError = class extends CommanderError {
73
+ /**
74
+ * Constructs the InvalidArgumentError class
75
+ * @param {string} [message] explanation of why argument is invalid
76
+ */
77
+ constructor(message) {
78
+ super(1, "commander.invalidArgument", message);
79
+ Error.captureStackTrace(this, this.constructor);
80
+ this.name = this.constructor.name;
81
+ }
82
+ };
83
+ exports.CommanderError = CommanderError;
84
+ exports.InvalidArgumentError = InvalidArgumentError;
85
+ }));
86
+ //#endregion
87
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js
88
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
89
+ const { InvalidArgumentError } = require_error();
90
+ var Argument = class {
91
+ /**
92
+ * Initialize a new command argument with the given name and description.
93
+ * The default is that the argument is required, and you can explicitly
94
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
95
+ *
96
+ * @param {string} name
97
+ * @param {string} [description]
98
+ */
99
+ constructor(name, description) {
100
+ this.description = description || "";
101
+ this.variadic = false;
102
+ this.parseArg = void 0;
103
+ this.defaultValue = void 0;
104
+ this.defaultValueDescription = void 0;
105
+ this.argChoices = void 0;
106
+ switch (name[0]) {
107
+ case "<":
108
+ this.required = true;
109
+ this._name = name.slice(1, -1);
110
+ break;
111
+ case "[":
112
+ this.required = false;
113
+ this._name = name.slice(1, -1);
114
+ break;
115
+ default:
116
+ this.required = true;
117
+ this._name = name;
118
+ break;
119
+ }
120
+ if (this._name.endsWith("...")) {
121
+ this.variadic = true;
122
+ this._name = this._name.slice(0, -3);
123
+ }
124
+ }
125
+ /**
126
+ * Return argument name.
127
+ *
128
+ * @return {string}
129
+ */
130
+ name() {
131
+ return this._name;
132
+ }
133
+ /**
134
+ * @package
135
+ */
136
+ _collectValue(value, previous) {
137
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
138
+ previous.push(value);
139
+ return previous;
140
+ }
141
+ /**
142
+ * Set the default value, and optionally supply the description to be displayed in the help.
143
+ *
144
+ * @param {*} value
145
+ * @param {string} [description]
146
+ * @return {Argument}
147
+ */
148
+ default(value, description) {
149
+ this.defaultValue = value;
150
+ this.defaultValueDescription = description;
151
+ return this;
152
+ }
153
+ /**
154
+ * Set the custom handler for processing CLI command arguments into argument values.
155
+ *
156
+ * @param {Function} [fn]
157
+ * @return {Argument}
158
+ */
159
+ argParser(fn) {
160
+ this.parseArg = fn;
161
+ return this;
162
+ }
163
+ /**
164
+ * Only allow argument value to be one of choices.
165
+ *
166
+ * @param {string[]} values
167
+ * @return {Argument}
168
+ */
169
+ choices(values) {
170
+ this.argChoices = values.slice();
171
+ this.parseArg = (arg, previous) => {
172
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
173
+ if (this.variadic) return this._collectValue(arg, previous);
174
+ return arg;
175
+ };
176
+ return this;
177
+ }
178
+ /**
179
+ * Make argument required.
180
+ *
181
+ * @returns {Argument}
182
+ */
183
+ argRequired() {
184
+ this.required = true;
185
+ return this;
186
+ }
187
+ /**
188
+ * Make argument optional.
189
+ *
190
+ * @returns {Argument}
191
+ */
192
+ argOptional() {
193
+ this.required = false;
194
+ return this;
195
+ }
196
+ };
197
+ /**
198
+ * Takes an argument and returns its human readable equivalent for help usage.
199
+ *
200
+ * @param {Argument} arg
201
+ * @return {string}
202
+ * @private
203
+ */
204
+ function humanReadableArgName(arg) {
205
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
206
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
207
+ }
208
+ exports.Argument = Argument;
209
+ exports.humanReadableArgName = humanReadableArgName;
210
+ }));
211
+ //#endregion
212
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js
213
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
214
+ const { humanReadableArgName } = require_argument();
215
+ /**
216
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
217
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
218
+ * @typedef { import("./argument.js").Argument } Argument
219
+ * @typedef { import("./command.js").Command } Command
220
+ * @typedef { import("./option.js").Option } Option
221
+ */
222
+ var Help = class {
223
+ constructor() {
224
+ this.helpWidth = void 0;
225
+ this.minWidthToWrap = 40;
226
+ this.sortSubcommands = false;
227
+ this.sortOptions = false;
228
+ this.showGlobalOptions = false;
229
+ }
230
+ /**
231
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
232
+ * and just before calling `formatHelp()`.
233
+ *
234
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
235
+ *
236
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
237
+ */
238
+ prepareContext(contextOptions) {
239
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
240
+ }
241
+ /**
242
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
243
+ *
244
+ * @param {Command} cmd
245
+ * @returns {Command[]}
246
+ */
247
+ visibleCommands(cmd) {
248
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
249
+ const helpCommand = cmd._getHelpCommand();
250
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
251
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
252
+ return a.name().localeCompare(b.name());
253
+ });
254
+ return visibleCommands;
255
+ }
256
+ /**
257
+ * Compare options for sort.
258
+ *
259
+ * @param {Option} a
260
+ * @param {Option} b
261
+ * @returns {number}
262
+ */
263
+ compareOptions(a, b) {
264
+ const getSortKey = (option) => {
265
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
266
+ };
267
+ return getSortKey(a).localeCompare(getSortKey(b));
268
+ }
269
+ /**
270
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
271
+ *
272
+ * @param {Command} cmd
273
+ * @returns {Option[]}
274
+ */
275
+ visibleOptions(cmd) {
276
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
277
+ const helpOption = cmd._getHelpOption();
278
+ if (helpOption && !helpOption.hidden) {
279
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
280
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
281
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
282
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
283
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
284
+ }
285
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
286
+ return visibleOptions;
287
+ }
288
+ /**
289
+ * Get an array of the visible global options. (Not including help.)
290
+ *
291
+ * @param {Command} cmd
292
+ * @returns {Option[]}
293
+ */
294
+ visibleGlobalOptions(cmd) {
295
+ if (!this.showGlobalOptions) return [];
296
+ const globalOptions = [];
297
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
298
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
299
+ globalOptions.push(...visibleOptions);
300
+ }
301
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
302
+ return globalOptions;
303
+ }
304
+ /**
305
+ * Get an array of the arguments if any have a description.
306
+ *
307
+ * @param {Command} cmd
308
+ * @returns {Argument[]}
309
+ */
310
+ visibleArguments(cmd) {
311
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
312
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
313
+ });
314
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
315
+ return [];
316
+ }
317
+ /**
318
+ * Get the command term to show in the list of subcommands.
319
+ *
320
+ * @param {Command} cmd
321
+ * @returns {string}
322
+ */
323
+ subcommandTerm(cmd) {
324
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
325
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
326
+ }
327
+ /**
328
+ * Get the option term to show in the list of options.
329
+ *
330
+ * @param {Option} option
331
+ * @returns {string}
332
+ */
333
+ optionTerm(option) {
334
+ return option.flags;
335
+ }
336
+ /**
337
+ * Get the argument term to show in the list of arguments.
338
+ *
339
+ * @param {Argument} argument
340
+ * @returns {string}
341
+ */
342
+ argumentTerm(argument) {
343
+ return argument.name();
344
+ }
345
+ /**
346
+ * Get the longest command term length.
347
+ *
348
+ * @param {Command} cmd
349
+ * @param {Help} helper
350
+ * @returns {number}
351
+ */
352
+ longestSubcommandTermLength(cmd, helper) {
353
+ return helper.visibleCommands(cmd).reduce((max, command) => {
354
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
355
+ }, 0);
356
+ }
357
+ /**
358
+ * Get the longest option term length.
359
+ *
360
+ * @param {Command} cmd
361
+ * @param {Help} helper
362
+ * @returns {number}
363
+ */
364
+ longestOptionTermLength(cmd, helper) {
365
+ return helper.visibleOptions(cmd).reduce((max, option) => {
366
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
367
+ }, 0);
368
+ }
369
+ /**
370
+ * Get the longest global option term length.
371
+ *
372
+ * @param {Command} cmd
373
+ * @param {Help} helper
374
+ * @returns {number}
375
+ */
376
+ longestGlobalOptionTermLength(cmd, helper) {
377
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
378
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
379
+ }, 0);
380
+ }
381
+ /**
382
+ * Get the longest argument term length.
383
+ *
384
+ * @param {Command} cmd
385
+ * @param {Help} helper
386
+ * @returns {number}
387
+ */
388
+ longestArgumentTermLength(cmd, helper) {
389
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
390
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
391
+ }, 0);
392
+ }
393
+ /**
394
+ * Get the command usage to be displayed at the top of the built-in help.
395
+ *
396
+ * @param {Command} cmd
397
+ * @returns {string}
398
+ */
399
+ commandUsage(cmd) {
400
+ let cmdName = cmd._name;
401
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
402
+ let ancestorCmdNames = "";
403
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
404
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
405
+ }
406
+ /**
407
+ * Get the description for the command.
408
+ *
409
+ * @param {Command} cmd
410
+ * @returns {string}
411
+ */
412
+ commandDescription(cmd) {
413
+ return cmd.description();
414
+ }
415
+ /**
416
+ * Get the subcommand summary to show in the list of subcommands.
417
+ * (Fallback to description for backwards compatibility.)
418
+ *
419
+ * @param {Command} cmd
420
+ * @returns {string}
421
+ */
422
+ subcommandDescription(cmd) {
423
+ return cmd.summary() || cmd.description();
424
+ }
425
+ /**
426
+ * Get the option description to show in the list of options.
427
+ *
428
+ * @param {Option} option
429
+ * @return {string}
430
+ */
431
+ optionDescription(option) {
432
+ const extraInfo = [];
433
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
434
+ if (option.defaultValue !== void 0) {
435
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
436
+ }
437
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
438
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
439
+ if (extraInfo.length > 0) {
440
+ const extraDescription = `(${extraInfo.join(", ")})`;
441
+ if (option.description) return `${option.description} ${extraDescription}`;
442
+ return extraDescription;
443
+ }
444
+ return option.description;
445
+ }
446
+ /**
447
+ * Get the argument description to show in the list of arguments.
448
+ *
449
+ * @param {Argument} argument
450
+ * @return {string}
451
+ */
452
+ argumentDescription(argument) {
453
+ const extraInfo = [];
454
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
455
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
456
+ if (extraInfo.length > 0) {
457
+ const extraDescription = `(${extraInfo.join(", ")})`;
458
+ if (argument.description) return `${argument.description} ${extraDescription}`;
459
+ return extraDescription;
460
+ }
461
+ return argument.description;
462
+ }
463
+ /**
464
+ * Format a list of items, given a heading and an array of formatted items.
465
+ *
466
+ * @param {string} heading
467
+ * @param {string[]} items
468
+ * @param {Help} helper
469
+ * @returns string[]
470
+ */
471
+ formatItemList(heading, items, helper) {
472
+ if (items.length === 0) return [];
473
+ return [
474
+ helper.styleTitle(heading),
475
+ ...items,
476
+ ""
477
+ ];
478
+ }
479
+ /**
480
+ * Group items by their help group heading.
481
+ *
482
+ * @param {Command[] | Option[]} unsortedItems
483
+ * @param {Command[] | Option[]} visibleItems
484
+ * @param {Function} getGroup
485
+ * @returns {Map<string, Command[] | Option[]>}
486
+ */
487
+ groupItems(unsortedItems, visibleItems, getGroup) {
488
+ const result = /* @__PURE__ */ new Map();
489
+ unsortedItems.forEach((item) => {
490
+ const group = getGroup(item);
491
+ if (!result.has(group)) result.set(group, []);
492
+ });
493
+ visibleItems.forEach((item) => {
494
+ const group = getGroup(item);
495
+ if (!result.has(group)) result.set(group, []);
496
+ result.get(group).push(item);
497
+ });
498
+ return result;
499
+ }
500
+ /**
501
+ * Generate the built-in help text.
502
+ *
503
+ * @param {Command} cmd
504
+ * @param {Help} helper
505
+ * @returns {string}
506
+ */
507
+ formatHelp(cmd, helper) {
508
+ const termWidth = helper.padWidth(cmd, helper);
509
+ const helpWidth = helper.helpWidth ?? 80;
510
+ function callFormatItem(term, description) {
511
+ return helper.formatItem(term, termWidth, description, helper);
512
+ }
513
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
514
+ const commandDescription = helper.commandDescription(cmd);
515
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
516
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
517
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
518
+ });
519
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
520
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
521
+ const optionList = options.map((option) => {
522
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
523
+ });
524
+ output = output.concat(this.formatItemList(group, optionList, helper));
525
+ });
526
+ if (helper.showGlobalOptions) {
527
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
528
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
529
+ });
530
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
531
+ }
532
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
533
+ const commandList = commands.map((sub) => {
534
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
535
+ });
536
+ output = output.concat(this.formatItemList(group, commandList, helper));
537
+ });
538
+ return output.join("\n");
539
+ }
540
+ /**
541
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
542
+ *
543
+ * @param {string} str
544
+ * @returns {number}
545
+ */
546
+ displayWidth(str) {
547
+ return stripColor(str).length;
548
+ }
549
+ /**
550
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
551
+ *
552
+ * @param {string} str
553
+ * @returns {string}
554
+ */
555
+ styleTitle(str) {
556
+ return str;
557
+ }
558
+ styleUsage(str) {
559
+ return str.split(" ").map((word) => {
560
+ if (word === "[options]") return this.styleOptionText(word);
561
+ if (word === "[command]") return this.styleSubcommandText(word);
562
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
563
+ return this.styleCommandText(word);
564
+ }).join(" ");
565
+ }
566
+ styleCommandDescription(str) {
567
+ return this.styleDescriptionText(str);
568
+ }
569
+ styleOptionDescription(str) {
570
+ return this.styleDescriptionText(str);
571
+ }
572
+ styleSubcommandDescription(str) {
573
+ return this.styleDescriptionText(str);
574
+ }
575
+ styleArgumentDescription(str) {
576
+ return this.styleDescriptionText(str);
577
+ }
578
+ styleDescriptionText(str) {
579
+ return str;
580
+ }
581
+ styleOptionTerm(str) {
582
+ return this.styleOptionText(str);
583
+ }
584
+ styleSubcommandTerm(str) {
585
+ return str.split(" ").map((word) => {
586
+ if (word === "[options]") return this.styleOptionText(word);
587
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
588
+ return this.styleSubcommandText(word);
589
+ }).join(" ");
590
+ }
591
+ styleArgumentTerm(str) {
592
+ return this.styleArgumentText(str);
593
+ }
594
+ styleOptionText(str) {
595
+ return str;
596
+ }
597
+ styleArgumentText(str) {
598
+ return str;
599
+ }
600
+ styleSubcommandText(str) {
601
+ return str;
602
+ }
603
+ styleCommandText(str) {
604
+ return str;
605
+ }
606
+ /**
607
+ * Calculate the pad width from the maximum term length.
608
+ *
609
+ * @param {Command} cmd
610
+ * @param {Help} helper
611
+ * @returns {number}
612
+ */
613
+ padWidth(cmd, helper) {
614
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
615
+ }
616
+ /**
617
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
618
+ *
619
+ * @param {string} str
620
+ * @returns {boolean}
621
+ */
622
+ preformatted(str) {
623
+ return /\n[^\S\r\n]/.test(str);
624
+ }
625
+ /**
626
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
627
+ *
628
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
629
+ * TTT DDD DDDD
630
+ * DD DDD
631
+ *
632
+ * @param {string} term
633
+ * @param {number} termWidth
634
+ * @param {string} description
635
+ * @param {Help} helper
636
+ * @returns {string}
637
+ */
638
+ formatItem(term, termWidth, description, helper) {
639
+ const itemIndent = 2;
640
+ const itemIndentStr = " ".repeat(itemIndent);
641
+ if (!description) return itemIndentStr + term;
642
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
643
+ const spacerWidth = 2;
644
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
645
+ let formattedDescription;
646
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
647
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
648
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
649
+ }
650
+ /**
651
+ * Wrap a string at whitespace, preserving existing line breaks.
652
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
653
+ *
654
+ * @param {string} str
655
+ * @param {number} width
656
+ * @returns {string}
657
+ */
658
+ boxWrap(str, width) {
659
+ if (width < this.minWidthToWrap) return str;
660
+ const rawLines = str.split(/\r\n|\n/);
661
+ const chunkPattern = /[\s]*[^\s]+/g;
662
+ const wrappedLines = [];
663
+ rawLines.forEach((line) => {
664
+ const chunks = line.match(chunkPattern);
665
+ if (chunks === null) {
666
+ wrappedLines.push("");
667
+ return;
668
+ }
669
+ let sumChunks = [chunks.shift()];
670
+ let sumWidth = this.displayWidth(sumChunks[0]);
671
+ chunks.forEach((chunk) => {
672
+ const visibleWidth = this.displayWidth(chunk);
673
+ if (sumWidth + visibleWidth <= width) {
674
+ sumChunks.push(chunk);
675
+ sumWidth += visibleWidth;
676
+ return;
677
+ }
678
+ wrappedLines.push(sumChunks.join(""));
679
+ const nextChunk = chunk.trimStart();
680
+ sumChunks = [nextChunk];
681
+ sumWidth = this.displayWidth(nextChunk);
682
+ });
683
+ wrappedLines.push(sumChunks.join(""));
684
+ });
685
+ return wrappedLines.join("\n");
686
+ }
687
+ };
688
+ /**
689
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
690
+ *
691
+ * @param {string} str
692
+ * @returns {string}
693
+ * @package
694
+ */
695
+ function stripColor(str) {
696
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
697
+ }
698
+ exports.Help = Help;
699
+ exports.stripColor = stripColor;
700
+ }));
701
+ //#endregion
702
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js
703
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
704
+ const { InvalidArgumentError } = require_error();
705
+ var Option = class {
706
+ /**
707
+ * Initialize a new `Option` with the given `flags` and `description`.
708
+ *
709
+ * @param {string} flags
710
+ * @param {string} [description]
711
+ */
712
+ constructor(flags, description) {
713
+ this.flags = flags;
714
+ this.description = description || "";
715
+ this.required = flags.includes("<");
716
+ this.optional = flags.includes("[");
717
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
718
+ this.mandatory = false;
719
+ const optionFlags = splitOptionFlags(flags);
720
+ this.short = optionFlags.shortFlag;
721
+ this.long = optionFlags.longFlag;
722
+ this.negate = false;
723
+ if (this.long) this.negate = this.long.startsWith("--no-");
724
+ this.defaultValue = void 0;
725
+ this.defaultValueDescription = void 0;
726
+ this.presetArg = void 0;
727
+ this.envVar = void 0;
728
+ this.parseArg = void 0;
729
+ this.hidden = false;
730
+ this.argChoices = void 0;
731
+ this.conflictsWith = [];
732
+ this.implied = void 0;
733
+ this.helpGroupHeading = void 0;
734
+ }
735
+ /**
736
+ * Set the default value, and optionally supply the description to be displayed in the help.
737
+ *
738
+ * @param {*} value
739
+ * @param {string} [description]
740
+ * @return {Option}
741
+ */
742
+ default(value, description) {
743
+ this.defaultValue = value;
744
+ this.defaultValueDescription = description;
745
+ return this;
746
+ }
747
+ /**
748
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
749
+ * The custom processing (parseArg) is called.
750
+ *
751
+ * @example
752
+ * new Option('--color').default('GREYSCALE').preset('RGB');
753
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
754
+ *
755
+ * @param {*} arg
756
+ * @return {Option}
757
+ */
758
+ preset(arg) {
759
+ this.presetArg = arg;
760
+ return this;
761
+ }
762
+ /**
763
+ * Add option name(s) that conflict with this option.
764
+ * An error will be displayed if conflicting options are found during parsing.
765
+ *
766
+ * @example
767
+ * new Option('--rgb').conflicts('cmyk');
768
+ * new Option('--js').conflicts(['ts', 'jsx']);
769
+ *
770
+ * @param {(string | string[])} names
771
+ * @return {Option}
772
+ */
773
+ conflicts(names) {
774
+ this.conflictsWith = this.conflictsWith.concat(names);
775
+ return this;
776
+ }
777
+ /**
778
+ * Specify implied option values for when this option is set and the implied options are not.
779
+ *
780
+ * The custom processing (parseArg) is not called on the implied values.
781
+ *
782
+ * @example
783
+ * program
784
+ * .addOption(new Option('--log', 'write logging information to file'))
785
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
786
+ *
787
+ * @param {object} impliedOptionValues
788
+ * @return {Option}
789
+ */
790
+ implies(impliedOptionValues) {
791
+ let newImplied = impliedOptionValues;
792
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
793
+ this.implied = Object.assign(this.implied || {}, newImplied);
794
+ return this;
795
+ }
796
+ /**
797
+ * Set environment variable to check for option value.
798
+ *
799
+ * An environment variable is only used if when processed the current option value is
800
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
801
+ *
802
+ * @param {string} name
803
+ * @return {Option}
804
+ */
805
+ env(name) {
806
+ this.envVar = name;
807
+ return this;
808
+ }
809
+ /**
810
+ * Set the custom handler for processing CLI option arguments into option values.
811
+ *
812
+ * @param {Function} [fn]
813
+ * @return {Option}
814
+ */
815
+ argParser(fn) {
816
+ this.parseArg = fn;
817
+ return this;
818
+ }
819
+ /**
820
+ * Whether the option is mandatory and must have a value after parsing.
821
+ *
822
+ * @param {boolean} [mandatory=true]
823
+ * @return {Option}
824
+ */
825
+ makeOptionMandatory(mandatory = true) {
826
+ this.mandatory = !!mandatory;
827
+ return this;
828
+ }
829
+ /**
830
+ * Hide option in help.
831
+ *
832
+ * @param {boolean} [hide=true]
833
+ * @return {Option}
834
+ */
835
+ hideHelp(hide = true) {
836
+ this.hidden = !!hide;
837
+ return this;
838
+ }
839
+ /**
840
+ * @package
841
+ */
842
+ _collectValue(value, previous) {
843
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
844
+ previous.push(value);
845
+ return previous;
846
+ }
847
+ /**
848
+ * Only allow option value to be one of choices.
849
+ *
850
+ * @param {string[]} values
851
+ * @return {Option}
852
+ */
853
+ choices(values) {
854
+ this.argChoices = values.slice();
855
+ this.parseArg = (arg, previous) => {
856
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
857
+ if (this.variadic) return this._collectValue(arg, previous);
858
+ return arg;
859
+ };
860
+ return this;
861
+ }
862
+ /**
863
+ * Return option name.
864
+ *
865
+ * @return {string}
866
+ */
867
+ name() {
868
+ if (this.long) return this.long.replace(/^--/, "");
869
+ return this.short.replace(/^-/, "");
870
+ }
871
+ /**
872
+ * Return option name, in a camelcase format that can be used
873
+ * as an object attribute key.
874
+ *
875
+ * @return {string}
876
+ */
877
+ attributeName() {
878
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
879
+ return camelcase(this.name());
880
+ }
881
+ /**
882
+ * Set the help group heading.
883
+ *
884
+ * @param {string} heading
885
+ * @return {Option}
886
+ */
887
+ helpGroup(heading) {
888
+ this.helpGroupHeading = heading;
889
+ return this;
890
+ }
891
+ /**
892
+ * Check if `arg` matches the short or long flag.
893
+ *
894
+ * @param {string} arg
895
+ * @return {boolean}
896
+ * @package
897
+ */
898
+ is(arg) {
899
+ return this.short === arg || this.long === arg;
900
+ }
901
+ /**
902
+ * Return whether a boolean option.
903
+ *
904
+ * Options are one of boolean, negated, required argument, or optional argument.
905
+ *
906
+ * @return {boolean}
907
+ * @package
908
+ */
909
+ isBoolean() {
910
+ return !this.required && !this.optional && !this.negate;
911
+ }
912
+ };
913
+ /**
914
+ * This class is to make it easier to work with dual options, without changing the existing
915
+ * implementation. We support separate dual options for separate positive and negative options,
916
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
917
+ * use cases, but is tricky for others where we want separate behaviours despite
918
+ * the single shared option value.
919
+ */
920
+ var DualOptions = class {
921
+ /**
922
+ * @param {Option[]} options
923
+ */
924
+ constructor(options) {
925
+ this.positiveOptions = /* @__PURE__ */ new Map();
926
+ this.negativeOptions = /* @__PURE__ */ new Map();
927
+ this.dualOptions = /* @__PURE__ */ new Set();
928
+ options.forEach((option) => {
929
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
930
+ else this.positiveOptions.set(option.attributeName(), option);
931
+ });
932
+ this.negativeOptions.forEach((value, key) => {
933
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
934
+ });
935
+ }
936
+ /**
937
+ * Did the value come from the option, and not from possible matching dual option?
938
+ *
939
+ * @param {*} value
940
+ * @param {Option} option
941
+ * @returns {boolean}
942
+ */
943
+ valueFromOption(value, option) {
944
+ const optionKey = option.attributeName();
945
+ if (!this.dualOptions.has(optionKey)) return true;
946
+ const preset = this.negativeOptions.get(optionKey).presetArg;
947
+ const negativeValue = preset !== void 0 ? preset : false;
948
+ return option.negate === (negativeValue === value);
949
+ }
950
+ };
951
+ /**
952
+ * Convert string from kebab-case to camelCase.
953
+ *
954
+ * @param {string} str
955
+ * @return {string}
956
+ * @private
957
+ */
958
+ function camelcase(str) {
959
+ return str.split("-").reduce((str, word) => {
960
+ return str + word[0].toUpperCase() + word.slice(1);
961
+ });
962
+ }
963
+ /**
964
+ * Split the short and long flag out of something like '-m,--mixed <value>'
965
+ *
966
+ * @private
967
+ */
968
+ function splitOptionFlags(flags) {
969
+ let shortFlag;
970
+ let longFlag;
971
+ const shortFlagExp = /^-[^-]$/;
972
+ const longFlagExp = /^--[^-]/;
973
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
974
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
975
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
976
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
977
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
978
+ shortFlag = longFlag;
979
+ longFlag = flagParts.shift();
980
+ }
981
+ if (flagParts[0].startsWith("-")) {
982
+ const unsupportedFlag = flagParts[0];
983
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
984
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
985
+ - a short flag is a single dash and a single character
986
+ - either use a single dash and a single character (for a short flag)
987
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
988
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
989
+ - too many short flags`);
990
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
991
+ - too many long flags`);
992
+ throw new Error(`${baseError}
993
+ - unrecognised flag format`);
994
+ }
995
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
996
+ return {
997
+ shortFlag,
998
+ longFlag
999
+ };
1000
+ }
1001
+ exports.Option = Option;
1002
+ exports.DualOptions = DualOptions;
1003
+ }));
1004
+ //#endregion
1005
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
1006
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
1007
+ const maxDistance = 3;
1008
+ function editDistance(a, b) {
1009
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1010
+ const d = [];
1011
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
1012
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
1013
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
1014
+ let cost = 1;
1015
+ if (a[i - 1] === b[j - 1]) cost = 0;
1016
+ else cost = 1;
1017
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1018
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1019
+ }
1020
+ return d[a.length][b.length];
1021
+ }
1022
+ /**
1023
+ * Find close matches, restricted to same number of edits.
1024
+ *
1025
+ * @param {string} word
1026
+ * @param {string[]} candidates
1027
+ * @returns {string}
1028
+ */
1029
+ function suggestSimilar(word, candidates) {
1030
+ if (!candidates || candidates.length === 0) return "";
1031
+ candidates = Array.from(new Set(candidates));
1032
+ const searchingOptions = word.startsWith("--");
1033
+ if (searchingOptions) {
1034
+ word = word.slice(2);
1035
+ candidates = candidates.map((candidate) => candidate.slice(2));
1036
+ }
1037
+ let similar = [];
1038
+ let bestDistance = maxDistance;
1039
+ const minSimilarity = .4;
1040
+ candidates.forEach((candidate) => {
1041
+ if (candidate.length <= 1) return;
1042
+ const distance = editDistance(word, candidate);
1043
+ const length = Math.max(word.length, candidate.length);
1044
+ if ((length - distance) / length > minSimilarity) {
1045
+ if (distance < bestDistance) {
1046
+ bestDistance = distance;
1047
+ similar = [candidate];
1048
+ } else if (distance === bestDistance) similar.push(candidate);
1049
+ }
1050
+ });
1051
+ similar.sort((a, b) => a.localeCompare(b));
1052
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1053
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1054
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1055
+ return "";
1056
+ }
1057
+ exports.suggestSimilar = suggestSimilar;
1058
+ }));
1059
+ //#endregion
1060
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js
1061
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1062
+ const EventEmitter = require("node:events").EventEmitter;
1063
+ const childProcess$1 = require("node:child_process");
1064
+ const path$3 = require("node:path");
1065
+ const fs$6 = require("node:fs");
1066
+ const process$6 = require("node:process");
1067
+ const { Argument, humanReadableArgName } = require_argument();
1068
+ const { CommanderError } = require_error();
1069
+ const { Help, stripColor } = require_help();
1070
+ const { Option, DualOptions } = require_option();
1071
+ const { suggestSimilar } = require_suggestSimilar();
1072
+ var Command = class Command extends EventEmitter {
1073
+ /**
1074
+ * Initialize a new `Command`.
1075
+ *
1076
+ * @param {string} [name]
1077
+ */
1078
+ constructor(name) {
1079
+ super();
1080
+ /** @type {Command[]} */
1081
+ this.commands = [];
1082
+ /** @type {Option[]} */
1083
+ this.options = [];
1084
+ this.parent = null;
1085
+ this._allowUnknownOption = false;
1086
+ this._allowExcessArguments = false;
1087
+ /** @type {Argument[]} */
1088
+ this.registeredArguments = [];
1089
+ this._args = this.registeredArguments;
1090
+ /** @type {string[]} */
1091
+ this.args = [];
1092
+ this.rawArgs = [];
1093
+ this.processedArgs = [];
1094
+ this._scriptPath = null;
1095
+ this._name = name || "";
1096
+ this._optionValues = {};
1097
+ this._optionValueSources = {};
1098
+ this._storeOptionsAsProperties = false;
1099
+ this._actionHandler = null;
1100
+ this._executableHandler = false;
1101
+ this._executableFile = null;
1102
+ this._executableDir = null;
1103
+ this._defaultCommandName = null;
1104
+ this._exitCallback = null;
1105
+ this._aliases = [];
1106
+ this._combineFlagAndOptionalValue = true;
1107
+ this._description = "";
1108
+ this._summary = "";
1109
+ this._argsDescription = void 0;
1110
+ this._enablePositionalOptions = false;
1111
+ this._passThroughOptions = false;
1112
+ this._lifeCycleHooks = {};
1113
+ /** @type {(boolean | string)} */
1114
+ this._showHelpAfterError = false;
1115
+ this._showSuggestionAfterError = true;
1116
+ this._savedState = null;
1117
+ this._outputConfiguration = {
1118
+ writeOut: (str) => process$6.stdout.write(str),
1119
+ writeErr: (str) => process$6.stderr.write(str),
1120
+ outputError: (str, write) => write(str),
1121
+ getOutHelpWidth: () => process$6.stdout.isTTY ? process$6.stdout.columns : void 0,
1122
+ getErrHelpWidth: () => process$6.stderr.isTTY ? process$6.stderr.columns : void 0,
1123
+ getOutHasColors: () => useColor() ?? (process$6.stdout.isTTY && process$6.stdout.hasColors?.()),
1124
+ getErrHasColors: () => useColor() ?? (process$6.stderr.isTTY && process$6.stderr.hasColors?.()),
1125
+ stripColor: (str) => stripColor(str)
1126
+ };
1127
+ this._hidden = false;
1128
+ /** @type {(Option | null | undefined)} */
1129
+ this._helpOption = void 0;
1130
+ this._addImplicitHelpCommand = void 0;
1131
+ /** @type {Command} */
1132
+ this._helpCommand = void 0;
1133
+ this._helpConfiguration = {};
1134
+ /** @type {string | undefined} */
1135
+ this._helpGroupHeading = void 0;
1136
+ /** @type {string | undefined} */
1137
+ this._defaultCommandGroup = void 0;
1138
+ /** @type {string | undefined} */
1139
+ this._defaultOptionGroup = void 0;
1140
+ }
1141
+ /**
1142
+ * Copy settings that are useful to have in common across root command and subcommands.
1143
+ *
1144
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1145
+ *
1146
+ * @param {Command} sourceCommand
1147
+ * @return {Command} `this` command for chaining
1148
+ */
1149
+ copyInheritedSettings(sourceCommand) {
1150
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1151
+ this._helpOption = sourceCommand._helpOption;
1152
+ this._helpCommand = sourceCommand._helpCommand;
1153
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1154
+ this._exitCallback = sourceCommand._exitCallback;
1155
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1156
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1157
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1158
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1159
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1160
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1161
+ return this;
1162
+ }
1163
+ /**
1164
+ * @returns {Command[]}
1165
+ * @private
1166
+ */
1167
+ _getCommandAndAncestors() {
1168
+ const result = [];
1169
+ for (let command = this; command; command = command.parent) result.push(command);
1170
+ return result;
1171
+ }
1172
+ /**
1173
+ * Define a command.
1174
+ *
1175
+ * There are two styles of command: pay attention to where to put the description.
1176
+ *
1177
+ * @example
1178
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1179
+ * program
1180
+ * .command('clone <source> [destination]')
1181
+ * .description('clone a repository into a newly created directory')
1182
+ * .action((source, destination) => {
1183
+ * console.log('clone command called');
1184
+ * });
1185
+ *
1186
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1187
+ * program
1188
+ * .command('start <service>', 'start named service')
1189
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1190
+ *
1191
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1192
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1193
+ * @param {object} [execOpts] - configuration options (for executable)
1194
+ * @return {Command} returns new command for action handler, or `this` for executable command
1195
+ */
1196
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1197
+ let desc = actionOptsOrExecDesc;
1198
+ let opts = execOpts;
1199
+ if (typeof desc === "object" && desc !== null) {
1200
+ opts = desc;
1201
+ desc = null;
1202
+ }
1203
+ opts = opts || {};
1204
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1205
+ const cmd = this.createCommand(name);
1206
+ if (desc) {
1207
+ cmd.description(desc);
1208
+ cmd._executableHandler = true;
1209
+ }
1210
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1211
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1212
+ cmd._executableFile = opts.executableFile || null;
1213
+ if (args) cmd.arguments(args);
1214
+ this._registerCommand(cmd);
1215
+ cmd.parent = this;
1216
+ cmd.copyInheritedSettings(this);
1217
+ if (desc) return this;
1218
+ return cmd;
1219
+ }
1220
+ /**
1221
+ * Factory routine to create a new unattached command.
1222
+ *
1223
+ * See .command() for creating an attached subcommand, which uses this routine to
1224
+ * create the command. You can override createCommand to customise subcommands.
1225
+ *
1226
+ * @param {string} [name]
1227
+ * @return {Command} new command
1228
+ */
1229
+ createCommand(name) {
1230
+ return new Command(name);
1231
+ }
1232
+ /**
1233
+ * You can customise the help with a subclass of Help by overriding createHelp,
1234
+ * or by overriding Help properties using configureHelp().
1235
+ *
1236
+ * @return {Help}
1237
+ */
1238
+ createHelp() {
1239
+ return Object.assign(new Help(), this.configureHelp());
1240
+ }
1241
+ /**
1242
+ * You can customise the help by overriding Help properties using configureHelp(),
1243
+ * or with a subclass of Help by overriding createHelp().
1244
+ *
1245
+ * @param {object} [configuration] - configuration options
1246
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1247
+ */
1248
+ configureHelp(configuration) {
1249
+ if (configuration === void 0) return this._helpConfiguration;
1250
+ this._helpConfiguration = configuration;
1251
+ return this;
1252
+ }
1253
+ /**
1254
+ * The default output goes to stdout and stderr. You can customise this for special
1255
+ * applications. You can also customise the display of errors by overriding outputError.
1256
+ *
1257
+ * The configuration properties are all functions:
1258
+ *
1259
+ * // change how output being written, defaults to stdout and stderr
1260
+ * writeOut(str)
1261
+ * writeErr(str)
1262
+ * // change how output being written for errors, defaults to writeErr
1263
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1264
+ * // specify width for wrapping help
1265
+ * getOutHelpWidth()
1266
+ * getErrHelpWidth()
1267
+ * // color support, currently only used with Help
1268
+ * getOutHasColors()
1269
+ * getErrHasColors()
1270
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1271
+ *
1272
+ * @param {object} [configuration] - configuration options
1273
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1274
+ */
1275
+ configureOutput(configuration) {
1276
+ if (configuration === void 0) return this._outputConfiguration;
1277
+ this._outputConfiguration = {
1278
+ ...this._outputConfiguration,
1279
+ ...configuration
1280
+ };
1281
+ return this;
1282
+ }
1283
+ /**
1284
+ * Display the help or a custom message after an error occurs.
1285
+ *
1286
+ * @param {(boolean|string)} [displayHelp]
1287
+ * @return {Command} `this` command for chaining
1288
+ */
1289
+ showHelpAfterError(displayHelp = true) {
1290
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1291
+ this._showHelpAfterError = displayHelp;
1292
+ return this;
1293
+ }
1294
+ /**
1295
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1296
+ *
1297
+ * @param {boolean} [displaySuggestion]
1298
+ * @return {Command} `this` command for chaining
1299
+ */
1300
+ showSuggestionAfterError(displaySuggestion = true) {
1301
+ this._showSuggestionAfterError = !!displaySuggestion;
1302
+ return this;
1303
+ }
1304
+ /**
1305
+ * Add a prepared subcommand.
1306
+ *
1307
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1308
+ *
1309
+ * @param {Command} cmd - new subcommand
1310
+ * @param {object} [opts] - configuration options
1311
+ * @return {Command} `this` command for chaining
1312
+ */
1313
+ addCommand(cmd, opts) {
1314
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1315
+ - specify the name in Command constructor or using .name()`);
1316
+ opts = opts || {};
1317
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1318
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1319
+ this._registerCommand(cmd);
1320
+ cmd.parent = this;
1321
+ cmd._checkForBrokenPassThrough();
1322
+ return this;
1323
+ }
1324
+ /**
1325
+ * Factory routine to create a new unattached argument.
1326
+ *
1327
+ * See .argument() for creating an attached argument, which uses this routine to
1328
+ * create the argument. You can override createArgument to return a custom argument.
1329
+ *
1330
+ * @param {string} name
1331
+ * @param {string} [description]
1332
+ * @return {Argument} new argument
1333
+ */
1334
+ createArgument(name, description) {
1335
+ return new Argument(name, description);
1336
+ }
1337
+ /**
1338
+ * Define argument syntax for command.
1339
+ *
1340
+ * The default is that the argument is required, and you can explicitly
1341
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1342
+ *
1343
+ * @example
1344
+ * program.argument('<input-file>');
1345
+ * program.argument('[output-file]');
1346
+ *
1347
+ * @param {string} name
1348
+ * @param {string} [description]
1349
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1350
+ * @param {*} [defaultValue]
1351
+ * @return {Command} `this` command for chaining
1352
+ */
1353
+ argument(name, description, parseArg, defaultValue) {
1354
+ const argument = this.createArgument(name, description);
1355
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1356
+ else argument.default(parseArg);
1357
+ this.addArgument(argument);
1358
+ return this;
1359
+ }
1360
+ /**
1361
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1362
+ *
1363
+ * See also .argument().
1364
+ *
1365
+ * @example
1366
+ * program.arguments('<cmd> [env]');
1367
+ *
1368
+ * @param {string} names
1369
+ * @return {Command} `this` command for chaining
1370
+ */
1371
+ arguments(names) {
1372
+ names.trim().split(/ +/).forEach((detail) => {
1373
+ this.argument(detail);
1374
+ });
1375
+ return this;
1376
+ }
1377
+ /**
1378
+ * Define argument syntax for command, adding a prepared argument.
1379
+ *
1380
+ * @param {Argument} argument
1381
+ * @return {Command} `this` command for chaining
1382
+ */
1383
+ addArgument(argument) {
1384
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1385
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1386
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1387
+ this.registeredArguments.push(argument);
1388
+ return this;
1389
+ }
1390
+ /**
1391
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1392
+ *
1393
+ * @example
1394
+ * program.helpCommand('help [cmd]');
1395
+ * program.helpCommand('help [cmd]', 'show help');
1396
+ * program.helpCommand(false); // suppress default help command
1397
+ * program.helpCommand(true); // add help command even if no subcommands
1398
+ *
1399
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1400
+ * @param {string} [description] - custom description
1401
+ * @return {Command} `this` command for chaining
1402
+ */
1403
+ helpCommand(enableOrNameAndArgs, description) {
1404
+ if (typeof enableOrNameAndArgs === "boolean") {
1405
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1406
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1407
+ return this;
1408
+ }
1409
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1410
+ const helpDescription = description ?? "display help for command";
1411
+ const helpCommand = this.createCommand(helpName);
1412
+ helpCommand.helpOption(false);
1413
+ if (helpArgs) helpCommand.arguments(helpArgs);
1414
+ if (helpDescription) helpCommand.description(helpDescription);
1415
+ this._addImplicitHelpCommand = true;
1416
+ this._helpCommand = helpCommand;
1417
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1418
+ return this;
1419
+ }
1420
+ /**
1421
+ * Add prepared custom help command.
1422
+ *
1423
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1424
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1425
+ * @return {Command} `this` command for chaining
1426
+ */
1427
+ addHelpCommand(helpCommand, deprecatedDescription) {
1428
+ if (typeof helpCommand !== "object") {
1429
+ this.helpCommand(helpCommand, deprecatedDescription);
1430
+ return this;
1431
+ }
1432
+ this._addImplicitHelpCommand = true;
1433
+ this._helpCommand = helpCommand;
1434
+ this._initCommandGroup(helpCommand);
1435
+ return this;
1436
+ }
1437
+ /**
1438
+ * Lazy create help command.
1439
+ *
1440
+ * @return {(Command|null)}
1441
+ * @package
1442
+ */
1443
+ _getHelpCommand() {
1444
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1445
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1446
+ return this._helpCommand;
1447
+ }
1448
+ return null;
1449
+ }
1450
+ /**
1451
+ * Add hook for life cycle event.
1452
+ *
1453
+ * @param {string} event
1454
+ * @param {Function} listener
1455
+ * @return {Command} `this` command for chaining
1456
+ */
1457
+ hook(event, listener) {
1458
+ const allowedValues = [
1459
+ "preSubcommand",
1460
+ "preAction",
1461
+ "postAction"
1462
+ ];
1463
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1464
+ Expecting one of '${allowedValues.join("', '")}'`);
1465
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1466
+ else this._lifeCycleHooks[event] = [listener];
1467
+ return this;
1468
+ }
1469
+ /**
1470
+ * Register callback to use as replacement for calling process.exit.
1471
+ *
1472
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1473
+ * @return {Command} `this` command for chaining
1474
+ */
1475
+ exitOverride(fn) {
1476
+ if (fn) this._exitCallback = fn;
1477
+ else this._exitCallback = (err) => {
1478
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1479
+ };
1480
+ return this;
1481
+ }
1482
+ /**
1483
+ * Call process.exit, and _exitCallback if defined.
1484
+ *
1485
+ * @param {number} exitCode exit code for using with process.exit
1486
+ * @param {string} code an id string representing the error
1487
+ * @param {string} message human-readable description of the error
1488
+ * @return never
1489
+ * @private
1490
+ */
1491
+ _exit(exitCode, code, message) {
1492
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1493
+ process$6.exit(exitCode);
1494
+ }
1495
+ /**
1496
+ * Register callback `fn` for the command.
1497
+ *
1498
+ * @example
1499
+ * program
1500
+ * .command('serve')
1501
+ * .description('start service')
1502
+ * .action(function() {
1503
+ * // do work here
1504
+ * });
1505
+ *
1506
+ * @param {Function} fn
1507
+ * @return {Command} `this` command for chaining
1508
+ */
1509
+ action(fn) {
1510
+ const listener = (args) => {
1511
+ const expectedArgsCount = this.registeredArguments.length;
1512
+ const actionArgs = args.slice(0, expectedArgsCount);
1513
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1514
+ else actionArgs[expectedArgsCount] = this.opts();
1515
+ actionArgs.push(this);
1516
+ return fn.apply(this, actionArgs);
1517
+ };
1518
+ this._actionHandler = listener;
1519
+ return this;
1520
+ }
1521
+ /**
1522
+ * Factory routine to create a new unattached option.
1523
+ *
1524
+ * See .option() for creating an attached option, which uses this routine to
1525
+ * create the option. You can override createOption to return a custom option.
1526
+ *
1527
+ * @param {string} flags
1528
+ * @param {string} [description]
1529
+ * @return {Option} new option
1530
+ */
1531
+ createOption(flags, description) {
1532
+ return new Option(flags, description);
1533
+ }
1534
+ /**
1535
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1536
+ *
1537
+ * @param {(Option | Argument)} target
1538
+ * @param {string} value
1539
+ * @param {*} previous
1540
+ * @param {string} invalidArgumentMessage
1541
+ * @private
1542
+ */
1543
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1544
+ try {
1545
+ return target.parseArg(value, previous);
1546
+ } catch (err) {
1547
+ if (err.code === "commander.invalidArgument") {
1548
+ const message = `${invalidArgumentMessage} ${err.message}`;
1549
+ this.error(message, {
1550
+ exitCode: err.exitCode,
1551
+ code: err.code
1552
+ });
1553
+ }
1554
+ throw err;
1555
+ }
1556
+ }
1557
+ /**
1558
+ * Check for option flag conflicts.
1559
+ * Register option if no conflicts found, or throw on conflict.
1560
+ *
1561
+ * @param {Option} option
1562
+ * @private
1563
+ */
1564
+ _registerOption(option) {
1565
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1566
+ if (matchingOption) {
1567
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1568
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1569
+ - already used by option '${matchingOption.flags}'`);
1570
+ }
1571
+ this._initOptionGroup(option);
1572
+ this.options.push(option);
1573
+ }
1574
+ /**
1575
+ * Check for command name and alias conflicts with existing commands.
1576
+ * Register command if no conflicts found, or throw on conflict.
1577
+ *
1578
+ * @param {Command} command
1579
+ * @private
1580
+ */
1581
+ _registerCommand(command) {
1582
+ const knownBy = (cmd) => {
1583
+ return [cmd.name()].concat(cmd.aliases());
1584
+ };
1585
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1586
+ if (alreadyUsed) {
1587
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1588
+ const newCmd = knownBy(command).join("|");
1589
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1590
+ }
1591
+ this._initCommandGroup(command);
1592
+ this.commands.push(command);
1593
+ }
1594
+ /**
1595
+ * Add an option.
1596
+ *
1597
+ * @param {Option} option
1598
+ * @return {Command} `this` command for chaining
1599
+ */
1600
+ addOption(option) {
1601
+ this._registerOption(option);
1602
+ const oname = option.name();
1603
+ const name = option.attributeName();
1604
+ if (option.negate) {
1605
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1606
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1607
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1608
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1609
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1610
+ const oldValue = this.getOptionValue(name);
1611
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1612
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1613
+ if (val == null) if (option.negate) val = false;
1614
+ else if (option.isBoolean() || option.optional) val = true;
1615
+ else val = "";
1616
+ this.setOptionValueWithSource(name, val, valueSource);
1617
+ };
1618
+ this.on("option:" + oname, (val) => {
1619
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1620
+ });
1621
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1622
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1623
+ });
1624
+ return this;
1625
+ }
1626
+ /**
1627
+ * Internal implementation shared by .option() and .requiredOption()
1628
+ *
1629
+ * @return {Command} `this` command for chaining
1630
+ * @private
1631
+ */
1632
+ _optionEx(config, flags, description, fn, defaultValue) {
1633
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1634
+ const option = this.createOption(flags, description);
1635
+ option.makeOptionMandatory(!!config.mandatory);
1636
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1637
+ else if (fn instanceof RegExp) {
1638
+ const regex = fn;
1639
+ fn = (val, def) => {
1640
+ const m = regex.exec(val);
1641
+ return m ? m[0] : def;
1642
+ };
1643
+ option.default(defaultValue).argParser(fn);
1644
+ } else option.default(fn);
1645
+ return this.addOption(option);
1646
+ }
1647
+ /**
1648
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1649
+ *
1650
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1651
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1652
+ *
1653
+ * See the README for more details, and see also addOption() and requiredOption().
1654
+ *
1655
+ * @example
1656
+ * program
1657
+ * .option('-p, --pepper', 'add pepper')
1658
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1659
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1660
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1661
+ *
1662
+ * @param {string} flags
1663
+ * @param {string} [description]
1664
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1665
+ * @param {*} [defaultValue]
1666
+ * @return {Command} `this` command for chaining
1667
+ */
1668
+ option(flags, description, parseArg, defaultValue) {
1669
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1670
+ }
1671
+ /**
1672
+ * Add a required option which must have a value after parsing. This usually means
1673
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1674
+ *
1675
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1676
+ *
1677
+ * @param {string} flags
1678
+ * @param {string} [description]
1679
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1680
+ * @param {*} [defaultValue]
1681
+ * @return {Command} `this` command for chaining
1682
+ */
1683
+ requiredOption(flags, description, parseArg, defaultValue) {
1684
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1685
+ }
1686
+ /**
1687
+ * Alter parsing of short flags with optional values.
1688
+ *
1689
+ * @example
1690
+ * // for `.option('-f,--flag [value]'):
1691
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1692
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1693
+ *
1694
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1695
+ * @return {Command} `this` command for chaining
1696
+ */
1697
+ combineFlagAndOptionalValue(combine = true) {
1698
+ this._combineFlagAndOptionalValue = !!combine;
1699
+ return this;
1700
+ }
1701
+ /**
1702
+ * Allow unknown options on the command line.
1703
+ *
1704
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1705
+ * @return {Command} `this` command for chaining
1706
+ */
1707
+ allowUnknownOption(allowUnknown = true) {
1708
+ this._allowUnknownOption = !!allowUnknown;
1709
+ return this;
1710
+ }
1711
+ /**
1712
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1713
+ *
1714
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1715
+ * @return {Command} `this` command for chaining
1716
+ */
1717
+ allowExcessArguments(allowExcess = true) {
1718
+ this._allowExcessArguments = !!allowExcess;
1719
+ return this;
1720
+ }
1721
+ /**
1722
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1723
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1724
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1725
+ *
1726
+ * @param {boolean} [positional]
1727
+ * @return {Command} `this` command for chaining
1728
+ */
1729
+ enablePositionalOptions(positional = true) {
1730
+ this._enablePositionalOptions = !!positional;
1731
+ return this;
1732
+ }
1733
+ /**
1734
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1735
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1736
+ * positional options to have been enabled on the program (parent commands).
1737
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1738
+ *
1739
+ * @param {boolean} [passThrough] for unknown options.
1740
+ * @return {Command} `this` command for chaining
1741
+ */
1742
+ passThroughOptions(passThrough = true) {
1743
+ this._passThroughOptions = !!passThrough;
1744
+ this._checkForBrokenPassThrough();
1745
+ return this;
1746
+ }
1747
+ /**
1748
+ * @private
1749
+ */
1750
+ _checkForBrokenPassThrough() {
1751
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1752
+ }
1753
+ /**
1754
+ * Whether to store option values as properties on command object,
1755
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1756
+ *
1757
+ * @param {boolean} [storeAsProperties=true]
1758
+ * @return {Command} `this` command for chaining
1759
+ */
1760
+ storeOptionsAsProperties(storeAsProperties = true) {
1761
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1762
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1763
+ this._storeOptionsAsProperties = !!storeAsProperties;
1764
+ return this;
1765
+ }
1766
+ /**
1767
+ * Retrieve option value.
1768
+ *
1769
+ * @param {string} key
1770
+ * @return {object} value
1771
+ */
1772
+ getOptionValue(key) {
1773
+ if (this._storeOptionsAsProperties) return this[key];
1774
+ return this._optionValues[key];
1775
+ }
1776
+ /**
1777
+ * Store option value.
1778
+ *
1779
+ * @param {string} key
1780
+ * @param {object} value
1781
+ * @return {Command} `this` command for chaining
1782
+ */
1783
+ setOptionValue(key, value) {
1784
+ return this.setOptionValueWithSource(key, value, void 0);
1785
+ }
1786
+ /**
1787
+ * Store option value and where the value came from.
1788
+ *
1789
+ * @param {string} key
1790
+ * @param {object} value
1791
+ * @param {string} source - expected values are default/config/env/cli/implied
1792
+ * @return {Command} `this` command for chaining
1793
+ */
1794
+ setOptionValueWithSource(key, value, source) {
1795
+ if (this._storeOptionsAsProperties) this[key] = value;
1796
+ else this._optionValues[key] = value;
1797
+ this._optionValueSources[key] = source;
1798
+ return this;
1799
+ }
1800
+ /**
1801
+ * Get source of option value.
1802
+ * Expected values are default | config | env | cli | implied
1803
+ *
1804
+ * @param {string} key
1805
+ * @return {string}
1806
+ */
1807
+ getOptionValueSource(key) {
1808
+ return this._optionValueSources[key];
1809
+ }
1810
+ /**
1811
+ * Get source of option value. See also .optsWithGlobals().
1812
+ * Expected values are default | config | env | cli | implied
1813
+ *
1814
+ * @param {string} key
1815
+ * @return {string}
1816
+ */
1817
+ getOptionValueSourceWithGlobals(key) {
1818
+ let source;
1819
+ this._getCommandAndAncestors().forEach((cmd) => {
1820
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1821
+ });
1822
+ return source;
1823
+ }
1824
+ /**
1825
+ * Get user arguments from implied or explicit arguments.
1826
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1827
+ *
1828
+ * @private
1829
+ */
1830
+ _prepareUserArgs(argv, parseOptions) {
1831
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1832
+ parseOptions = parseOptions || {};
1833
+ if (argv === void 0 && parseOptions.from === void 0) {
1834
+ if (process$6.versions?.electron) parseOptions.from = "electron";
1835
+ const execArgv = process$6.execArgv ?? [];
1836
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1837
+ }
1838
+ if (argv === void 0) argv = process$6.argv;
1839
+ this.rawArgs = argv.slice();
1840
+ let userArgs;
1841
+ switch (parseOptions.from) {
1842
+ case void 0:
1843
+ case "node":
1844
+ this._scriptPath = argv[1];
1845
+ userArgs = argv.slice(2);
1846
+ break;
1847
+ case "electron":
1848
+ if (process$6.defaultApp) {
1849
+ this._scriptPath = argv[1];
1850
+ userArgs = argv.slice(2);
1851
+ } else userArgs = argv.slice(1);
1852
+ break;
1853
+ case "user":
1854
+ userArgs = argv.slice(0);
1855
+ break;
1856
+ case "eval":
1857
+ userArgs = argv.slice(1);
1858
+ break;
1859
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1860
+ }
1861
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1862
+ this._name = this._name || "program";
1863
+ return userArgs;
1864
+ }
1865
+ /**
1866
+ * Parse `argv`, setting options and invoking commands when defined.
1867
+ *
1868
+ * Use parseAsync instead of parse if any of your action handlers are async.
1869
+ *
1870
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1871
+ *
1872
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1873
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1874
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1875
+ * - `'user'`: just user arguments
1876
+ *
1877
+ * @example
1878
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1879
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1880
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1881
+ *
1882
+ * @param {string[]} [argv] - optional, defaults to process.argv
1883
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1884
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1885
+ * @return {Command} `this` command for chaining
1886
+ */
1887
+ parse(argv, parseOptions) {
1888
+ this._prepareForParse();
1889
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1890
+ this._parseCommand([], userArgs);
1891
+ return this;
1892
+ }
1893
+ /**
1894
+ * Parse `argv`, setting options and invoking commands when defined.
1895
+ *
1896
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1897
+ *
1898
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1899
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1900
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1901
+ * - `'user'`: just user arguments
1902
+ *
1903
+ * @example
1904
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1905
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1906
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1907
+ *
1908
+ * @param {string[]} [argv]
1909
+ * @param {object} [parseOptions]
1910
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1911
+ * @return {Promise}
1912
+ */
1913
+ async parseAsync(argv, parseOptions) {
1914
+ this._prepareForParse();
1915
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1916
+ await this._parseCommand([], userArgs);
1917
+ return this;
1918
+ }
1919
+ _prepareForParse() {
1920
+ if (this._savedState === null) this.saveStateBeforeParse();
1921
+ else this.restoreStateBeforeParse();
1922
+ }
1923
+ /**
1924
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1925
+ * Not usually called directly, but available for subclasses to save their custom state.
1926
+ *
1927
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1928
+ */
1929
+ saveStateBeforeParse() {
1930
+ this._savedState = {
1931
+ _name: this._name,
1932
+ _optionValues: { ...this._optionValues },
1933
+ _optionValueSources: { ...this._optionValueSources }
1934
+ };
1935
+ }
1936
+ /**
1937
+ * Restore state before parse for calls after the first.
1938
+ * Not usually called directly, but available for subclasses to save their custom state.
1939
+ *
1940
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1941
+ */
1942
+ restoreStateBeforeParse() {
1943
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1944
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1945
+ this._name = this._savedState._name;
1946
+ this._scriptPath = null;
1947
+ this.rawArgs = [];
1948
+ this._optionValues = { ...this._savedState._optionValues };
1949
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1950
+ this.args = [];
1951
+ this.processedArgs = [];
1952
+ }
1953
+ /**
1954
+ * Throw if expected executable is missing. Add lots of help for author.
1955
+ *
1956
+ * @param {string} executableFile
1957
+ * @param {string} executableDir
1958
+ * @param {string} subcommandName
1959
+ */
1960
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1961
+ if (fs$6.existsSync(executableFile)) return;
1962
+ const executableMissing = `'${executableFile}' does not exist
1963
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1964
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1965
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1966
+ throw new Error(executableMissing);
1967
+ }
1968
+ /**
1969
+ * Execute a sub-command executable.
1970
+ *
1971
+ * @private
1972
+ */
1973
+ _executeSubCommand(subcommand, args) {
1974
+ args = args.slice();
1975
+ let launchWithNode = false;
1976
+ const sourceExt = [
1977
+ ".js",
1978
+ ".ts",
1979
+ ".tsx",
1980
+ ".mjs",
1981
+ ".cjs"
1982
+ ];
1983
+ function findFile(baseDir, baseName) {
1984
+ const localBin = path$3.resolve(baseDir, baseName);
1985
+ if (fs$6.existsSync(localBin)) return localBin;
1986
+ if (sourceExt.includes(path$3.extname(baseName))) return void 0;
1987
+ const foundExt = sourceExt.find((ext) => fs$6.existsSync(`${localBin}${ext}`));
1988
+ if (foundExt) return `${localBin}${foundExt}`;
1989
+ }
1990
+ this._checkForMissingMandatoryOptions();
1991
+ this._checkForConflictingOptions();
1992
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1993
+ let executableDir = this._executableDir || "";
1994
+ if (this._scriptPath) {
1995
+ let resolvedScriptPath;
1996
+ try {
1997
+ resolvedScriptPath = fs$6.realpathSync(this._scriptPath);
1998
+ } catch {
1999
+ resolvedScriptPath = this._scriptPath;
2000
+ }
2001
+ executableDir = path$3.resolve(path$3.dirname(resolvedScriptPath), executableDir);
2002
+ }
2003
+ if (executableDir) {
2004
+ let localFile = findFile(executableDir, executableFile);
2005
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2006
+ const legacyName = path$3.basename(this._scriptPath, path$3.extname(this._scriptPath));
2007
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2008
+ }
2009
+ executableFile = localFile || executableFile;
2010
+ }
2011
+ launchWithNode = sourceExt.includes(path$3.extname(executableFile));
2012
+ let proc;
2013
+ if (process$6.platform !== "win32") if (launchWithNode) {
2014
+ args.unshift(executableFile);
2015
+ args = incrementNodeInspectorPort(process$6.execArgv).concat(args);
2016
+ proc = childProcess$1.spawn(process$6.argv[0], args, { stdio: "inherit" });
2017
+ } else proc = childProcess$1.spawn(executableFile, args, { stdio: "inherit" });
2018
+ else {
2019
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2020
+ args.unshift(executableFile);
2021
+ args = incrementNodeInspectorPort(process$6.execArgv).concat(args);
2022
+ proc = childProcess$1.spawn(process$6.execPath, args, { stdio: "inherit" });
2023
+ }
2024
+ if (!proc.killed) [
2025
+ "SIGUSR1",
2026
+ "SIGUSR2",
2027
+ "SIGTERM",
2028
+ "SIGINT",
2029
+ "SIGHUP"
2030
+ ].forEach((signal) => {
2031
+ process$6.on(signal, () => {
2032
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2033
+ });
2034
+ });
2035
+ const exitCallback = this._exitCallback;
2036
+ proc.on("close", (code) => {
2037
+ code = code ?? 1;
2038
+ if (!exitCallback) process$6.exit(code);
2039
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2040
+ });
2041
+ proc.on("error", (err) => {
2042
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2043
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2044
+ if (!exitCallback) process$6.exit(1);
2045
+ else {
2046
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2047
+ wrappedError.nestedError = err;
2048
+ exitCallback(wrappedError);
2049
+ }
2050
+ });
2051
+ this.runningCommand = proc;
2052
+ }
2053
+ /**
2054
+ * @private
2055
+ */
2056
+ _dispatchSubcommand(commandName, operands, unknown) {
2057
+ const subCommand = this._findCommand(commandName);
2058
+ if (!subCommand) this.help({ error: true });
2059
+ subCommand._prepareForParse();
2060
+ let promiseChain;
2061
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2062
+ promiseChain = this._chainOrCall(promiseChain, () => {
2063
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2064
+ else return subCommand._parseCommand(operands, unknown);
2065
+ });
2066
+ return promiseChain;
2067
+ }
2068
+ /**
2069
+ * Invoke help directly if possible, or dispatch if necessary.
2070
+ * e.g. help foo
2071
+ *
2072
+ * @private
2073
+ */
2074
+ _dispatchHelpCommand(subcommandName) {
2075
+ if (!subcommandName) this.help();
2076
+ const subCommand = this._findCommand(subcommandName);
2077
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2078
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2079
+ }
2080
+ /**
2081
+ * Check this.args against expected this.registeredArguments.
2082
+ *
2083
+ * @private
2084
+ */
2085
+ _checkNumberOfArguments() {
2086
+ this.registeredArguments.forEach((arg, i) => {
2087
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2088
+ });
2089
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2090
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2091
+ }
2092
+ /**
2093
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2094
+ *
2095
+ * @private
2096
+ */
2097
+ _processArguments() {
2098
+ const myParseArg = (argument, value, previous) => {
2099
+ let parsedValue = value;
2100
+ if (value !== null && argument.parseArg) {
2101
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2102
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2103
+ }
2104
+ return parsedValue;
2105
+ };
2106
+ this._checkNumberOfArguments();
2107
+ const processedArgs = [];
2108
+ this.registeredArguments.forEach((declaredArg, index) => {
2109
+ let value = declaredArg.defaultValue;
2110
+ if (declaredArg.variadic) {
2111
+ if (index < this.args.length) {
2112
+ value = this.args.slice(index);
2113
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2114
+ return myParseArg(declaredArg, v, processed);
2115
+ }, declaredArg.defaultValue);
2116
+ } else if (value === void 0) value = [];
2117
+ } else if (index < this.args.length) {
2118
+ value = this.args[index];
2119
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2120
+ }
2121
+ processedArgs[index] = value;
2122
+ });
2123
+ this.processedArgs = processedArgs;
2124
+ }
2125
+ /**
2126
+ * Once we have a promise we chain, but call synchronously until then.
2127
+ *
2128
+ * @param {(Promise|undefined)} promise
2129
+ * @param {Function} fn
2130
+ * @return {(Promise|undefined)}
2131
+ * @private
2132
+ */
2133
+ _chainOrCall(promise, fn) {
2134
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2135
+ return fn();
2136
+ }
2137
+ /**
2138
+ *
2139
+ * @param {(Promise|undefined)} promise
2140
+ * @param {string} event
2141
+ * @return {(Promise|undefined)}
2142
+ * @private
2143
+ */
2144
+ _chainOrCallHooks(promise, event) {
2145
+ let result = promise;
2146
+ const hooks = [];
2147
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2148
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2149
+ hooks.push({
2150
+ hookedCommand,
2151
+ callback
2152
+ });
2153
+ });
2154
+ });
2155
+ if (event === "postAction") hooks.reverse();
2156
+ hooks.forEach((hookDetail) => {
2157
+ result = this._chainOrCall(result, () => {
2158
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2159
+ });
2160
+ });
2161
+ return result;
2162
+ }
2163
+ /**
2164
+ *
2165
+ * @param {(Promise|undefined)} promise
2166
+ * @param {Command} subCommand
2167
+ * @param {string} event
2168
+ * @return {(Promise|undefined)}
2169
+ * @private
2170
+ */
2171
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2172
+ let result = promise;
2173
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2174
+ result = this._chainOrCall(result, () => {
2175
+ return hook(this, subCommand);
2176
+ });
2177
+ });
2178
+ return result;
2179
+ }
2180
+ /**
2181
+ * Process arguments in context of this command.
2182
+ * Returns action result, in case it is a promise.
2183
+ *
2184
+ * @private
2185
+ */
2186
+ _parseCommand(operands, unknown) {
2187
+ const parsed = this.parseOptions(unknown);
2188
+ this._parseOptionsEnv();
2189
+ this._parseOptionsImplied();
2190
+ operands = operands.concat(parsed.operands);
2191
+ unknown = parsed.unknown;
2192
+ this.args = operands.concat(unknown);
2193
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2194
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2195
+ if (this._defaultCommandName) {
2196
+ this._outputHelpIfRequested(unknown);
2197
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2198
+ }
2199
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2200
+ this._outputHelpIfRequested(parsed.unknown);
2201
+ this._checkForMissingMandatoryOptions();
2202
+ this._checkForConflictingOptions();
2203
+ const checkForUnknownOptions = () => {
2204
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2205
+ };
2206
+ const commandEvent = `command:${this.name()}`;
2207
+ if (this._actionHandler) {
2208
+ checkForUnknownOptions();
2209
+ this._processArguments();
2210
+ let promiseChain;
2211
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2212
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2213
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2214
+ this.parent.emit(commandEvent, operands, unknown);
2215
+ });
2216
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2217
+ return promiseChain;
2218
+ }
2219
+ if (this.parent?.listenerCount(commandEvent)) {
2220
+ checkForUnknownOptions();
2221
+ this._processArguments();
2222
+ this.parent.emit(commandEvent, operands, unknown);
2223
+ } else if (operands.length) {
2224
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2225
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2226
+ else if (this.commands.length) this.unknownCommand();
2227
+ else {
2228
+ checkForUnknownOptions();
2229
+ this._processArguments();
2230
+ }
2231
+ } else if (this.commands.length) {
2232
+ checkForUnknownOptions();
2233
+ this.help({ error: true });
2234
+ } else {
2235
+ checkForUnknownOptions();
2236
+ this._processArguments();
2237
+ }
2238
+ }
2239
+ /**
2240
+ * Find matching command.
2241
+ *
2242
+ * @private
2243
+ * @return {Command | undefined}
2244
+ */
2245
+ _findCommand(name) {
2246
+ if (!name) return void 0;
2247
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2248
+ }
2249
+ /**
2250
+ * Return an option matching `arg` if any.
2251
+ *
2252
+ * @param {string} arg
2253
+ * @return {Option}
2254
+ * @package
2255
+ */
2256
+ _findOption(arg) {
2257
+ return this.options.find((option) => option.is(arg));
2258
+ }
2259
+ /**
2260
+ * Display an error message if a mandatory option does not have a value.
2261
+ * Called after checking for help flags in leaf subcommand.
2262
+ *
2263
+ * @private
2264
+ */
2265
+ _checkForMissingMandatoryOptions() {
2266
+ this._getCommandAndAncestors().forEach((cmd) => {
2267
+ cmd.options.forEach((anOption) => {
2268
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2269
+ });
2270
+ });
2271
+ }
2272
+ /**
2273
+ * Display an error message if conflicting options are used together in this.
2274
+ *
2275
+ * @private
2276
+ */
2277
+ _checkForConflictingLocalOptions() {
2278
+ const definedNonDefaultOptions = this.options.filter((option) => {
2279
+ const optionKey = option.attributeName();
2280
+ if (this.getOptionValue(optionKey) === void 0) return false;
2281
+ return this.getOptionValueSource(optionKey) !== "default";
2282
+ });
2283
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2284
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2285
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2286
+ });
2287
+ }
2288
+ /**
2289
+ * Display an error message if conflicting options are used together.
2290
+ * Called after checking for help flags in leaf subcommand.
2291
+ *
2292
+ * @private
2293
+ */
2294
+ _checkForConflictingOptions() {
2295
+ this._getCommandAndAncestors().forEach((cmd) => {
2296
+ cmd._checkForConflictingLocalOptions();
2297
+ });
2298
+ }
2299
+ /**
2300
+ * Parse options from `argv` removing known options,
2301
+ * and return argv split into operands and unknown arguments.
2302
+ *
2303
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2304
+ *
2305
+ * Examples:
2306
+ *
2307
+ * argv => operands, unknown
2308
+ * --known kkk op => [op], []
2309
+ * op --known kkk => [op], []
2310
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2311
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2312
+ *
2313
+ * @param {string[]} args
2314
+ * @return {{operands: string[], unknown: string[]}}
2315
+ */
2316
+ parseOptions(args) {
2317
+ const operands = [];
2318
+ const unknown = [];
2319
+ let dest = operands;
2320
+ function maybeOption(arg) {
2321
+ return arg.length > 1 && arg[0] === "-";
2322
+ }
2323
+ const negativeNumberArg = (arg) => {
2324
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2325
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2326
+ };
2327
+ let activeVariadicOption = null;
2328
+ let activeGroup = null;
2329
+ let i = 0;
2330
+ while (i < args.length || activeGroup) {
2331
+ const arg = activeGroup ?? args[i++];
2332
+ activeGroup = null;
2333
+ if (arg === "--") {
2334
+ if (dest === unknown) dest.push(arg);
2335
+ dest.push(...args.slice(i));
2336
+ break;
2337
+ }
2338
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2339
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2340
+ continue;
2341
+ }
2342
+ activeVariadicOption = null;
2343
+ if (maybeOption(arg)) {
2344
+ const option = this._findOption(arg);
2345
+ if (option) {
2346
+ if (option.required) {
2347
+ const value = args[i++];
2348
+ if (value === void 0) this.optionMissingArgument(option);
2349
+ this.emit(`option:${option.name()}`, value);
2350
+ } else if (option.optional) {
2351
+ let value = null;
2352
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2353
+ this.emit(`option:${option.name()}`, value);
2354
+ } else this.emit(`option:${option.name()}`);
2355
+ activeVariadicOption = option.variadic ? option : null;
2356
+ continue;
2357
+ }
2358
+ }
2359
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2360
+ const option = this._findOption(`-${arg[1]}`);
2361
+ if (option) {
2362
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2363
+ else {
2364
+ this.emit(`option:${option.name()}`);
2365
+ activeGroup = `-${arg.slice(2)}`;
2366
+ }
2367
+ continue;
2368
+ }
2369
+ }
2370
+ if (/^--[^=]+=/.test(arg)) {
2371
+ const index = arg.indexOf("=");
2372
+ const option = this._findOption(arg.slice(0, index));
2373
+ if (option && (option.required || option.optional)) {
2374
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2375
+ continue;
2376
+ }
2377
+ }
2378
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2379
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2380
+ if (this._findCommand(arg)) {
2381
+ operands.push(arg);
2382
+ unknown.push(...args.slice(i));
2383
+ break;
2384
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2385
+ operands.push(arg, ...args.slice(i));
2386
+ break;
2387
+ } else if (this._defaultCommandName) {
2388
+ unknown.push(arg, ...args.slice(i));
2389
+ break;
2390
+ }
2391
+ }
2392
+ if (this._passThroughOptions) {
2393
+ dest.push(arg, ...args.slice(i));
2394
+ break;
2395
+ }
2396
+ dest.push(arg);
2397
+ }
2398
+ return {
2399
+ operands,
2400
+ unknown
2401
+ };
2402
+ }
2403
+ /**
2404
+ * Return an object containing local option values as key-value pairs.
2405
+ *
2406
+ * @return {object}
2407
+ */
2408
+ opts() {
2409
+ if (this._storeOptionsAsProperties) {
2410
+ const result = {};
2411
+ const len = this.options.length;
2412
+ for (let i = 0; i < len; i++) {
2413
+ const key = this.options[i].attributeName();
2414
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2415
+ }
2416
+ return result;
2417
+ }
2418
+ return this._optionValues;
2419
+ }
2420
+ /**
2421
+ * Return an object containing merged local and global option values as key-value pairs.
2422
+ *
2423
+ * @return {object}
2424
+ */
2425
+ optsWithGlobals() {
2426
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2427
+ }
2428
+ /**
2429
+ * Display error message and exit (or call exitOverride).
2430
+ *
2431
+ * @param {string} message
2432
+ * @param {object} [errorOptions]
2433
+ * @param {string} [errorOptions.code] - an id string representing the error
2434
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2435
+ */
2436
+ error(message, errorOptions) {
2437
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2438
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2439
+ else if (this._showHelpAfterError) {
2440
+ this._outputConfiguration.writeErr("\n");
2441
+ this.outputHelp({ error: true });
2442
+ }
2443
+ const config = errorOptions || {};
2444
+ const exitCode = config.exitCode || 1;
2445
+ const code = config.code || "commander.error";
2446
+ this._exit(exitCode, code, message);
2447
+ }
2448
+ /**
2449
+ * Apply any option related environment variables, if option does
2450
+ * not have a value from cli or client code.
2451
+ *
2452
+ * @private
2453
+ */
2454
+ _parseOptionsEnv() {
2455
+ this.options.forEach((option) => {
2456
+ if (option.envVar && option.envVar in process$6.env) {
2457
+ const optionKey = option.attributeName();
2458
+ if (this.getOptionValue(optionKey) === void 0 || [
2459
+ "default",
2460
+ "config",
2461
+ "env"
2462
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$6.env[option.envVar]);
2463
+ else this.emit(`optionEnv:${option.name()}`);
2464
+ }
2465
+ });
2466
+ }
2467
+ /**
2468
+ * Apply any implied option values, if option is undefined or default value.
2469
+ *
2470
+ * @private
2471
+ */
2472
+ _parseOptionsImplied() {
2473
+ const dualHelper = new DualOptions(this.options);
2474
+ const hasCustomOptionValue = (optionKey) => {
2475
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2476
+ };
2477
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2478
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2479
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2480
+ });
2481
+ });
2482
+ }
2483
+ /**
2484
+ * Argument `name` is missing.
2485
+ *
2486
+ * @param {string} name
2487
+ * @private
2488
+ */
2489
+ missingArgument(name) {
2490
+ const message = `error: missing required argument '${name}'`;
2491
+ this.error(message, { code: "commander.missingArgument" });
2492
+ }
2493
+ /**
2494
+ * `Option` is missing an argument.
2495
+ *
2496
+ * @param {Option} option
2497
+ * @private
2498
+ */
2499
+ optionMissingArgument(option) {
2500
+ const message = `error: option '${option.flags}' argument missing`;
2501
+ this.error(message, { code: "commander.optionMissingArgument" });
2502
+ }
2503
+ /**
2504
+ * `Option` does not have a value, and is a mandatory option.
2505
+ *
2506
+ * @param {Option} option
2507
+ * @private
2508
+ */
2509
+ missingMandatoryOptionValue(option) {
2510
+ const message = `error: required option '${option.flags}' not specified`;
2511
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2512
+ }
2513
+ /**
2514
+ * `Option` conflicts with another option.
2515
+ *
2516
+ * @param {Option} option
2517
+ * @param {Option} conflictingOption
2518
+ * @private
2519
+ */
2520
+ _conflictingOption(option, conflictingOption) {
2521
+ const findBestOptionFromValue = (option) => {
2522
+ const optionKey = option.attributeName();
2523
+ const optionValue = this.getOptionValue(optionKey);
2524
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2525
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2526
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2527
+ return positiveOption || option;
2528
+ };
2529
+ const getErrorMessage = (option) => {
2530
+ const bestOption = findBestOptionFromValue(option);
2531
+ const optionKey = bestOption.attributeName();
2532
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2533
+ return `option '${bestOption.flags}'`;
2534
+ };
2535
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2536
+ this.error(message, { code: "commander.conflictingOption" });
2537
+ }
2538
+ /**
2539
+ * Unknown option `flag`.
2540
+ *
2541
+ * @param {string} flag
2542
+ * @private
2543
+ */
2544
+ unknownOption(flag) {
2545
+ if (this._allowUnknownOption) return;
2546
+ let suggestion = "";
2547
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2548
+ let candidateFlags = [];
2549
+ let command = this;
2550
+ do {
2551
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2552
+ candidateFlags = candidateFlags.concat(moreFlags);
2553
+ command = command.parent;
2554
+ } while (command && !command._enablePositionalOptions);
2555
+ suggestion = suggestSimilar(flag, candidateFlags);
2556
+ }
2557
+ const message = `error: unknown option '${flag}'${suggestion}`;
2558
+ this.error(message, { code: "commander.unknownOption" });
2559
+ }
2560
+ /**
2561
+ * Excess arguments, more than expected.
2562
+ *
2563
+ * @param {string[]} receivedArgs
2564
+ * @private
2565
+ */
2566
+ _excessArguments(receivedArgs) {
2567
+ if (this._allowExcessArguments) return;
2568
+ const expected = this.registeredArguments.length;
2569
+ const s = expected === 1 ? "" : "s";
2570
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2571
+ this.error(message, { code: "commander.excessArguments" });
2572
+ }
2573
+ /**
2574
+ * Unknown command.
2575
+ *
2576
+ * @private
2577
+ */
2578
+ unknownCommand() {
2579
+ const unknownName = this.args[0];
2580
+ let suggestion = "";
2581
+ if (this._showSuggestionAfterError) {
2582
+ const candidateNames = [];
2583
+ this.createHelp().visibleCommands(this).forEach((command) => {
2584
+ candidateNames.push(command.name());
2585
+ if (command.alias()) candidateNames.push(command.alias());
2586
+ });
2587
+ suggestion = suggestSimilar(unknownName, candidateNames);
2588
+ }
2589
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2590
+ this.error(message, { code: "commander.unknownCommand" });
2591
+ }
2592
+ /**
2593
+ * Get or set the program version.
2594
+ *
2595
+ * This method auto-registers the "-V, --version" option which will print the version number.
2596
+ *
2597
+ * You can optionally supply the flags and description to override the defaults.
2598
+ *
2599
+ * @param {string} [str]
2600
+ * @param {string} [flags]
2601
+ * @param {string} [description]
2602
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2603
+ */
2604
+ version(str, flags, description) {
2605
+ if (str === void 0) return this._version;
2606
+ this._version = str;
2607
+ flags = flags || "-V, --version";
2608
+ description = description || "output the version number";
2609
+ const versionOption = this.createOption(flags, description);
2610
+ this._versionOptionName = versionOption.attributeName();
2611
+ this._registerOption(versionOption);
2612
+ this.on("option:" + versionOption.name(), () => {
2613
+ this._outputConfiguration.writeOut(`${str}\n`);
2614
+ this._exit(0, "commander.version", str);
2615
+ });
2616
+ return this;
2617
+ }
2618
+ /**
2619
+ * Set the description.
2620
+ *
2621
+ * @param {string} [str]
2622
+ * @param {object} [argsDescription]
2623
+ * @return {(string|Command)}
2624
+ */
2625
+ description(str, argsDescription) {
2626
+ if (str === void 0 && argsDescription === void 0) return this._description;
2627
+ this._description = str;
2628
+ if (argsDescription) this._argsDescription = argsDescription;
2629
+ return this;
2630
+ }
2631
+ /**
2632
+ * Set the summary. Used when listed as subcommand of parent.
2633
+ *
2634
+ * @param {string} [str]
2635
+ * @return {(string|Command)}
2636
+ */
2637
+ summary(str) {
2638
+ if (str === void 0) return this._summary;
2639
+ this._summary = str;
2640
+ return this;
2641
+ }
2642
+ /**
2643
+ * Set an alias for the command.
2644
+ *
2645
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2646
+ *
2647
+ * @param {string} [alias]
2648
+ * @return {(string|Command)}
2649
+ */
2650
+ alias(alias) {
2651
+ if (alias === void 0) return this._aliases[0];
2652
+ /** @type {Command} */
2653
+ let command = this;
2654
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2655
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2656
+ const matchingCommand = this.parent?._findCommand(alias);
2657
+ if (matchingCommand) {
2658
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2659
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2660
+ }
2661
+ command._aliases.push(alias);
2662
+ return this;
2663
+ }
2664
+ /**
2665
+ * Set aliases for the command.
2666
+ *
2667
+ * Only the first alias is shown in the auto-generated help.
2668
+ *
2669
+ * @param {string[]} [aliases]
2670
+ * @return {(string[]|Command)}
2671
+ */
2672
+ aliases(aliases) {
2673
+ if (aliases === void 0) return this._aliases;
2674
+ aliases.forEach((alias) => this.alias(alias));
2675
+ return this;
2676
+ }
2677
+ /**
2678
+ * Set / get the command usage `str`.
2679
+ *
2680
+ * @param {string} [str]
2681
+ * @return {(string|Command)}
2682
+ */
2683
+ usage(str) {
2684
+ if (str === void 0) {
2685
+ if (this._usage) return this._usage;
2686
+ const args = this.registeredArguments.map((arg) => {
2687
+ return humanReadableArgName(arg);
2688
+ });
2689
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2690
+ }
2691
+ this._usage = str;
2692
+ return this;
2693
+ }
2694
+ /**
2695
+ * Get or set the name of the command.
2696
+ *
2697
+ * @param {string} [str]
2698
+ * @return {(string|Command)}
2699
+ */
2700
+ name(str) {
2701
+ if (str === void 0) return this._name;
2702
+ this._name = str;
2703
+ return this;
2704
+ }
2705
+ /**
2706
+ * Set/get the help group heading for this subcommand in parent command's help.
2707
+ *
2708
+ * @param {string} [heading]
2709
+ * @return {Command | string}
2710
+ */
2711
+ helpGroup(heading) {
2712
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2713
+ this._helpGroupHeading = heading;
2714
+ return this;
2715
+ }
2716
+ /**
2717
+ * Set/get the default help group heading for subcommands added to this command.
2718
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2719
+ *
2720
+ * @example
2721
+ * program.commandsGroup('Development Commands:);
2722
+ * program.command('watch')...
2723
+ * program.command('lint')...
2724
+ * ...
2725
+ *
2726
+ * @param {string} [heading]
2727
+ * @returns {Command | string}
2728
+ */
2729
+ commandsGroup(heading) {
2730
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2731
+ this._defaultCommandGroup = heading;
2732
+ return this;
2733
+ }
2734
+ /**
2735
+ * Set/get the default help group heading for options added to this command.
2736
+ * (This does not override a group set directly on the option using .helpGroup().)
2737
+ *
2738
+ * @example
2739
+ * program
2740
+ * .optionsGroup('Development Options:')
2741
+ * .option('-d, --debug', 'output extra debugging')
2742
+ * .option('-p, --profile', 'output profiling information')
2743
+ *
2744
+ * @param {string} [heading]
2745
+ * @returns {Command | string}
2746
+ */
2747
+ optionsGroup(heading) {
2748
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2749
+ this._defaultOptionGroup = heading;
2750
+ return this;
2751
+ }
2752
+ /**
2753
+ * @param {Option} option
2754
+ * @private
2755
+ */
2756
+ _initOptionGroup(option) {
2757
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2758
+ }
2759
+ /**
2760
+ * @param {Command} cmd
2761
+ * @private
2762
+ */
2763
+ _initCommandGroup(cmd) {
2764
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2765
+ }
2766
+ /**
2767
+ * Set the name of the command from script filename, such as process.argv[1],
2768
+ * or require.main.filename, or __filename.
2769
+ *
2770
+ * (Used internally and public although not documented in README.)
2771
+ *
2772
+ * @example
2773
+ * program.nameFromFilename(require.main.filename);
2774
+ *
2775
+ * @param {string} filename
2776
+ * @return {Command}
2777
+ */
2778
+ nameFromFilename(filename) {
2779
+ this._name = path$3.basename(filename, path$3.extname(filename));
2780
+ return this;
2781
+ }
2782
+ /**
2783
+ * Get or set the directory for searching for executable subcommands of this command.
2784
+ *
2785
+ * @example
2786
+ * program.executableDir(__dirname);
2787
+ * // or
2788
+ * program.executableDir('subcommands');
2789
+ *
2790
+ * @param {string} [path]
2791
+ * @return {(string|null|Command)}
2792
+ */
2793
+ executableDir(path) {
2794
+ if (path === void 0) return this._executableDir;
2795
+ this._executableDir = path;
2796
+ return this;
2797
+ }
2798
+ /**
2799
+ * Return program help documentation.
2800
+ *
2801
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2802
+ * @return {string}
2803
+ */
2804
+ helpInformation(contextOptions) {
2805
+ const helper = this.createHelp();
2806
+ const context = this._getOutputContext(contextOptions);
2807
+ helper.prepareContext({
2808
+ error: context.error,
2809
+ helpWidth: context.helpWidth,
2810
+ outputHasColors: context.hasColors
2811
+ });
2812
+ const text = helper.formatHelp(this, helper);
2813
+ if (context.hasColors) return text;
2814
+ return this._outputConfiguration.stripColor(text);
2815
+ }
2816
+ /**
2817
+ * @typedef HelpContext
2818
+ * @type {object}
2819
+ * @property {boolean} error
2820
+ * @property {number} helpWidth
2821
+ * @property {boolean} hasColors
2822
+ * @property {function} write - includes stripColor if needed
2823
+ *
2824
+ * @returns {HelpContext}
2825
+ * @private
2826
+ */
2827
+ _getOutputContext(contextOptions) {
2828
+ contextOptions = contextOptions || {};
2829
+ const error = !!contextOptions.error;
2830
+ let baseWrite;
2831
+ let hasColors;
2832
+ let helpWidth;
2833
+ if (error) {
2834
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2835
+ hasColors = this._outputConfiguration.getErrHasColors();
2836
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2837
+ } else {
2838
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2839
+ hasColors = this._outputConfiguration.getOutHasColors();
2840
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2841
+ }
2842
+ const write = (str) => {
2843
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2844
+ return baseWrite(str);
2845
+ };
2846
+ return {
2847
+ error,
2848
+ write,
2849
+ hasColors,
2850
+ helpWidth
2851
+ };
2852
+ }
2853
+ /**
2854
+ * Output help information for this command.
2855
+ *
2856
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2857
+ *
2858
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2859
+ */
2860
+ outputHelp(contextOptions) {
2861
+ let deprecatedCallback;
2862
+ if (typeof contextOptions === "function") {
2863
+ deprecatedCallback = contextOptions;
2864
+ contextOptions = void 0;
2865
+ }
2866
+ const outputContext = this._getOutputContext(contextOptions);
2867
+ /** @type {HelpTextEventContext} */
2868
+ const eventContext = {
2869
+ error: outputContext.error,
2870
+ write: outputContext.write,
2871
+ command: this
2872
+ };
2873
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2874
+ this.emit("beforeHelp", eventContext);
2875
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2876
+ if (deprecatedCallback) {
2877
+ helpInformation = deprecatedCallback(helpInformation);
2878
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2879
+ }
2880
+ outputContext.write(helpInformation);
2881
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2882
+ this.emit("afterHelp", eventContext);
2883
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2884
+ }
2885
+ /**
2886
+ * You can pass in flags and a description to customise the built-in help option.
2887
+ * Pass in false to disable the built-in help option.
2888
+ *
2889
+ * @example
2890
+ * program.helpOption('-?, --help' 'show help'); // customise
2891
+ * program.helpOption(false); // disable
2892
+ *
2893
+ * @param {(string | boolean)} flags
2894
+ * @param {string} [description]
2895
+ * @return {Command} `this` command for chaining
2896
+ */
2897
+ helpOption(flags, description) {
2898
+ if (typeof flags === "boolean") {
2899
+ if (flags) {
2900
+ if (this._helpOption === null) this._helpOption = void 0;
2901
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2902
+ } else this._helpOption = null;
2903
+ return this;
2904
+ }
2905
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2906
+ if (flags || description) this._initOptionGroup(this._helpOption);
2907
+ return this;
2908
+ }
2909
+ /**
2910
+ * Lazy create help option.
2911
+ * Returns null if has been disabled with .helpOption(false).
2912
+ *
2913
+ * @returns {(Option | null)} the help option
2914
+ * @package
2915
+ */
2916
+ _getHelpOption() {
2917
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2918
+ return this._helpOption;
2919
+ }
2920
+ /**
2921
+ * Supply your own option to use for the built-in help option.
2922
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2923
+ *
2924
+ * @param {Option} option
2925
+ * @return {Command} `this` command for chaining
2926
+ */
2927
+ addHelpOption(option) {
2928
+ this._helpOption = option;
2929
+ this._initOptionGroup(option);
2930
+ return this;
2931
+ }
2932
+ /**
2933
+ * Output help information and exit.
2934
+ *
2935
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2936
+ *
2937
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2938
+ */
2939
+ help(contextOptions) {
2940
+ this.outputHelp(contextOptions);
2941
+ let exitCode = Number(process$6.exitCode ?? 0);
2942
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2943
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2944
+ }
2945
+ /**
2946
+ * // Do a little typing to coordinate emit and listener for the help text events.
2947
+ * @typedef HelpTextEventContext
2948
+ * @type {object}
2949
+ * @property {boolean} error
2950
+ * @property {Command} command
2951
+ * @property {function} write
2952
+ */
2953
+ /**
2954
+ * Add additional text to be displayed with the built-in help.
2955
+ *
2956
+ * Position is 'before' or 'after' to affect just this command,
2957
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2958
+ *
2959
+ * @param {string} position - before or after built-in help
2960
+ * @param {(string | Function)} text - string to add, or a function returning a string
2961
+ * @return {Command} `this` command for chaining
2962
+ */
2963
+ addHelpText(position, text) {
2964
+ const allowedValues = [
2965
+ "beforeAll",
2966
+ "before",
2967
+ "after",
2968
+ "afterAll"
2969
+ ];
2970
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2971
+ Expecting one of '${allowedValues.join("', '")}'`);
2972
+ const helpEvent = `${position}Help`;
2973
+ this.on(helpEvent, (context) => {
2974
+ let helpStr;
2975
+ if (typeof text === "function") helpStr = text({
2976
+ error: context.error,
2977
+ command: context.command
2978
+ });
2979
+ else helpStr = text;
2980
+ if (helpStr) context.write(`${helpStr}\n`);
2981
+ });
2982
+ return this;
2983
+ }
2984
+ /**
2985
+ * Output help information if help flags specified
2986
+ *
2987
+ * @param {Array} args - array of options to search for help flags
2988
+ * @private
2989
+ */
2990
+ _outputHelpIfRequested(args) {
2991
+ const helpOption = this._getHelpOption();
2992
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2993
+ this.outputHelp();
2994
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2995
+ }
2996
+ }
2997
+ };
2998
+ /**
2999
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
3000
+ *
3001
+ * @param {string[]} args - array of arguments from node.execArgv
3002
+ * @returns {string[]}
3003
+ * @private
3004
+ */
3005
+ function incrementNodeInspectorPort(args) {
3006
+ return args.map((arg) => {
3007
+ if (!arg.startsWith("--inspect")) return arg;
3008
+ let debugOption;
3009
+ let debugHost = "127.0.0.1";
3010
+ let debugPort = "9229";
3011
+ let match;
3012
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3013
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3014
+ debugOption = match[1];
3015
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3016
+ else debugHost = match[3];
3017
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3018
+ debugOption = match[1];
3019
+ debugHost = match[3];
3020
+ debugPort = match[4];
3021
+ }
3022
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3023
+ return arg;
3024
+ });
3025
+ }
3026
+ /**
3027
+ * @returns {boolean | undefined}
3028
+ * @package
3029
+ */
3030
+ function useColor() {
3031
+ if (process$6.env.NO_COLOR || process$6.env.FORCE_COLOR === "0" || process$6.env.FORCE_COLOR === "false") return false;
3032
+ if (process$6.env.FORCE_COLOR || process$6.env.CLICOLOR_FORCE !== void 0) return true;
3033
+ }
3034
+ exports.Command = Command;
3035
+ exports.useColor = useColor;
3036
+ }));
3037
+ const { program: program$1, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = (/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
3038
+ const { Argument } = require_argument();
3039
+ const { Command } = require_command();
3040
+ const { CommanderError, InvalidArgumentError } = require_error();
3041
+ const { Help } = require_help();
3042
+ const { Option } = require_option();
3043
+ exports.program = new Command();
3044
+ exports.createCommand = (name) => new Command(name);
3045
+ exports.createOption = (flags, description) => new Option(flags, description);
3046
+ exports.createArgument = (name, description) => new Argument(name, description);
3047
+ /**
3048
+ * Expose classes
3049
+ */
3050
+ exports.Command = Command;
3051
+ exports.Option = Option;
3052
+ exports.Argument = Argument;
3053
+ exports.Help = Help;
3054
+ exports.CommanderError = CommanderError;
3055
+ exports.InvalidArgumentError = InvalidArgumentError;
3056
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
3057
+ })))(), 1)).default;
3058
+ //#endregion
3059
+ //#region src/utils/configShim.ts
3060
+ const CONFIG_EXTS = [
3061
+ "ts",
3062
+ "cts",
3063
+ "mts",
3064
+ "js",
3065
+ "cjs",
3066
+ "mjs"
3067
+ ];
3068
+ const findConfig = (cwd, base) => {
3069
+ for (const ext of CONFIG_EXTS) {
3070
+ const candidate = path.default.join(cwd, `${base}.config.${ext}`);
3071
+ if (fs.default.existsSync(candidate)) return candidate;
3072
+ }
3073
+ return null;
3074
+ };
3075
+ /**
3076
+ * Make Tile Push commands work against a published `@hot-updater/cli-tools`.
3077
+ *
3078
+ * Published cli-tools hardcodes its config filename to `hot-updater.config.*`
3079
+ * and ignores `HOT_UPDATER_CONFIG_NAME` (that override is fork-only). Tile Push
3080
+ * ships its config as `tile-push.config.*`, so on a plain `npm i` install the
3081
+ * loader would never find it.
3082
+ *
3083
+ * Fix: for the duration of a command, mirror `tile-push.config.*` to a transient
3084
+ * `hot-updater.config.<sameExt>` the published loader will find. Byte-identical,
3085
+ * so every relative import + env reference resolves the same. Removed after.
3086
+ *
3087
+ * No-op (writes nothing) when there's no `tile-push.config.*` (e.g. `init`,
3088
+ * `whoami`) or a real `hot-updater.config.*` already exists.
3089
+ */
3090
+ const ensureHotUpdaterConfig = (cwd = process.cwd()) => {
3091
+ const src = findConfig(cwd, "tile-push");
3092
+ if (!src) return () => {};
3093
+ if (findConfig(cwd, "hot-updater")) return () => {};
3094
+ const ext = src.split(".").pop();
3095
+ const dest = path.default.join(cwd, `hot-updater.config.${ext}`);
3096
+ try {
3097
+ fs.default.copyFileSync(src, dest);
3098
+ } catch {
3099
+ return () => {};
3100
+ }
3101
+ let cleaned = false;
3102
+ const cleanup = () => {
3103
+ if (cleaned) return;
3104
+ cleaned = true;
3105
+ try {
3106
+ fs.default.unlinkSync(dest);
3107
+ } catch {}
3108
+ };
3109
+ process.once("exit", cleanup);
3110
+ return cleanup;
3111
+ };
3112
+ //#endregion
3113
+ //#region src/utils/outputFilter.ts
3114
+ /**
3115
+ * Output filter that rewrites "hot-updater" / "Hot Updater" strings in
3116
+ * stdout/stderr to their Tile Push equivalents, so wrapped command output
3117
+ * never leaks the underlying tool's name.
3118
+ *
3119
+ * Implementation: we hijack process.stdout.write and process.stderr.write
3120
+ * for the duration of the wrapped call, run the regex on each chunk before
3121
+ * forwarding to the original writer. ANSI color codes pass through untouched
3122
+ * because the regex only matches alphabetic sequences.
3123
+ *
3124
+ * `withOutputFilter(fn)` is fire-and-forget — even if fn throws, the
3125
+ * originals are restored in a finally.
3126
+ *
3127
+ * It also mirrors `tile-push.config.*` to a transient `hot-updater.config.*`
3128
+ * (see {@link ensureHotUpdaterConfig}) so config discovery works against a
3129
+ * published `@hot-updater/cli-tools`, then removes it.
3130
+ */
3131
+ /**
3132
+ * How the user actually invokes this CLI, for the command suggestions we echo back.
3133
+ *
3134
+ * A wrapper sets this to its own verb: the Tile CLI runs us as `tile ota …`, so a
3135
+ * message reading "run 'tile-push fingerprint create'" sends people to a binary they
3136
+ * never installed. Defaults to our own name when nobody wraps us.
3137
+ */
3138
+ const CLI_NAME = process.env.TILE_PUSH_CLI_NAME?.trim() || "tile-push";
3139
+ /**
3140
+ * URLs must survive verbatim. Rewriting "hot-updater" everywhere also rewrote it INSIDE
3141
+ * the upstream repo link, so the banner advertised github.com/gronxb/tile-push — a
3142
+ * repository that does not exist — and asked users to star it. Park real URLs behind a
3143
+ * placeholder, run the rewrites, then restore them.
3144
+ */
3145
+ const URL_RE = /https?:\/\/\S+/g;
3146
+ const URL_TOKEN = "\0URL\0";
3147
+ const REPLACEMENTS = [
3148
+ [/Hot Updater/g, "Tile Push"],
3149
+ [/HotUpdater/g, "TilePush"],
3150
+ [/* @__PURE__ */ new RegExp("hot-updater(?= )", "g"), CLI_NAME],
3151
+ [/hot-updater/g, "tile-push"]
3152
+ ];
3153
+ /**
3154
+ * Drop the upstream banner entirely.
3155
+ *
3156
+ * ╭───────────────────────────────────────────╮
3157
+ * │ Tile Push - React Native OTA Solution │
3158
+ * │ Github: https://github.com/… │
3159
+ * │ Give a ⭐️ if you like it! │
3160
+ * ╰───────────────────────────────────────────╯
3161
+ *
3162
+ * It advertises a third-party repo and asks OUR users to star it, on every
3163
+ * command. It cannot be turned off upstream: `printBanner()` is called
3164
+ * unconditionally by every handler, and although `HOT_UPDATER_SKIP_BANNER=1` is
3165
+ * set in 18 places, nothing reads it. The only upstream guard is
3166
+ * `if (!options.json)` on three bundle subcommands — which is why `--json` was
3167
+ * the one clean path.
3168
+ *
3169
+ * Removing it HERE rather than in the Tile CLI is deliberate: the wrapper would
3170
+ * have to pipe the child's stdout to filter it, and this CLI is interactive
3171
+ * (clack prompts), so piping trades working prompts for a tidy banner. We are
3172
+ * already inside the write path, so it costs nothing here.
3173
+ *
3174
+ * Matched narrowly. The banner is a standalone rounded box; the boxes this CLI
3175
+ * draws itself open with `◇ …╮` and close with `├──╯`, so they cannot match.
3176
+ * The content guard is a second lock: a rounded box is dropped only if it
3177
+ * actually carries banner text.
3178
+ *
3179
+ * Caveat: this fires only when the banner arrives in one write, which is how
3180
+ * upstream emits it today. A future upstream that streamed it line-by-line
3181
+ * would slip through — visible immediately, and not worth carrying cross-chunk
3182
+ * state for until it happens.
3183
+ */
3184
+ const ROUNDED_BOX_RE = /╭[─]+╮[\s\S]*?╰[─]+╯\r?\n?/g;
3185
+ const BANNER_CONTENT_RE = /Give a ⭐|OTA Solution|Github:/;
3186
+ const stripBanner = (s) => s.replace(ROUNDED_BOX_RE, (block) => BANNER_CONTENT_RE.test(block) ? "" : block);
3187
+ const rewrite = (s) => {
3188
+ const urls = [];
3189
+ let out = s.replace(URL_RE, (u) => {
3190
+ urls.push(u);
3191
+ return URL_TOKEN;
3192
+ });
3193
+ for (const [pat, rep] of REPLACEMENTS) out = out.replace(pat, rep);
3194
+ let i = 0;
3195
+ return stripBanner(out.replace(new RegExp(URL_TOKEN, "g"), () => urls[i++] ?? ""));
3196
+ };
3197
+ const wrap = (original) => {
3198
+ return function wrapped(chunk, encOrCb, cb) {
3199
+ const filtered = rewrite(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
3200
+ if (typeof encOrCb === "function") return original.call(this, filtered, encOrCb);
3201
+ return original.call(this, filtered, encOrCb, cb);
3202
+ };
3203
+ };
3204
+ const withOutputFilter = async (fn) => {
3205
+ const origOut = process.stdout.write.bind(process.stdout);
3206
+ const origErr = process.stderr.write.bind(process.stderr);
3207
+ const cleanupConfig = ensureHotUpdaterConfig();
3208
+ process.stdout.write = wrap(origOut);
3209
+ process.stderr.write = wrap(origErr);
3210
+ try {
3211
+ return await fn();
3212
+ } finally {
3213
+ process.stdout.write = origOut;
3214
+ process.stderr.write = origErr;
3215
+ cleanupConfig();
3216
+ }
3217
+ };
3218
+ //#endregion
3219
+ //#region src/commands/bundle.ts
3220
+ const parseBooleanOption = (value) => {
3221
+ if (value === "true") return true;
3222
+ if (value === "false") return false;
3223
+ throw new InvalidArgumentError("must be true or false");
3224
+ };
3225
+ const parseRolloutCohortCount = (value) => {
3226
+ const count = Number.parseInt(value, 10);
3227
+ if (!Number.isInteger(count) || count < 0 || count > 1e3) throw new InvalidArgumentError("must be an integer between 0 and 1000");
3228
+ return count;
3229
+ };
3230
+ const platformOption = new Option("--platform <platform>", "ios | android").choices(["ios", "android"]);
3231
+ const withWrapEnv = async (fn) => {
3232
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3233
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3234
+ return withOutputFilter(fn);
3235
+ };
3236
+ /**
3237
+ * tile-push bundle <subcommand>
3238
+ *
3239
+ * Wraps hot-updater's bundle management commands. All subcommands run
3240
+ * through the configured database plugin — for tile-push customers that's
3241
+ * our tilePushDatabase, which proxies every call through the server.
3242
+ */
3243
+ const registerBundle = (program) => {
3244
+ const bundleCmd = program.command("bundle").description("Manage bundles");
3245
+ bundleCmd.command("list").description("List bundles, most recent first").option("-c, --channel <channel>", "filter by channel").option("--json", "output raw JSON").addOption(platformOption).option("--limit <n>", "max results", (value) => {
3246
+ const n = Number.parseInt(value, 10);
3247
+ if (!Number.isInteger(n) || n <= 0) throw new InvalidArgumentError("must be a positive integer");
3248
+ return n;
3249
+ }, 20).action(async (options) => {
3250
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handleBundleList)(options));
3251
+ });
3252
+ bundleCmd.command("show").description("Show one bundle by id").argument("<bundle-id>", "bundle id").option("--json", "output raw JSON").action(async (bundleId, options) => {
3253
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handleBundleShow)(bundleId, options));
3254
+ });
3255
+ bundleCmd.command("disable").description("Disable a bundle by id").argument("<bundle-id>", "bundle id").option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3256
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handleBundleSetEnabled)(bundleId, false, options));
3257
+ });
3258
+ bundleCmd.command("enable").description("Re-enable a bundle by id").argument("<bundle-id>", "bundle id").option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3259
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handleBundleSetEnabled)(bundleId, true, options));
3260
+ });
3261
+ bundleCmd.command("update").description("Update bundle rollout / targeting metadata").argument("<bundle-id>", "bundle id").option("--rollout-cohort-count <count>", "rollout cohort count (0-1000)", parseRolloutCohortCount).option("--force-update <value>", "force-update flag (true or false)", parseBooleanOption).option("--target-cohorts <cohorts>", "comma-separated target cohorts").option("--clear-target-cohorts", "clear target cohorts").option("--json", "output the updated bundle as JSON").option("-y, --yes", "skip confirmation prompt").action(async (...args) => {
3262
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handleBundleUpdate)(...args));
3263
+ });
3264
+ bundleCmd.command("delete").description("Delete a bundle record by id").argument("<bundle-id>", "bundle id").option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3265
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handleBundleDelete)(bundleId, options));
3266
+ });
3267
+ bundleCmd.command("promote").description("Move or copy a bundle to a different channel").argument("<bundle-id>", "bundle id").requiredOption("-t, --target <channel>", "target channel").addOption(new Option("-a, --action <action>", "copy creates a new bundle id; move keeps the id").choices(["copy", "move"]).default("copy")).option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3268
+ await withWrapEnv(() => (0, hot_updater_internal_commands.handlePromote)(bundleId, options));
3269
+ });
3270
+ };
3271
+ //#endregion
3272
+ //#region src/commands/channel.ts
3273
+ /**
3274
+ * tile-push channel
3275
+ * tile-push channel set <channel>
3276
+ *
3277
+ * Reads/writes native files (Android BuildConfig, iOS Info.plist) — no
3278
+ * server interaction, just local file ops.
3279
+ */
3280
+ const registerChannel = (program) => {
3281
+ const channelCmd = program.command("channel").description("Manage channels");
3282
+ channelCmd.action(async () => {
3283
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3284
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3285
+ await withOutputFilter(() => (0, hot_updater_internal_commands.handleChannel)());
3286
+ });
3287
+ channelCmd.command("set").description("Set the channel for Android (BuildConfig) and iOS (Info.plist)").argument("<channel>", "channel to set").action(async (channel) => {
3288
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3289
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3290
+ await withOutputFilter(() => (0, hot_updater_internal_commands.handleSetChannel)(channel));
3291
+ });
3292
+ };
3293
+ //#endregion
3294
+ //#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
3295
+ let isDockerCached;
3296
+ function hasDockerEnv() {
3297
+ try {
3298
+ node_fs.default.statSync("/.dockerenv");
3299
+ return true;
3300
+ } catch {
3301
+ return false;
3302
+ }
3303
+ }
3304
+ function hasDockerCGroup() {
3305
+ try {
3306
+ return node_fs.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
3307
+ } catch {
3308
+ return false;
3309
+ }
3310
+ }
3311
+ function isDocker() {
3312
+ if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
3313
+ return isDockerCached;
3314
+ }
3315
+ //#endregion
3316
+ //#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
3317
+ let cachedResult;
3318
+ const hasContainerEnv = () => {
3319
+ try {
3320
+ node_fs.default.statSync("/run/.containerenv");
3321
+ return true;
3322
+ } catch {
3323
+ return false;
3324
+ }
3325
+ };
3326
+ function isInsideContainer() {
3327
+ if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
3328
+ return cachedResult;
3329
+ }
3330
+ //#endregion
3331
+ //#region ../../node_modules/.pnpm/is-wsl@3.1.1/node_modules/is-wsl/index.js
3332
+ const isWsl = () => {
3333
+ if (node_process.default.platform !== "linux") return false;
3334
+ if (node_os.default.release().toLowerCase().includes("microsoft")) {
3335
+ if (isInsideContainer()) return false;
3336
+ return true;
3337
+ }
3338
+ try {
3339
+ if (node_fs.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) return !isInsideContainer();
3340
+ } catch {}
3341
+ if (node_fs.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || node_fs.default.existsSync("/run/WSL")) return !isInsideContainer();
3342
+ return false;
3343
+ };
3344
+ var is_wsl_default = node_process.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
3345
+ //#endregion
3346
+ //#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
3347
+ function defineLazyProperty(object, propertyName, valueGetter) {
3348
+ const define = (value) => Object.defineProperty(object, propertyName, {
3349
+ value,
3350
+ enumerable: true,
3351
+ writable: true
3352
+ });
3353
+ Object.defineProperty(object, propertyName, {
3354
+ configurable: true,
3355
+ enumerable: true,
3356
+ get() {
3357
+ const result = valueGetter();
3358
+ define(result);
3359
+ return result;
3360
+ },
3361
+ set(value) {
3362
+ define(value);
3363
+ }
3364
+ });
3365
+ return object;
3366
+ }
3367
+ //#endregion
3368
+ //#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
3369
+ const execFileAsync$3 = (0, node_util.promisify)(node_child_process.execFile);
3370
+ async function defaultBrowserId() {
3371
+ if (node_process.default.platform !== "darwin") throw new Error("macOS only");
3372
+ const { stdout } = await execFileAsync$3("defaults", [
3373
+ "read",
3374
+ "com.apple.LaunchServices/com.apple.launchservices.secure",
3375
+ "LSHandlers"
3376
+ ]);
3377
+ const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
3378
+ if (browserId === "com.apple.safari") return "com.apple.Safari";
3379
+ return browserId;
3380
+ }
3381
+ //#endregion
3382
+ //#region ../../node_modules/.pnpm/run-applescript@7.0.0/node_modules/run-applescript/index.js
3383
+ const execFileAsync$2 = (0, node_util.promisify)(node_child_process.execFile);
3384
+ async function runAppleScript(script, { humanReadableOutput = true } = {}) {
3385
+ if (node_process.default.platform !== "darwin") throw new Error("macOS only");
3386
+ const { stdout } = await execFileAsync$2("osascript", [
3387
+ "-e",
3388
+ script,
3389
+ humanReadableOutput ? [] : ["-ss"]
3390
+ ]);
3391
+ return stdout.trim();
3392
+ }
3393
+ //#endregion
3394
+ //#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
3395
+ async function bundleName(bundleId) {
3396
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
3397
+ }
3398
+ //#endregion
3399
+ //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
3400
+ const execFileAsync$1 = (0, node_util.promisify)(node_child_process.execFile);
3401
+ const windowsBrowserProgIds = {
3402
+ MSEdgeHTM: {
3403
+ name: "Edge",
3404
+ id: "com.microsoft.edge"
3405
+ },
3406
+ MSEdgeBHTML: {
3407
+ name: "Edge Beta",
3408
+ id: "com.microsoft.edge.beta"
3409
+ },
3410
+ MSEdgeDHTML: {
3411
+ name: "Edge Dev",
3412
+ id: "com.microsoft.edge.dev"
3413
+ },
3414
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
3415
+ name: "Edge",
3416
+ id: "com.microsoft.edge.old"
3417
+ },
3418
+ ChromeHTML: {
3419
+ name: "Chrome",
3420
+ id: "com.google.chrome"
3421
+ },
3422
+ ChromeBHTML: {
3423
+ name: "Chrome Beta",
3424
+ id: "com.google.chrome.beta"
3425
+ },
3426
+ ChromeDHTML: {
3427
+ name: "Chrome Dev",
3428
+ id: "com.google.chrome.dev"
3429
+ },
3430
+ ChromiumHTM: {
3431
+ name: "Chromium",
3432
+ id: "org.chromium.Chromium"
3433
+ },
3434
+ BraveHTML: {
3435
+ name: "Brave",
3436
+ id: "com.brave.Browser"
3437
+ },
3438
+ BraveBHTML: {
3439
+ name: "Brave Beta",
3440
+ id: "com.brave.Browser.beta"
3441
+ },
3442
+ BraveDHTML: {
3443
+ name: "Brave Dev",
3444
+ id: "com.brave.Browser.dev"
3445
+ },
3446
+ BraveSSHTM: {
3447
+ name: "Brave Nightly",
3448
+ id: "com.brave.Browser.nightly"
3449
+ },
3450
+ FirefoxURL: {
3451
+ name: "Firefox",
3452
+ id: "org.mozilla.firefox"
3453
+ },
3454
+ OperaStable: {
3455
+ name: "Opera",
3456
+ id: "com.operasoftware.Opera"
3457
+ },
3458
+ VivaldiHTM: {
3459
+ name: "Vivaldi",
3460
+ id: "com.vivaldi.Vivaldi"
3461
+ },
3462
+ "IE.HTTP": {
3463
+ name: "Internet Explorer",
3464
+ id: "com.microsoft.ie"
3465
+ }
3466
+ };
3467
+ new Map(Object.entries(windowsBrowserProgIds));
3468
+ var UnknownBrowserError = class extends Error {};
3469
+ async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
3470
+ const { stdout } = await _execFileAsync("reg", [
3471
+ "QUERY",
3472
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
3473
+ "/v",
3474
+ "ProgId"
3475
+ ]);
3476
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
3477
+ if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
3478
+ const { id } = match.groups;
3479
+ const dotIndex = id.lastIndexOf(".");
3480
+ const hyphenIndex = id.lastIndexOf("-");
3481
+ const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
3482
+ const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
3483
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {
3484
+ name: id,
3485
+ id
3486
+ };
3487
+ }
3488
+ //#endregion
3489
+ //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
3490
+ const execFileAsync = (0, node_util.promisify)(node_child_process.execFile);
3491
+ const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
3492
+ async function defaultBrowser() {
3493
+ if (node_process.default.platform === "darwin") {
3494
+ const id = await defaultBrowserId();
3495
+ return {
3496
+ name: await bundleName(id),
3497
+ id
3498
+ };
3499
+ }
3500
+ if (node_process.default.platform === "linux") {
3501
+ const { stdout } = await execFileAsync("xdg-mime", [
3502
+ "query",
3503
+ "default",
3504
+ "x-scheme-handler/http"
3505
+ ]);
3506
+ const id = stdout.trim();
3507
+ return {
3508
+ name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
3509
+ id
3510
+ };
3511
+ }
3512
+ if (node_process.default.platform === "win32") return defaultBrowser$1();
3513
+ throw new Error("Only macOS, Linux, and Windows are supported");
3514
+ }
3515
+ //#endregion
3516
+ //#region ../../node_modules/.pnpm/open@10.1.0/node_modules/open/index.js
3517
+ const __dirname$1 = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
3518
+ const localXdgOpenPath = node_path.default.join(__dirname$1, "xdg-open");
3519
+ const { platform, arch } = node_process.default;
3520
+ /**
3521
+ Get the mount point for fixed drives in WSL.
3522
+
3523
+ @inner
3524
+ @returns {string} The mount point.
3525
+ */
3526
+ const getWslDrivesMountPoint = (() => {
3527
+ const defaultMountPoint = "/mnt/";
3528
+ let mountPoint;
3529
+ return async function() {
3530
+ if (mountPoint) return mountPoint;
3531
+ const configFilePath = "/etc/wsl.conf";
3532
+ let isConfigFileExists = false;
3533
+ try {
3534
+ await node_fs_promises.default.access(configFilePath, node_fs_promises.constants.F_OK);
3535
+ isConfigFileExists = true;
3536
+ } catch {}
3537
+ if (!isConfigFileExists) return defaultMountPoint;
3538
+ const configContent = await node_fs_promises.default.readFile(configFilePath, { encoding: "utf8" });
3539
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
3540
+ if (!configMountPoint) return defaultMountPoint;
3541
+ mountPoint = configMountPoint.groups.mountPoint.trim();
3542
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
3543
+ return mountPoint;
3544
+ };
3545
+ })();
3546
+ const pTryEach = async (array, mapper) => {
3547
+ let latestError;
3548
+ for (const item of array) try {
3549
+ return await mapper(item);
3550
+ } catch (error) {
3551
+ latestError = error;
3552
+ }
3553
+ throw latestError;
3554
+ };
3555
+ const baseOpen = async (options) => {
3556
+ options = {
3557
+ wait: false,
3558
+ background: false,
3559
+ newInstance: false,
3560
+ allowNonzeroExitCode: false,
3561
+ ...options
3562
+ };
3563
+ if (Array.isArray(options.app)) return pTryEach(options.app, (singleApp) => baseOpen({
3564
+ ...options,
3565
+ app: singleApp
3566
+ }));
3567
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
3568
+ appArguments = [...appArguments];
3569
+ if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
3570
+ ...options,
3571
+ app: {
3572
+ name: appName,
3573
+ arguments: appArguments
3574
+ }
3575
+ }));
3576
+ if (app === "browser" || app === "browserPrivate") {
3577
+ const ids = {
3578
+ "com.google.chrome": "chrome",
3579
+ "google-chrome.desktop": "chrome",
3580
+ "org.mozilla.firefox": "firefox",
3581
+ "firefox.desktop": "firefox",
3582
+ "com.microsoft.msedge": "edge",
3583
+ "com.microsoft.edge": "edge",
3584
+ "microsoft-edge.desktop": "edge"
3585
+ };
3586
+ const flags = {
3587
+ chrome: "--incognito",
3588
+ firefox: "--private-window",
3589
+ edge: "--inPrivate"
3590
+ };
3591
+ const browser = await defaultBrowser();
3592
+ if (browser.id in ids) {
3593
+ const browserName = ids[browser.id];
3594
+ if (app === "browserPrivate") appArguments.push(flags[browserName]);
3595
+ return baseOpen({
3596
+ ...options,
3597
+ app: {
3598
+ name: apps[browserName],
3599
+ arguments: appArguments
3600
+ }
3601
+ });
3602
+ }
3603
+ throw new Error(`${browser.name} is not supported as a default browser`);
3604
+ }
3605
+ let command;
3606
+ const cliArguments = [];
3607
+ const childProcessOptions = {};
3608
+ if (platform === "darwin") {
3609
+ command = "open";
3610
+ if (options.wait) cliArguments.push("--wait-apps");
3611
+ if (options.background) cliArguments.push("--background");
3612
+ if (options.newInstance) cliArguments.push("--new");
3613
+ if (app) cliArguments.push("-a", app);
3614
+ } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
3615
+ const mountPoint = await getWslDrivesMountPoint();
3616
+ command = is_wsl_default ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${node_process.default.env.SYSTEMROOT || node_process.default.env.windir || "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
3617
+ cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
3618
+ if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
3619
+ const encodedArguments = ["Start"];
3620
+ if (options.wait) encodedArguments.push("-Wait");
3621
+ if (app) {
3622
+ encodedArguments.push(`"\`"${app}\`""`);
3623
+ if (options.target) appArguments.push(options.target);
3624
+ } else if (options.target) encodedArguments.push(`"${options.target}"`);
3625
+ if (appArguments.length > 0) {
3626
+ appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
3627
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
3628
+ }
3629
+ options.target = node_buffer.Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64");
3630
+ } else {
3631
+ if (app) command = app;
3632
+ else {
3633
+ const isBundled = !__dirname$1 || __dirname$1 === "/";
3634
+ let exeLocalXdgOpen = false;
3635
+ try {
3636
+ await node_fs_promises.default.access(localXdgOpenPath, node_fs_promises.constants.X_OK);
3637
+ exeLocalXdgOpen = true;
3638
+ } catch {}
3639
+ command = node_process.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
3640
+ }
3641
+ if (appArguments.length > 0) cliArguments.push(...appArguments);
3642
+ if (!options.wait) {
3643
+ childProcessOptions.stdio = "ignore";
3644
+ childProcessOptions.detached = true;
3645
+ }
3646
+ }
3647
+ if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
3648
+ if (options.target) cliArguments.push(options.target);
3649
+ const subprocess = node_child_process.default.spawn(command, cliArguments, childProcessOptions);
3650
+ if (options.wait) return new Promise((resolve, reject) => {
3651
+ subprocess.once("error", reject);
3652
+ subprocess.once("close", (exitCode) => {
3653
+ if (!options.allowNonzeroExitCode && exitCode > 0) {
3654
+ reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
3655
+ return;
3656
+ }
3657
+ resolve(subprocess);
3658
+ });
3659
+ });
3660
+ subprocess.unref();
3661
+ return subprocess;
3662
+ };
3663
+ const open = (target, options) => {
3664
+ if (typeof target !== "string") throw new TypeError("Expected a `target`");
3665
+ return baseOpen({
3666
+ ...options,
3667
+ target
3668
+ });
3669
+ };
3670
+ function detectArchBinary(binary) {
3671
+ if (typeof binary === "string" || Array.isArray(binary)) return binary;
3672
+ const { [arch]: archBinary } = binary;
3673
+ if (!archBinary) throw new Error(`${arch} is not supported`);
3674
+ return archBinary;
3675
+ }
3676
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
3677
+ if (wsl && is_wsl_default) return detectArchBinary(wsl);
3678
+ if (!platformBinary) throw new Error(`${platform} is not supported`);
3679
+ return detectArchBinary(platformBinary);
3680
+ }
3681
+ const apps = {};
3682
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
3683
+ darwin: "google chrome",
3684
+ win32: "chrome",
3685
+ linux: [
3686
+ "google-chrome",
3687
+ "google-chrome-stable",
3688
+ "chromium"
3689
+ ]
3690
+ }, { wsl: {
3691
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
3692
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
3693
+ } }));
3694
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
3695
+ darwin: "firefox",
3696
+ win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
3697
+ linux: "firefox"
3698
+ }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
3699
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
3700
+ darwin: "microsoft edge",
3701
+ win32: "msedge",
3702
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
3703
+ }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
3704
+ defineLazyProperty(apps, "browser", () => "browser");
3705
+ defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
3706
+ //#endregion
3707
+ //#region src/branding.ts
3708
+ var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3709
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
3710
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
3711
+ let formatter = (open, close, replace = open) => (input) => {
3712
+ let string = "" + input, index = string.indexOf(close, open.length);
3713
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
3714
+ };
3715
+ let replaceClose = (string, close, replace, index) => {
3716
+ let result = "", cursor = 0;
3717
+ do {
3718
+ result += string.substring(cursor, index) + replace;
3719
+ cursor = index + close.length;
3720
+ index = string.indexOf(close, cursor);
3721
+ } while (~index);
3722
+ return result + string.substring(cursor);
3723
+ };
3724
+ let createColors = (enabled = isColorSupported) => {
3725
+ let f = enabled ? formatter : () => String;
3726
+ return {
3727
+ isColorSupported: enabled,
3728
+ reset: f("\x1B[0m", "\x1B[0m"),
3729
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
3730
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
3731
+ italic: f("\x1B[3m", "\x1B[23m"),
3732
+ underline: f("\x1B[4m", "\x1B[24m"),
3733
+ inverse: f("\x1B[7m", "\x1B[27m"),
3734
+ hidden: f("\x1B[8m", "\x1B[28m"),
3735
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
3736
+ black: f("\x1B[30m", "\x1B[39m"),
3737
+ red: f("\x1B[31m", "\x1B[39m"),
3738
+ green: f("\x1B[32m", "\x1B[39m"),
3739
+ yellow: f("\x1B[33m", "\x1B[39m"),
3740
+ blue: f("\x1B[34m", "\x1B[39m"),
3741
+ magenta: f("\x1B[35m", "\x1B[39m"),
3742
+ cyan: f("\x1B[36m", "\x1B[39m"),
3743
+ white: f("\x1B[37m", "\x1B[39m"),
3744
+ gray: f("\x1B[90m", "\x1B[39m"),
3745
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
3746
+ bgRed: f("\x1B[41m", "\x1B[49m"),
3747
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
3748
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
3749
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
3750
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
3751
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
3752
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
3753
+ blackBright: f("\x1B[90m", "\x1B[39m"),
3754
+ redBright: f("\x1B[91m", "\x1B[39m"),
3755
+ greenBright: f("\x1B[92m", "\x1B[39m"),
3756
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
3757
+ blueBright: f("\x1B[94m", "\x1B[39m"),
3758
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
3759
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
3760
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
3761
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
3762
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
3763
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
3764
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
3765
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
3766
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
3767
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
3768
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
3769
+ };
3770
+ };
3771
+ module.exports = createColors();
3772
+ module.exports.createColors = createColors;
3773
+ })))(), 1);
3774
+ /**
3775
+ * Tile Push CLI banner. Printed at the start of each branded command
3776
+ * (deploy, init, bundle ops). Replaces the hot-updater banner which is
3777
+ * suppressed via HOT_UPDATER_SKIP_BANNER=1 when we invoke wrapped commands.
3778
+ */
3779
+ const BANNER_LINES = [
3780
+ " ████████╗██╗██╗ ███████╗ ██████╗ ██╗ ██╗███████╗██╗ ██╗",
3781
+ " ╚══██╔══╝██║██║ ██╔════╝ ██╔══██╗██║ ██║██╔════╝██║ ██║",
3782
+ " ██║ ██║██║ █████╗ ██████╔╝██║ ██║███████╗███████║",
3783
+ " ██║ ██║██║ ██╔══╝ ██╔═══╝ ██║ ██║╚════██║██╔══██║",
3784
+ " ██║ ██║███████╗███████╗ ██║ ╚██████╔╝███████║██║ ██║",
3785
+ " ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝"
3786
+ ];
3787
+ const TAGLINE = "OTA updates for React Native";
3788
+ const printTilePushBanner = (version) => {
3789
+ if (process.env.TILE_PUSH_SKIP_BANNER) return;
3790
+ const lines = ["", ...BANNER_LINES.map((l) => import_picocolors.default.cyan(l))];
3791
+ const taglineLine = version ? `${TAGLINE} · v${version}` : TAGLINE;
3792
+ lines.push("", ` ${import_picocolors.default.dim(taglineLine)}`, "");
3793
+ console.log(lines.join("\n"));
3794
+ };
3795
+ /**
3796
+ * Banner + tenant context. Use this for any command that's about to act on
3797
+ * a tenant (deploy, rollback, bundle disable/enable/delete) so the customer
3798
+ * sees which app they're about to touch BEFORE the action runs.
3799
+ *
3800
+ * Loads credentials best-effort: if not configured, prints the banner with
3801
+ * a "no credentials" warning instead of crashing — the underlying command
3802
+ * will surface the proper error a moment later, but the banner needs to
3803
+ * print first so the customer at least sees that we *tried* to identify
3804
+ * the tenant.
3805
+ */
3806
+ const printTilePushHeader = async (version) => {
3807
+ printTilePushBanner(version);
3808
+ if (process.env.TILE_PUSH_SKIP_BANNER) return;
3809
+ let appId = null;
3810
+ let apiUrl = null;
3811
+ try {
3812
+ const creds = await require_apiClient.loadCredentials();
3813
+ if (creds) {
3814
+ appId = creds.appId;
3815
+ apiUrl = creds.apiUrl ?? null;
3816
+ }
3817
+ } catch {}
3818
+ if (appId) {
3819
+ const label = (k) => import_picocolors.default.dim(k.padEnd(8));
3820
+ console.log(` ${label("Tenant:")}${import_picocolors.default.bold(import_picocolors.default.cyan(appId))}`);
3821
+ if (apiUrl) console.log(` ${label("Server:")}${apiUrl}`);
3822
+ console.log("");
3823
+ } else {
3824
+ console.log(` ${import_picocolors.default.yellow("!")} ${import_picocolors.default.yellow("No Tile Push credentials configured")} — run ${import_picocolors.default.bold("tile-push init")} or export ${import_picocolors.default.bold("TILE_PUSH_APP_ID")} + ${import_picocolors.default.bold("TILE_PUSH_TOKEN")}`);
3825
+ console.log("");
3826
+ }
3827
+ };
3828
+ /**
3829
+ * Branded success message — used at the end of deploy / bundle commands.
3830
+ */
3831
+ const tilePushSuccess = (msg) => `${import_picocolors.default.green("✔")} ${msg}`;
3832
+ /**
3833
+ * Branded error message — for top-level catches before process exit.
3834
+ */
3835
+ const tilePushError = (msg) => `${import_picocolors.default.red("✖")} ${import_picocolors.default.red(msg)}`;
3836
+ //#endregion
3837
+ //#region src/commands/console.ts
3838
+ const DEFAULT_CONSOLE_URL = "https://console.tile-push.app";
3839
+ /**
3840
+ * tile-push console
3841
+ *
3842
+ * Opens the web console for the current tenant in the default browser.
3843
+ * The URL is derived from the active appId so customers don't have to
3844
+ * remember it (or paste it from Slack).
3845
+ */
3846
+ const registerConsole = (program) => {
3847
+ program.command("console").description("Open the Tile Push web console for the current tenant").option("--url <baseUrl>", "console base URL (defaults to https://console.tile-push.app)").action(async (options) => {
3848
+ try {
3849
+ const client = await require_apiClient.TilePushClient.create();
3850
+ const target = `${(options.url ?? DEFAULT_CONSOLE_URL).replace(/\/+$/, "")}/${encodeURIComponent(client.appId)}`;
3851
+ console.log(`Opening ${target} ...`);
3852
+ await open(target);
3853
+ } catch (err) {
3854
+ console.error(tilePushError(err.message));
3855
+ process.exitCode = 1;
3856
+ }
3857
+ });
3858
+ };
3859
+ //#endregion
3860
+ //#region src/commands/deploy.ts
3861
+ const SEMVER_RANGE_PATTERN = /^[\d\sxX*~^.<>=|&-]+$/;
3862
+ const DEFAULT_CHANNEL = "production";
3863
+ /**
3864
+ * tile-push deploy
3865
+ *
3866
+ * Wraps hot-updater's deploy command. The wrap injects:
3867
+ * - HOT_UPDATER_CONFIG_NAME=tile-push so the loader looks for tile-push.config.ts
3868
+ * - HOT_UPDATER_SKIP_BANNER=1 so the hot-updater banner is suppressed
3869
+ * - withOutputFilter() so any leaking "Hot Updater" strings become "Tile Push"
3870
+ * - our own banner before invocation
3871
+ */
3872
+ const registerDeploy = (program) => {
3873
+ program.command("deploy").description("Build and ship a new bundle to Tile Push").addOption(new Option("-p, --platform <platform>", "ios | android").choices(["ios", "android"])).addOption(new Option("-t, --target-app-version <targetAppVersion>", "target app version (semver, e.g. 1.0.0, 1.x.x)").argParser((value) => {
3874
+ if (!SEMVER_RANGE_PATTERN.test(value)) throw new InvalidArgumentError("Invalid semver range (e.g. 1.0.0, 1.x.x).");
3875
+ return value;
3876
+ })).addOption(new Option("-d, --disabled", "ship disabled").default(false)).addOption(new Option("-f, --force-update", "require immediate update on launch").default(false)).addOption(new Option("-o, --bundle-output-path <bundleOutputPath>", "output dir for the bundle archive")).addOption(new Option("-r, --rollout <percentage>", "rollout percentage (0-100)").argParser((value) => {
3877
+ try {
3878
+ return (0, hot_updater_internal_commands.normalizeRolloutPercentage)(value);
3879
+ } catch (error) {
3880
+ throw new InvalidArgumentError(error.message);
3881
+ }
3882
+ }).default(100)).addOption(new Option("-i, --interactive", "prompt for missing options interactively").default(true)).addOption(new Option("-c, --channel <channel>", "release channel").default(DEFAULT_CHANNEL)).addOption(new Option("-m, --message <message>", "release notes; falls back to the latest git commit message")).action(async (options) => {
3883
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3884
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3885
+ await printTilePushHeader();
3886
+ await withOutputFilter(() => (0, hot_updater_internal_commands.deploy)(options));
3887
+ });
3888
+ };
3889
+ //#endregion
3890
+ //#region src/commands/doctor.ts
3891
+ const fmt = (c) => {
3892
+ return `${c.status === "ok" ? import_picocolors.default.green("✔") : c.status === "warn" ? import_picocolors.default.yellow("!") : import_picocolors.default.red("✖")} ${c.name} — ${c.detail}`;
3893
+ };
3894
+ /**
3895
+ * tile-push doctor
3896
+ *
3897
+ * Runs through the common setup checks and reports which ones pass/fail.
3898
+ * Customer-facing — message wording assumes no prior context.
3899
+ */
3900
+ const registerDoctor = (program) => {
3901
+ program.command("doctor").description("Check the health of your Tile Push setup").option("--json", "output machine-readable JSON").action(async (options) => {
3902
+ const checks = [];
3903
+ const cwd = process.cwd();
3904
+ const configPath = (0, node_path.join)(cwd, "tile-push.config.ts");
3905
+ checks.push((0, node_fs.existsSync)(configPath) ? {
3906
+ name: "Config",
3907
+ status: "ok",
3908
+ detail: `tile-push.config.ts found at ${cwd}`
3909
+ } : {
3910
+ name: "Config",
3911
+ status: "fail",
3912
+ detail: "tile-push.config.ts missing in cwd. Run `tile-push init`."
3913
+ });
3914
+ const diag = await require_apiClient.credentialsDiagnostic();
3915
+ if (diag.source === "env") checks.push({
3916
+ name: "Credentials",
3917
+ status: "ok",
3918
+ detail: `Loaded from ${diag.pathOrEnv}`
3919
+ });
3920
+ else if (diag.source === "file") checks.push({
3921
+ name: "Credentials",
3922
+ status: diag.modeOk ? "ok" : "warn",
3923
+ detail: diag.modeOk ? `Loaded from ${diag.pathOrEnv} (mode 0600)` : `Loaded from ${diag.pathOrEnv} but permissions are not 0600 — anyone with shell access can read your deploy token`
3924
+ });
3925
+ else checks.push({
3926
+ name: "Credentials",
3927
+ status: "fail",
3928
+ detail: `No credentials. Run \`tile-push init\` or set TILE_PUSH_APP_ID + TILE_PUSH_TOKEN.`
3929
+ });
3930
+ if (await require_apiClient.loadCredentials()) try {
3931
+ const me = await (await require_apiClient.TilePushClient.create()).get("/me");
3932
+ checks.push({
3933
+ name: "Server",
3934
+ status: "ok",
3935
+ detail: `Authenticated as "${me.tenantName}" with token "${me.tokenLabel}"`
3936
+ });
3937
+ } catch (err) {
3938
+ checks.push({
3939
+ name: "Server",
3940
+ status: "fail",
3941
+ detail: `Could not reach Tile Push API: ${err.message}`
3942
+ });
3943
+ }
3944
+ else checks.push({
3945
+ name: "Server",
3946
+ status: "warn",
3947
+ detail: "Skipped — no credentials to test with"
3948
+ });
3949
+ if ((0, node_fs.existsSync)((0, node_path.join)(cwd, "package.json"))) checks.push({
3950
+ name: "Project",
3951
+ status: "ok",
3952
+ detail: `package.json found at ${cwd}`
3953
+ });
3954
+ else checks.push({
3955
+ name: "Project",
3956
+ status: "warn",
3957
+ detail: "No package.json in cwd — run doctor from your RN project root"
3958
+ });
3959
+ if (options.json) {
3960
+ console.log(JSON.stringify(checks, null, 2));
3961
+ if (!checks.every((c) => c.status === "ok")) process.exitCode = 1;
3962
+ return;
3963
+ }
3964
+ for (const c of checks) console.log(fmt(c));
3965
+ const failed = checks.filter((c) => c.status === "fail");
3966
+ if (failed.length > 0) {
3967
+ console.log("");
3968
+ console.log(tilePushError(`${failed.length} check(s) failed.`));
3969
+ process.exitCode = 1;
3970
+ } else {
3971
+ console.log("");
3972
+ console.log(import_picocolors.default.green("All checks passed."));
3973
+ }
3974
+ });
3975
+ };
3976
+ //#endregion
3977
+ //#region src/commands/fingerprint.ts
3978
+ /**
3979
+ * tile-push fingerprint — compute / verify current fingerprint
3980
+ * tile-push fingerprint create — write a new fingerprint snapshot
3981
+ *
3982
+ * Fingerprints are pure local computation (no server interaction), so
3983
+ * these wraps exist purely for branding consistency.
3984
+ */
3985
+ const registerFingerprint = (program) => {
3986
+ const fpCmd = program.command("fingerprint").description("Generate fingerprint");
3987
+ fpCmd.action(async () => {
3988
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3989
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3990
+ await withOutputFilter(() => (0, hot_updater_internal_commands.handleFingerprint)());
3991
+ });
3992
+ fpCmd.command("create").description("Create fingerprint").action(async () => {
3993
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3994
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3995
+ await withOutputFilter(() => (0, hot_updater_internal_commands.handleCreateFingerprint)());
3996
+ });
3997
+ };
3998
+ //#endregion
3999
+ //#region src/commands/info.ts
4000
+ /**
4001
+ * tile-push info
4002
+ *
4003
+ * Prints every setting the CLI will resolve at runtime AND where each value
4004
+ * came from (env var, project .env file, ~/.tile-push/credentials.json,
4005
+ * default). Equivalent to `sentry-cli info` — the debugging tool you reach
4006
+ * for first when something resolves to a value you didn't expect.
4007
+ *
4008
+ * Non-destructive. Read-only. Safe to run anywhere.
4009
+ */
4010
+ const DEFAULT_API_URL = "https://ota.tile.dev";
4011
+ const CREDS_PATH = (0, node_path.join)((0, node_os.homedir)(), ".tile-push", "credentials.json");
4012
+ const sourceLabel = (s) => {
4013
+ switch (s.kind) {
4014
+ case "env": return `env ${s.name}`;
4015
+ case "dotenv": return `${s.path} (.env file)`;
4016
+ case "credsFile": return s.path;
4017
+ case "default": return "default";
4018
+ case "missing": return "not set";
4019
+ }
4020
+ };
4021
+ const maskToken = (token) => {
4022
+ if (token.length <= 8) return "•".repeat(token.length);
4023
+ const tail = token.slice(-4);
4024
+ return `${token.slice(0, 4)}${"•".repeat(Math.min(token.length - 8, 12))}${tail}`;
4025
+ };
4026
+ /**
4027
+ * Parse a .env file just enough to pull out the keys we care about. We
4028
+ * deliberately don't depend on the `dotenv` package — we only need to
4029
+ * surface the value to the user; we don't load it into process.env (that's
4030
+ * the project's tile-push.config.ts's job via `import "dotenv/config"`).
4031
+ */
4032
+ const readDotenvKey = (envPath, key) => {
4033
+ if (!(0, node_fs.existsSync)(envPath)) return null;
4034
+ try {
4035
+ const text = (0, node_fs.readFileSync)(envPath, "utf8");
4036
+ for (const raw of text.split("\n")) {
4037
+ const line = raw.trim();
4038
+ if (!line || line.startsWith("#")) continue;
4039
+ const eq = line.indexOf("=");
4040
+ if (eq === -1) continue;
4041
+ if (line.slice(0, eq).trim() !== key) continue;
4042
+ let v = line.slice(eq + 1).trim();
4043
+ if (v.startsWith("\"") && v.endsWith("\"") || v.startsWith("'") && v.endsWith("'")) v = v.slice(1, -1);
4044
+ return v;
4045
+ }
4046
+ } catch {}
4047
+ return null;
4048
+ };
4049
+ const readCredsFile = () => {
4050
+ if (!(0, node_fs.existsSync)(CREDS_PATH)) return null;
4051
+ try {
4052
+ const raw = (0, node_fs.readFileSync)(CREDS_PATH, "utf8");
4053
+ return JSON.parse(raw);
4054
+ } catch {
4055
+ return null;
4056
+ }
4057
+ };
4058
+ const credsFileMode = () => {
4059
+ if (!(0, node_fs.existsSync)(CREDS_PATH)) return null;
4060
+ try {
4061
+ const m = (0, node_fs.statSync)(CREDS_PATH).mode & 511;
4062
+ return {
4063
+ ok: m === 384,
4064
+ mode: m.toString(8).padStart(4, "0")
4065
+ };
4066
+ } catch {
4067
+ return null;
4068
+ }
4069
+ };
4070
+ /**
4071
+ * Resolve a single string-valued setting in priority order:
4072
+ * 1. env var
4073
+ * 2. .env file in cwd
4074
+ * 3. credentials file
4075
+ * 4. fallback default (if provided)
4076
+ *
4077
+ * Also tracks any conflicting values from lower-priority sources so we can
4078
+ * warn about them — drift between .env and creds.json is a common cause of
4079
+ * "why am I deploying to the wrong tenant?"
4080
+ */
4081
+ const resolveSetting = (config) => {
4082
+ const candidates = [];
4083
+ if (config.envName) {
4084
+ const v = process.env[config.envName];
4085
+ if (v) candidates.push({
4086
+ value: v,
4087
+ source: {
4088
+ kind: "env",
4089
+ name: config.envName
4090
+ }
4091
+ });
4092
+ }
4093
+ if (config.dotenvKey) {
4094
+ const v = readDotenvKey(config.dotenvPath, config.dotenvKey);
4095
+ if (v) candidates.push({
4096
+ value: v,
4097
+ source: {
4098
+ kind: "dotenv",
4099
+ path: config.dotenvPath
4100
+ }
4101
+ });
4102
+ }
4103
+ if (config.credsValue) candidates.push({
4104
+ value: config.credsValue,
4105
+ source: {
4106
+ kind: "credsFile",
4107
+ path: CREDS_PATH
4108
+ }
4109
+ });
4110
+ if (candidates.length === 0) {
4111
+ if (config.fallback) return {
4112
+ value: config.fallback,
4113
+ source: { kind: "default" }
4114
+ };
4115
+ return {
4116
+ value: null,
4117
+ source: { kind: "missing" }
4118
+ };
4119
+ }
4120
+ const [primary, ...rest] = candidates;
4121
+ const conflicts = rest.filter((c) => c.value !== primary.value);
4122
+ return {
4123
+ value: primary.value,
4124
+ source: primary.source,
4125
+ conflicts: conflicts.length > 0 ? conflicts : void 0
4126
+ };
4127
+ };
4128
+ const fmtKv = (key, value, source) => {
4129
+ return ` ${import_picocolors.default.bold(key.padEnd(8))}${value} ${import_picocolors.default.dim(`← ${source}`)}`;
4130
+ };
4131
+ const VERSION$1 = "0.1.0";
4132
+ const registerInfo = (program) => {
4133
+ program.command("info").description("Print resolved Tile Push CLI settings and where each came from").option("--no-network", "skip the server reachability + auth check").option("--json", "output machine-readable JSON").action(async (options) => {
4134
+ const cwd = process.cwd();
4135
+ const configPath = (0, node_path.join)(cwd, "tile-push.config.ts");
4136
+ const envPath = (0, node_path.join)(cwd, ".env");
4137
+ const pkgPath = (0, node_path.join)(cwd, "package.json");
4138
+ const creds = readCredsFile();
4139
+ const credsMode = credsFileMode();
4140
+ const appId = resolveSetting({
4141
+ envName: "TILE_PUSH_APP_ID",
4142
+ dotenvKey: "TILE_PUSH_APP_ID",
4143
+ dotenvPath: envPath,
4144
+ credsValue: creds?.appId
4145
+ });
4146
+ const token = resolveSetting({
4147
+ envName: "TILE_PUSH_TOKEN",
4148
+ dotenvKey: "TILE_PUSH_TOKEN",
4149
+ dotenvPath: envPath,
4150
+ credsValue: creds?.token
4151
+ });
4152
+ const apiUrl = resolveSetting({
4153
+ envName: "TILE_PUSH_API_URL",
4154
+ dotenvKey: null,
4155
+ dotenvPath: envPath,
4156
+ credsValue: creds?.apiUrl,
4157
+ fallback: DEFAULT_API_URL
4158
+ });
4159
+ if (options.json) {
4160
+ const payload = {
4161
+ version: VERSION$1,
4162
+ binary: process.argv[1],
4163
+ node: process.version,
4164
+ platform: `${process.platform}/${process.arch}`,
4165
+ cwd,
4166
+ project: {
4167
+ configPath,
4168
+ configExists: (0, node_fs.existsSync)(configPath),
4169
+ envPath,
4170
+ envExists: (0, node_fs.existsSync)(envPath),
4171
+ pkgPath,
4172
+ pkgExists: (0, node_fs.existsSync)(pkgPath)
4173
+ },
4174
+ user: {
4175
+ credsPath: CREDS_PATH,
4176
+ credsExists: !!creds,
4177
+ credsModeOk: credsMode?.ok ?? null,
4178
+ credsMode: credsMode?.mode ?? null
4179
+ },
4180
+ settings: {
4181
+ appId: {
4182
+ value: appId.value,
4183
+ source: sourceLabel(appId.source)
4184
+ },
4185
+ token: {
4186
+ value: token.value ? maskToken(token.value) : null,
4187
+ source: sourceLabel(token.source)
4188
+ },
4189
+ apiUrl: {
4190
+ value: apiUrl.value,
4191
+ source: sourceLabel(apiUrl.source)
4192
+ }
4193
+ },
4194
+ conflicts: {
4195
+ appId: appId.conflicts?.map((c) => ({
4196
+ value: c.value,
4197
+ source: sourceLabel(c.source)
4198
+ })),
4199
+ token: token.conflicts?.map((c) => ({
4200
+ value: maskToken(c.value),
4201
+ source: sourceLabel(c.source)
4202
+ })),
4203
+ apiUrl: apiUrl.conflicts?.map((c) => ({
4204
+ value: c.value,
4205
+ source: sourceLabel(c.source)
4206
+ }))
4207
+ }
4208
+ };
4209
+ console.log(JSON.stringify(payload, null, 2));
4210
+ return;
4211
+ }
4212
+ const rel = (p) => (0, node_path.relative)(cwd, p) || `.${p.endsWith("/") ? "/" : ""}`;
4213
+ console.log("");
4214
+ console.log(import_picocolors.default.bold("Tile Push CLI"));
4215
+ console.log(` version ${VERSION$1}`);
4216
+ console.log(` binary ${process.argv[1]}`);
4217
+ console.log(` node ${process.version}`);
4218
+ console.log(` platform ${process.platform}/${process.arch}`);
4219
+ console.log(` cwd ${cwd}`);
4220
+ console.log("");
4221
+ console.log(import_picocolors.default.bold("Project files (resolved from cwd)"));
4222
+ const mark = (ok) => ok ? import_picocolors.default.green("✔") : import_picocolors.default.dim("·");
4223
+ console.log(` ${mark((0, node_fs.existsSync)(configPath))} tile-push.config.ts ${import_picocolors.default.dim(rel(configPath))}`);
4224
+ console.log(` ${mark((0, node_fs.existsSync)(envPath))} .env ${import_picocolors.default.dim(rel(envPath))}`);
4225
+ console.log(` ${mark((0, node_fs.existsSync)(pkgPath))} package.json ${import_picocolors.default.dim(rel(pkgPath))}`);
4226
+ console.log("");
4227
+ console.log(import_picocolors.default.bold("User files (~/.tile-push)"));
4228
+ if (creds) {
4229
+ const modeColor = credsMode?.ok ?? false ? import_picocolors.default.green : import_picocolors.default.yellow;
4230
+ console.log(` ${import_picocolors.default.green("✔")} credentials.json ${import_picocolors.default.dim(CREDS_PATH)} ${modeColor(`(mode ${credsMode?.mode})`)}`);
4231
+ if (credsMode && !credsMode.ok) console.log(import_picocolors.default.yellow(` ! permissions should be 0600 — run: chmod 600 ${CREDS_PATH}`));
4232
+ } else console.log(` ${import_picocolors.default.dim("·")} credentials.json ${import_picocolors.default.dim(`${CREDS_PATH} (not present)`)}`);
4233
+ console.log("");
4234
+ console.log(import_picocolors.default.bold("Resolved settings"));
4235
+ if (appId.value) console.log(fmtKv("appId", appId.value, sourceLabel(appId.source)));
4236
+ else console.log(fmtKv("appId", import_picocolors.default.red("(not set)"), sourceLabel(appId.source)));
4237
+ if (token.value) console.log(fmtKv("token", maskToken(token.value), sourceLabel(token.source)));
4238
+ else console.log(fmtKv("token", import_picocolors.default.red("(not set)"), sourceLabel(token.source)));
4239
+ console.log(fmtKv("apiUrl", apiUrl.value ?? "", sourceLabel(apiUrl.source)));
4240
+ const conflicts = [
4241
+ ["appId", appId],
4242
+ ["token", token],
4243
+ ["apiUrl", apiUrl]
4244
+ ].filter(([, r]) => r.conflicts && r.conflicts.length > 0);
4245
+ if (conflicts.length > 0) {
4246
+ console.log("");
4247
+ console.log(import_picocolors.default.yellow(import_picocolors.default.bold("Conflicts")));
4248
+ for (const [name, r] of conflicts) {
4249
+ console.log(` ${import_picocolors.default.yellow("!")} ${name} differs across sources:`);
4250
+ for (const c of r.conflicts) {
4251
+ const shown = name === "token" ? maskToken(c.value) : c.value;
4252
+ console.log(` ${import_picocolors.default.dim(sourceLabel(c.source))}: ${shown}`);
4253
+ }
4254
+ }
4255
+ console.log(import_picocolors.default.dim(" (the value listed above under 'Resolved settings' wins per precedence: env > .env > credentials.json)"));
4256
+ }
4257
+ if (options.network === false) {
4258
+ console.log("");
4259
+ console.log(import_picocolors.default.dim("Server check skipped (--no-network)."));
4260
+ return;
4261
+ }
4262
+ if (!appId.value || !token.value) {
4263
+ console.log("");
4264
+ console.log(import_picocolors.default.dim("Server check skipped — no appId/token to authenticate with."));
4265
+ return;
4266
+ }
4267
+ console.log("");
4268
+ console.log(import_picocolors.default.bold("Server check"));
4269
+ try {
4270
+ const me = await (await require_apiClient.TilePushClient.create()).get("/me");
4271
+ console.log(` ${import_picocolors.default.green("✔")} authenticated as "${me.tenantName}" (token: ${me.tokenLabel})`);
4272
+ } catch (err) {
4273
+ const msg = err instanceof Error ? err.message : String(err);
4274
+ console.log(` ${import_picocolors.default.red("✖")} ${msg}`);
4275
+ process.exitCode = 1;
4276
+ }
4277
+ });
4278
+ };
4279
+ //#endregion
4280
+ //#region src/commands/init.ts
4281
+ const prompt = (question, defaultValue) => {
4282
+ const rl = (0, node_readline.createInterface)({
4283
+ input: process.stdin,
4284
+ output: process.stdout
4285
+ });
4286
+ const promptText = defaultValue ? `${question} ${import_picocolors.default.dim(`(${defaultValue})`)} ` : `${question} `;
4287
+ return new Promise((resolve) => {
4288
+ rl.question(promptText, (answer) => {
4289
+ rl.close();
4290
+ resolve(answer.trim() || defaultValue || "");
4291
+ });
4292
+ });
4293
+ };
4294
+ const promptYesNo = async (question, defaultYes = true) => {
4295
+ const hint = defaultYes ? "Y/n" : "y/N";
4296
+ const ans = await prompt(`${question} ${import_picocolors.default.dim(`[${hint}]`)}`);
4297
+ if (!ans) return defaultYes;
4298
+ return /^y(es)?$/i.test(ans);
4299
+ };
4300
+ const detectBundler = (cwd) => {
4301
+ const pkgPath = (0, node_path.join)(cwd, "package.json");
4302
+ if (!(0, node_fs.existsSync)(pkgPath)) return null;
4303
+ try {
4304
+ const raw = (0, node_fs.readFileSync)(pkgPath, "utf8");
4305
+ const pkg = JSON.parse(raw);
4306
+ const all = {
4307
+ ...pkg.dependencies,
4308
+ ...pkg.devDependencies
4309
+ };
4310
+ if (all.expo) return "expo";
4311
+ if (all["react-native"]) return "metro";
4312
+ } catch {}
4313
+ return null;
4314
+ };
4315
+ const renderConfig = (bundler) => {
4316
+ return `// Auto-loads .env so TILE_PUSH_APP_ID below resolves when invoked via
4317
+ // \`tile-push deploy\` from a shell that hasn't exported it explicitly.
4318
+ import "dotenv/config";
4319
+
4320
+ import { defineConfig } from "hot-updater";
4321
+ ${bundler === "expo" ? `import { expo } from "@hot-updater/expo";` : `import { metro } from "@hot-updater/metro";`}
4322
+ import { tilePushDatabase, tilePushStorage } from "@tiledev/tile-push-cli";
4323
+
4324
+ const appId = process.env.TILE_PUSH_APP_ID;
4325
+ if (!appId) {
4326
+ throw new Error(
4327
+ "TILE_PUSH_APP_ID is not set. Run \`tile-push init\` or export it manually.",
4328
+ );
4329
+ }
4330
+
4331
+ export default defineConfig({
4332
+ build: ${bundler === "expo" ? "expo({ enableHermes: true })" : "metro()"},
4333
+ storage: tilePushStorage({ appId }),
4334
+ database: tilePushDatabase({ appId }),
4335
+ // Fingerprint strategy: device sends its native fingerprint hash on
4336
+ // check-update and is only served bundles built from a matching native
4337
+ // tree. Safer than appVersion alone — catches accidental native drift.
4338
+ updateStrategy: "fingerprint",
4339
+ });
4340
+ `;
4341
+ };
4342
+ const upsertEnv = async (path, key, value) => {
4343
+ let existing = "";
4344
+ try {
4345
+ existing = await (0, node_fs_promises.readFile)(path, "utf8");
4346
+ } catch (err) {
4347
+ if (err.code !== "ENOENT") throw err;
4348
+ }
4349
+ const lines = existing.split("\n");
4350
+ let found = false;
4351
+ for (let i = 0; i < lines.length; i++) if (lines[i].startsWith(`${key}=`)) {
4352
+ lines[i] = `${key}=${value}`;
4353
+ found = true;
4354
+ break;
4355
+ }
4356
+ if (!found) {
4357
+ if (existing && !existing.endsWith("\n")) lines.push("");
4358
+ lines.push(`${key}=${value}`);
4359
+ }
4360
+ await (0, node_fs_promises.writeFile)(path, lines.join("\n"));
4361
+ };
4362
+ const registerInit = (program) => {
4363
+ program.command("init").description("Configure a project for Tile Push deploys").option("--app-id <appId>", "tenant app id (tk_...)").option("--token <token>", "deploy token").option("--bundler <bundler>", "bundler to use (metro|expo); auto-detected if omitted").option("--api-url <url>", "Tile Push API URL override").option("-y, --yes", "accept overwrites without prompting").action(async (options) => {
4364
+ printTilePushBanner();
4365
+ const cwd = process.cwd();
4366
+ const configPath = (0, node_path.join)(cwd, "tile-push.config.ts");
4367
+ const envPath = (0, node_path.join)(cwd, ".env");
4368
+ const appId = options.appId ?? await prompt("App id (e.g. tk_acme):");
4369
+ if (!appId) {
4370
+ console.error(tilePushError("App id is required."));
4371
+ process.exitCode = 1;
4372
+ return;
4373
+ }
4374
+ const token = options.token ?? await prompt("Deploy token (paste from the Tile Push console):");
4375
+ if (!token) {
4376
+ console.error(tilePushError("Deploy token is required."));
4377
+ process.exitCode = 1;
4378
+ return;
4379
+ }
4380
+ const detected = detectBundler(cwd);
4381
+ const bundler = options.bundler ?? detected ?? await prompt("Bundler (metro|expo):", "metro");
4382
+ if ((0, node_fs.existsSync)(configPath) && !options.yes) if (!await promptYesNo(`${configPath} already exists. Overwrite?`, false)) console.log("Skipped config write.");
4383
+ else {
4384
+ await (0, node_fs_promises.writeFile)(configPath, renderConfig(bundler));
4385
+ console.log(tilePushSuccess(`Wrote ${configPath}`));
4386
+ }
4387
+ else {
4388
+ await (0, node_fs_promises.writeFile)(configPath, renderConfig(bundler));
4389
+ console.log(tilePushSuccess(`Wrote ${configPath}`));
4390
+ }
4391
+ await upsertEnv(envPath, "TILE_PUSH_APP_ID", appId);
4392
+ console.log(tilePushSuccess(`Added TILE_PUSH_APP_ID to ${envPath}`));
4393
+ await require_apiClient.saveCredentials({
4394
+ appId,
4395
+ token,
4396
+ apiUrl: options.apiUrl
4397
+ });
4398
+ console.log(tilePushSuccess("Saved credentials to ~/.tile-push/credentials.json"));
4399
+ console.log("");
4400
+ console.log(`Next steps:`);
4401
+ console.log(` ${import_picocolors.default.cyan("tile-push deploy")} — ship a bundle`);
4402
+ console.log(` ${import_picocolors.default.cyan("tile-push whoami")} — verify your connection`);
4403
+ console.log(` ${import_picocolors.default.cyan("tile-push doctor")} — diagnose setup issues`);
4404
+ });
4405
+ };
4406
+ //#endregion
4407
+ //#region src/commands/rollback.ts
4408
+ /**
4409
+ * tile-push rollback <channel>
4410
+ *
4411
+ * Disables the most recent enabled bundle on a channel. The device picks
4412
+ * up the disabled flag on its next check-update and rolls back to the
4413
+ * previous enabled bundle (or INIT_ROLLBACK if none).
4414
+ */
4415
+ const registerRollback = (program) => {
4416
+ program.command("rollback").description("Disable the most recent enabled bundle on a channel").argument("<channel>", "channel to roll back").addOption(new Option("--platform <platform>", "ios | android").choices(["ios", "android"])).option("-y, --yes", "skip confirmation prompt").option("--target <bundle-id>", "scope rollback to exactly this bundle id (use to retry a failed rollback)").action(async (channel, options) => {
4417
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
4418
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
4419
+ await printTilePushHeader();
4420
+ await withOutputFilter(() => (0, hot_updater_internal_commands.handleRollback)(channel, options));
4421
+ });
4422
+ };
4423
+ //#endregion
4424
+ //#region src/commands/whoami.ts
4425
+ /**
4426
+ * tile-push whoami
4427
+ *
4428
+ * Hits GET /me on the server and prints the active tenant identity. Useful
4429
+ * for confirming the right credentials are in place before deploying.
4430
+ */
4431
+ const registerWhoami = (program) => {
4432
+ program.command("whoami").description("Show the active Tile Push tenant and token info").option("--json", "output as JSON").action(async (options) => {
4433
+ try {
4434
+ const me = await (await require_apiClient.TilePushClient.create()).get("/me");
4435
+ if (options.json) {
4436
+ console.log(JSON.stringify(me, null, 2));
4437
+ return;
4438
+ }
4439
+ console.log(`${import_picocolors.default.bold("Tenant:")} ${me.tenantName}`);
4440
+ console.log(`${import_picocolors.default.bold("App id:")} ${me.appId}`);
4441
+ console.log(`${import_picocolors.default.bold("Token: ")} ${me.tokenLabel}`);
4442
+ } catch (err) {
4443
+ if (err instanceof require_apiClient.TilePushApiError) console.error(tilePushError(err.message));
4444
+ else console.error(tilePushError(err.message));
4445
+ process.exitCode = 1;
4446
+ }
4447
+ });
4448
+ };
4449
+ //#endregion
4450
+ //#region bin/tile-push.ts
4451
+ const VERSION = "0.1.0";
4452
+ const program = new Command();
4453
+ program.name("tile-push").description("Tile Push — OTA updates for React Native").version(VERSION);
4454
+ registerInit(program);
4455
+ registerDeploy(program);
4456
+ registerBundle(program);
4457
+ registerRollback(program);
4458
+ registerChannel(program);
4459
+ registerFingerprint(program);
4460
+ registerWhoami(program);
4461
+ registerConsole(program);
4462
+ registerDoctor(program);
4463
+ registerInfo(program);
4464
+ program.parseAsync(process.argv).catch((err) => {
4465
+ console.error(err);
4466
+ process.exit(1);
4467
+ });
4468
+ //#endregion
4469
+ exports.__toESM = __toESM;