@rockcarver/frodo-cli 5.0.0-6 → 5.0.0-8

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,1856 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-Ctb5zv51.cjs");
2
+ const require_Console = require("./Console-1LBCP_JZ.cjs");
3
+ const require_EscapableSelectPrompt = require("./EscapableSelectPrompt-BljVxNDm.cjs");
4
+ const require_AuthoringPrintState = require("./AuthoringPrintState-vyWOD1Wt.cjs");
5
+ const require_EntityPickers = require("./EntityPickers-BGrRn1Yq.cjs");
6
+ const require_DefaultsStore = require("./DefaultsStore-RlEkAWqT.cjs");
7
+ const require_RealmPickers = require("./RealmPickers-IjVJiRB5.cjs");
8
+ let path = require("path");
9
+ path = require_rolldown_runtime.__toESM(path, 1);
10
+ let fs = require("fs");
11
+ fs = require_rolldown_runtime.__toESM(fs, 1);
12
+ let os = require("os");
13
+ os = require_rolldown_runtime.__toESM(os, 1);
14
+ /**
15
+ * Read a line of free-form text. Paste-safe and editable (the readline
16
+ * buffer does the editing; the prompt only reads it), unlike accumulating
17
+ * individual keypresses by hand.
18
+ */
19
+ async function promptInput(config) {
20
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
21
+ return runTextPrompt(config, { suppress: false });
22
+ }
23
+ /**
24
+ * Read a line of text without echoing it (passwords, passphrases, and
25
+ * similar secrets). Same result contract as `promptInput`.
26
+ */
27
+ async function promptPassword(config) {
28
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
29
+ return runTextPrompt(config, { suppress: true });
30
+ }
31
+ /**
32
+ * Terminal conditions outside the user's in-prompt choices: stdin EOF
33
+ * (Ctrl-D, e.g. the driver's shutdown write) and Ctrl-C both reject the
34
+ * prompt with @inquirer/core's ExitPromptError. For gap-fills both mean
35
+ * "no value supplied" and must degrade to the declined result (`''`) so
36
+ * the caller falls through to its pre-existing missing-input error --
37
+ * never a raw stack trace. (Escape is handled in-prompt, so it never
38
+ * reaches this wrapper.)
39
+ */
40
+ async function runTextPrompt(config, opts) {
41
+ require_EscapableSelectPrompt.notePromptRendered();
42
+ try {
43
+ return await textPrompt(config, opts);
44
+ } catch (error) {
45
+ if (error instanceof require_EscapableSelectPrompt.ExitPromptError) return "";
46
+ throw error;
47
+ }
48
+ }
49
+ function textPrompt(config, { suppress }) {
50
+ return require_EscapableSelectPrompt.createPrompt((cfg, done) => {
51
+ const [value, setValue] = require_EscapableSelectPrompt.useState("");
52
+ const [status, setStatus] = require_EscapableSelectPrompt.useState("idle");
53
+ const prefix = require_EscapableSelectPrompt.usePrefix({ status: status === "declined" ? "done" : status });
54
+ require_EscapableSelectPrompt.useKeypress((key, rl) => {
55
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
56
+ const line = value || rl.line || "";
57
+ if (line.length === 0 && cfg.default !== void 0) {
58
+ setValue(cfg.default);
59
+ setStatus("done");
60
+ done(cfg.default);
61
+ } else if (line.length === 0) {
62
+ setStatus("declined");
63
+ done("");
64
+ } else {
65
+ setValue(line);
66
+ setStatus("done");
67
+ done(line);
68
+ }
69
+ } else if (key.name === "escape") {
70
+ setStatus("declined");
71
+ done("");
72
+ } else setValue(rl.line);
73
+ });
74
+ const defaultHint = cfg.default !== void 0 && !suppress ? ` ${require_Console.theme.muted(`(${cfg.default})`)}` : "";
75
+ if (status === "declined") return `${prefix} ${config.message} ${require_Console.theme.muted("(no input)")}`;
76
+ if (status === "done") {
77
+ const shown = suppress ? "*".repeat(value.length) : value;
78
+ return `${prefix} ${config.message} ${require_Console.theme.positive(shown)}`;
79
+ }
80
+ const shown = suppress ? "*".repeat(value.length) : value;
81
+ return `${prefix} ${config.message}${defaultHint}${shown ? ` ${require_Console.theme.command(shown)}` : ""}`;
82
+ })(config, { clearPromptOnDone: true });
83
+ }
84
+ //#endregion
85
+ //#region src/utils/interactive/CommandPreview.ts
86
+ /**
87
+ * frodo-lib's sentinel default for "no realm chosen yet" and its
88
+ * per-deployment-type translations (the same mapping frodo-lib's
89
+ * determineDefaultRealm applies during auth). Zero-import constraint:
90
+ * the map is duplicated here rather than imported from frodo-lib --
91
+ * if the lib map ever changes, this copy MUST change with it (the test
92
+ * below pins the values).
93
+ */
94
+ const DEFAULT_REALM_KEY = "__default__realm__";
95
+ const DEPLOYMENT_TYPE_REALM_MAP = {
96
+ classic: "/",
97
+ cloud: "alpha",
98
+ forgeops: "/"
99
+ };
100
+ /**
101
+ * The deployment type the resolver knows for this process (set from the
102
+ * CLI side via setDeploymentTypeForPreview -- the resolution pass and
103
+ * profile loading may resolve it in either order relative to the first
104
+ * prompt render). Undefined = not yet known.
105
+ */
106
+ let previewDeploymentType;
107
+ /**
108
+ * Records the deployment type for sentinel translation in the preview.
109
+ * Called by the resolution pass when the deployment type is (or becomes)
110
+ * known: CLI-provided (-m/--type), connection-profile-carried, or
111
+ * persisted.
112
+ */
113
+ function setDeploymentTypeForPreview(type) {
114
+ previewDeploymentType = type;
115
+ }
116
+ /**
117
+ * Translates a positional value for serialization. The realm sentinel
118
+ * NEVER displays: with a known deployment type it becomes that type's
119
+ * default realm (alpha on cloud, / on classic/forgeops -- the SAME
120
+ * translation frodo-lib applies during auth, so the printed command is
121
+ * exactly what the run will execute; printing the TRANSLATED value is
122
+ * deliberate -- defaults can change between frodo versions, and a CI
123
+ * pipeline that copy-pasted the printed command must keep reading and
124
+ * writing the realm it was authored against, pinning the value now
125
+ * beats a silent realm change on upgrade). Before the type is known
126
+ * (e.g. the profile picker footer, where no host has been picked yet)
127
+ * the positional is OMITTED entirely -- the sentinel is an
128
+ * implementation detail no user ever typed or should ever see, and the
129
+ * live footer is a status display, not a copy-paste surface; by the
130
+ * final authoring print the type is always resolved, so the pipeline
131
+ * guarantee is unaffected.
132
+ */
133
+ function serializePositionalValue(argumentName, value) {
134
+ if (argumentName === "password") return "********";
135
+ if (argumentName === "realm" && value === DEFAULT_REALM_KEY) return (previewDeploymentType && DEPLOYMENT_TYPE_REALM_MAP[previewDeploymentType]) ?? "";
136
+ return value;
137
+ }
138
+ /** Options that are machinery, not configuration -- never serialized. */
139
+ const NON_SERIALIZABLE_OPTIONS = /* @__PURE__ */ new Set([
140
+ "help",
141
+ "help-more",
142
+ "help-all",
143
+ "version",
144
+ "prompt",
145
+ "no-prompt",
146
+ "edit",
147
+ "save-defaults"
148
+ ]);
149
+ /** Resolves a ReadinessInput to a snapshot (undefined when the provider declines). */
150
+ function resolveReadiness(input) {
151
+ return typeof input === "function" ? input() : input;
152
+ }
153
+ /**
154
+ * Serializes the command as it would be typed on the command line today
155
+ * -- every valued option as its flag (value placeholder included),
156
+ * valued positional arguments in order. Secrets (the password
157
+ * positional) are masked; values are shell-safe by inspection but NOT
158
+ * shell-quoted -- this is a preview, not an eval string.
159
+ */
160
+ function serializeCommand(command) {
161
+ const parts = [commandPath(command)];
162
+ const args = [];
163
+ command.registeredArguments.forEach((argument, index) => {
164
+ const value = command.processedArgs?.[index];
165
+ if (typeof value !== "string" || value.length === 0) return;
166
+ const serialized = serializePositionalValue(argument.name(), value);
167
+ if (serialized.length === 0) return;
168
+ args.push(serialized);
169
+ });
170
+ parts.push(...args);
171
+ for (const option of command.options) {
172
+ if (NON_SERIALIZABLE_OPTIONS.has(option.name())) continue;
173
+ const value = command.getOptionValue(option.attributeName());
174
+ if (value === void 0 || value === "" || !option.negate && value === false) continue;
175
+ if (command.getOptionValueSource(option.attributeName()) === "default") continue;
176
+ if (value === true || option.negate) parts.push(option.flags.split(/[, ]+/)[0]);
177
+ else if (Array.isArray(value)) {
178
+ const longFlag = option.flags.split(/[, ]+/).find((token) => token.startsWith("--"));
179
+ for (const entry of value) parts.push(`${longFlag ?? option.flags} ${String(entry)}`);
180
+ } else {
181
+ const longFlag = option.flags.split(/[, ]+/).find((token) => token.startsWith("--"));
182
+ parts.push(`${longFlag ?? option.flags} ${String(value)}`);
183
+ }
184
+ }
185
+ return parts.join(" ");
186
+ }
187
+ /**
188
+ * The `frodo x y z` path of the command (root name + ancestors + this).
189
+ */
190
+ function commandPath(command) {
191
+ const names = [];
192
+ for (let cursor = command; cursor; cursor = cursor.parent) names.unshift(cursor.name());
193
+ return names.join(" ");
194
+ }
195
+ /**
196
+ * Whether the command still has mandatory input to collect (red+cursive
197
+ * in the preview) or is validated and ready (green/white): a deferred
198
+ * mandatory option, an unsatisfied one-of group, or -- per the resolver's
199
+ * readiness input -- an unresolved connection. Positional values are NOT
200
+ * sniffed here: host/username/password can legitimately resolve from
201
+ * env/profile without ever landing in the command object (the resolver's
202
+ * own fallbacks), so only the resolver can say whether the connection
203
+ * level is satisfied.
204
+ */
205
+ function isCommandReady(_command, readiness) {
206
+ if (readiness.missingMandatoryOptionLabels.length > 0) return false;
207
+ if (readiness.oneOfUnsatisfied) return false;
208
+ return readiness.connectionResolved !== false;
209
+ }
210
+ /**
211
+ * The preview footer line for the prompts: colored per readiness state
212
+ * (red + cursive = still missing mandatory input; green/white = ready).
213
+ */
214
+ function renderCommandPreview(command, readiness) {
215
+ const serialized = serializeCommand(command);
216
+ if (isCommandReady(command, readiness)) return require_Console.theme.positive(serialized);
217
+ return require_Console.theme.italic(require_Console.theme.negative(serialized));
218
+ }
219
+ /**
220
+ * The default highlighted-value→option-value mapping: pass-through for
221
+ * strings (value pickers), otherwise undefined (entity objects, the
222
+ * "enter manually" sentinel -- the callback renders the committed state).
223
+ */
224
+ function defaultToValue(highlighted) {
225
+ return typeof highlighted === "string" ? highlighted : void 0;
226
+ }
227
+ /**
228
+ * LIVE preview footer (the footer shows what the
229
+ * user is INFLUENCING, not what they last committed). Returns a callback
230
+ * for a prompt's `preview` config that re-renders on every highlight
231
+ * change: the highlighted value is serialized into a SHADOW copy of the
232
+ * command's positional (the real command object is untouched -- only
233
+ * <enter> commits), so arrowing through e.g. a realm list moves the
234
+ * footer's realm token in real time. When nothing is highlighted
235
+ * (filtered to no matches) the callback falls back to the command's
236
+ * committed state.
237
+ *
238
+ * Options picks pass `undefined` as the positional name and use the
239
+ * option-name variant below instead; this helper is for positionals
240
+ * (realm, host...).
241
+ */
242
+ function livePositionalPreview(command, positionalName, readiness) {
243
+ const index = command.registeredArguments.findIndex((argument) => argument.name() === positionalName);
244
+ return (highlighted) => {
245
+ const value = defaultToValue(highlighted);
246
+ if (index !== -1 && command.processedArgs && value) {
247
+ const committed = command.processedArgs[index];
248
+ command.processedArgs[index] = value;
249
+ try {
250
+ return renderWithCurrentReadiness(command, readiness);
251
+ } finally {
252
+ command.processedArgs[index] = committed;
253
+ }
254
+ }
255
+ return renderWithCurrentReadiness(command, readiness);
256
+ };
257
+ }
258
+ /**
259
+ * Renders the preview with readiness derived NOW: the thunk form
260
+ * re-derives after the caller's highlight shadow is in place, so the
261
+ * color answers "is the command valid as shown right now?" (user
262
+ * decision 2026-10-14). A provider that declines (no prompting)
263
+ * renders nothing.
264
+ */
265
+ function renderWithCurrentReadiness(command, readiness) {
266
+ const current = resolveReadiness(readiness);
267
+ if (!current) return "";
268
+ return renderCommandPreview(command, current);
269
+ }
270
+ /**
271
+ * LIVE preview for an entity/option/value picker: the highlighted
272
+ * choice's value (after `toValue`) is serialized into a SHADOW copy of
273
+ * the named OPTION (source 'cli', the same source the real apply uses)
274
+ * for this render only. Restoring writes the previous value+source back
275
+ * verbatim: for a never-set option that is (undefined, undefined), which
276
+ * is exactly commander's pristine state (getOptionValue -> undefined,
277
+ * serializer skips it). `toValue` maps the highlighted choice to the
278
+ * option's value form -- identity for value pickers, the entity's label
279
+ * for entity pickers (whose choice values are the raw entities, exactly
280
+ * what the real apply writes); a mapping to undefined/empty renders the
281
+ * committed state.
282
+ */
283
+ function liveOptionPreview(command, optionName, readiness, toValue = defaultToValue) {
284
+ return (highlighted) => {
285
+ const value = toValue(highlighted);
286
+ if (value === true || value && value.length > 0) {
287
+ const committed = command.getOptionValue(optionName);
288
+ const committedSource = command.getOptionValueSource(optionName);
289
+ command.setOptionValueWithSource(optionName, value, "cli");
290
+ try {
291
+ return renderWithCurrentReadiness(command, readiness);
292
+ } finally {
293
+ command.setOptionValueWithSource(optionName, committed, committedSource);
294
+ }
295
+ }
296
+ return renderWithCurrentReadiness(command, readiness);
297
+ };
298
+ }
299
+ /**
300
+ * LIVE preview for the invocation editor (a MULTI-select): the callback
301
+ * receives the currently SELECTED attribute names (the space-toggled
302
+ * set), and the footer renders each as its flag -- booleans commit `true`
303
+ * on the editor's pick, valued options still need their value step, so
304
+ * they serialize as the flag with the value placeholder the user is
305
+ * about to fill ("--type <type>"). The real command object is never
306
+ * written here: every shadow is applied for THIS render and restored in
307
+ * the finally. An empty selection renders the committed state.
308
+ */
309
+ function liveMultiOptionPreview(command, readiness) {
310
+ return (selectedAttributeNames) => {
311
+ if (!Array.isArray(selectedAttributeNames)) return renderWithCurrentReadiness(command, readiness);
312
+ const shadows = [];
313
+ for (const attributeName of selectedAttributeNames) {
314
+ if (typeof attributeName !== "string") continue;
315
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
316
+ if (!option) continue;
317
+ const boolean = !/<[^>]+>|\[[^\]]+\]/.test(option.flags);
318
+ const committed = command.getOptionValue(attributeName);
319
+ const committedSource = command.getOptionValueSource(attributeName);
320
+ const hasUserValue = committedSource === "cli" && committed !== void 0 && (!Array.isArray(committed) || committed.length > 0);
321
+ shadows.push({
322
+ optionName: attributeName,
323
+ committed,
324
+ committedSource
325
+ });
326
+ if (!boolean && hasUserValue) continue;
327
+ const placeholder = option.flags.split(/[, ]+/).filter((token) => /^[<[].*>?\]?$/.test(token)).join(" ") || "value";
328
+ command.setOptionValueWithSource(attributeName, boolean ? true : placeholder, "cli");
329
+ }
330
+ try {
331
+ return renderWithCurrentReadiness(command, readiness);
332
+ } finally {
333
+ for (const shadow of shadows.reverse()) command.setOptionValueWithSource(shadow.optionName, shadow.committed, shadow.committedSource);
334
+ }
335
+ };
336
+ }
337
+ //#endregion
338
+ //#region src/utils/interactive/ConnectionPagePrompt.ts
339
+ /**
340
+ * Resolved by `connectionPage` when the user presses Escape on the page
341
+ * (not inside a row editor): "don't touch connection args". The caller
342
+ * falls back to its pre-existing behavior (today: the sequential
343
+ * prompts; for an already-resolved visit, just conclude).
344
+ */
345
+ const PAGE_ESCAPE = Symbol("connectionPage:escape");
346
+ /** The masked rendering of a password row's stored value. */
347
+ const PASSWORD_MASK = "••••••••";
348
+ const connectionPageImpl = require_EscapableSelectPrompt.createPrompt((config, done) => {
349
+ const [rows, setRows] = require_EscapableSelectPrompt.useState(config.rows);
350
+ const doneIndex = config.rows.length;
351
+ const [active, setActive] = require_EscapableSelectPrompt.useState(0);
352
+ const [status, setStatus] = require_EscapableSelectPrompt.useState("idle");
353
+ const [editing, setEditing] = require_EscapableSelectPrompt.useState(null);
354
+ const [draft, setDraft] = require_EscapableSelectPrompt.useState("");
355
+ const [resolving, setResolving] = require_EscapableSelectPrompt.useState(false);
356
+ const prefix = require_EscapableSelectPrompt.usePrefix({ status: status === "escaped" ? "done" : status });
357
+ const draftRef = require_EscapableSelectPrompt.useRef("");
358
+ const escapeGraceRef = require_EscapableSelectPrompt.useRef(void 0);
359
+ const [escapeGraceOpen, setEscapeGraceOpen] = require_EscapableSelectPrompt.useState(false);
360
+ const resolvingRef = require_EscapableSelectPrompt.useRef(false);
361
+ require_EscapableSelectPrompt.useEffect(() => () => escapeGraceRef.current?.dispose(), []);
362
+ require_EscapableSelectPrompt.useEffect(() => {
363
+ draftRef.current = draft;
364
+ }, [draft]);
365
+ const commitRow = async (key, value) => {
366
+ setEditing(null);
367
+ setDraft("");
368
+ if (key === "host" && config.onHostChange) {
369
+ setResolving(true);
370
+ resolvingRef.current = true;
371
+ try {
372
+ const updated = await config.onHostChange(value);
373
+ setRows(updated);
374
+ } catch {}
375
+ setResolving(false);
376
+ resolvingRef.current = false;
377
+ } else setRows((previous) => previous.map((row) => row.key === key ? {
378
+ ...row,
379
+ value
380
+ } : row));
381
+ };
382
+ const conclude = () => {
383
+ setStatus("done");
384
+ const result = {};
385
+ for (const row of rows) result[row.key] = row.value;
386
+ done(result);
387
+ };
388
+ require_EscapableSelectPrompt.useKeypress((key, rl) => {
389
+ if (resolvingRef.current) return;
390
+ if (editing !== null) {
391
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
392
+ escapeGraceRef.current?.otherKey();
393
+ escapeGraceRef.current = void 0;
394
+ const line = draft || rl.line || "";
395
+ if (editing === "password" && line.length === 0) commitRow(editing, rows.find((r) => r.key === "password")?.value ?? "");
396
+ else commitRow(editing, line);
397
+ } else if (key.name === "escape") {
398
+ if (escapeGraceRef.current) {
399
+ const grace = escapeGraceRef.current;
400
+ escapeGraceRef.current = void 0;
401
+ grace.secondEscape();
402
+ return;
403
+ }
404
+ setEscapeGraceOpen(true);
405
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
406
+ onSecondEscape: () => {
407
+ setEditing(null);
408
+ setDraft("");
409
+ setStatus("escaped");
410
+ done(require_EscapableSelectPrompt.EXIT_ALL);
411
+ },
412
+ onGraceExpire: () => {
413
+ setEscapeGraceOpen(false);
414
+ setEditing(null);
415
+ setDraft("");
416
+ rl.clearLine(0);
417
+ }
418
+ });
419
+ return;
420
+ } else {
421
+ escapeGraceRef.current?.otherKey();
422
+ escapeGraceRef.current = void 0;
423
+ setDraft(rl.line);
424
+ }
425
+ return;
426
+ }
427
+ if (key.name === "escape") {
428
+ if (escapeGraceRef.current) {
429
+ const grace = escapeGraceRef.current;
430
+ escapeGraceRef.current = void 0;
431
+ grace.secondEscape();
432
+ return;
433
+ }
434
+ setEscapeGraceOpen(true);
435
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
436
+ onSecondEscape: () => {
437
+ setEscapeGraceOpen(false);
438
+ setStatus("escaped");
439
+ done(require_EscapableSelectPrompt.EXIT_ALL);
440
+ },
441
+ onGraceExpire: () => {
442
+ setEscapeGraceOpen(false);
443
+ setStatus("escaped");
444
+ done(PAGE_ESCAPE);
445
+ }
446
+ });
447
+ return;
448
+ } else if (require_EscapableSelectPrompt.isEnterKey(key)) {
449
+ escapeGraceRef.current?.otherKey();
450
+ escapeGraceRef.current = void 0;
451
+ if (active === doneIndex) conclude();
452
+ else {
453
+ const row = rows[active];
454
+ setEditing(row.key);
455
+ setDraft("");
456
+ rl.clearLine(0);
457
+ }
458
+ } else if (require_EscapableSelectPrompt.isUpKey(key) || require_EscapableSelectPrompt.isDownKey(key)) {
459
+ escapeGraceRef.current?.otherKey();
460
+ escapeGraceRef.current = void 0;
461
+ const offset = require_EscapableSelectPrompt.isUpKey(key) ? -1 : 1;
462
+ setActive(active + offset < 0 ? doneIndex : (active + offset) % (doneIndex + 1));
463
+ }
464
+ });
465
+ const renderValue = (row, isEditing) => {
466
+ if (isEditing) return row.key === "password" ? "•".repeat(draft.length) : draft;
467
+ if (row.value === void 0 || row.value === "") return require_Console.theme.muted("(not set)");
468
+ return row.key === "password" ? require_Console.theme.muted(PASSWORD_MASK) : row.value;
469
+ };
470
+ if (status === "escaped") return `${prefix} ${config.message} ${require_Console.theme.muted("(cancelled)")}`;
471
+ if (status === "done") return `${prefix} ${config.message} ${require_Console.theme.positive("saved for this invocation")}`;
472
+ const resolvingNote = resolving ? require_Console.theme.muted(" (re-resolving credentials...)") : "";
473
+ const menu = require_EscapableSelectPrompt.renderNavigationMenu(require_EscapableSelectPrompt.navigationMenuItems({
474
+ enter: "edit / done",
475
+ escape: "cancel page"
476
+ }));
477
+ const rowLines = [...rows.map((row, index) => {
478
+ const isEditing = editing === row.key;
479
+ const cursor = isEditing ? "›" : index === active ? "›" : " ";
480
+ const note = !isEditing && row.note ? require_Console.theme.muted(` (${row.note})`) : "";
481
+ const line = `${cursor} ${row.label}: ${renderValue(row, isEditing)}${note}`;
482
+ return {
483
+ text: index === active || isEditing ? require_Console.theme.command(line) : line,
484
+ plain: `${cursor} ${row.label}: ${require_EscapableSelectPrompt.stripAnsi(renderValue(row, isEditing))}${row.note && !isEditing ? ` (${row.note})` : ""}`
485
+ };
486
+ }), (() => {
487
+ const line = `${active === doneIndex ? "›" : " "} Done — run with these values`;
488
+ return {
489
+ text: require_Console.theme.command(line),
490
+ plain: line
491
+ };
492
+ })()];
493
+ if (escapeGraceOpen) rowLines.push({
494
+ text: require_Console.theme.muted("esc again to exit all -- or wait to cancel the page"),
495
+ plain: "esc again to exit all -- or wait to cancel the page"
496
+ });
497
+ return [
498
+ menu,
499
+ require_EscapableSelectPrompt.renderFramedBox({
500
+ title: {
501
+ text: `${prefix} ${config.message}${resolvingNote}`,
502
+ plain: `? ${config.message}${resolvingNote}`
503
+ },
504
+ lines: rowLines
505
+ }),
506
+ config.preview
507
+ ].filter(Boolean).join("\n");
508
+ });
509
+ const connectionPage = ((config) => {
510
+ require_EscapableSelectPrompt.notePromptRendered();
511
+ return connectionPageImpl(config, { clearPromptOnDone: true });
512
+ });
513
+ //#endregion
514
+ //#region src/utils/interactive/ChoiceSections.ts
515
+ /**
516
+ * Builds the rows the prompt renders. With a query: the flat
517
+ * case-insensitive name matches across ALL choices, no headers,
518
+ * unindented (the pre-grouping behavior -- nothing hides from
519
+ * type-to-find). Without: own choices, then per group (config order)
520
+ * its header, and its choices -- indented -- only while expanded.
521
+ * Empty groups never render.
522
+ *
523
+ * `groups` omitted/empty keeps the exact pre-grouping behavior for
524
+ * every caller that has not adopted sections (choice `group` ids are
525
+ * then ignored): one flat list.
526
+ */
527
+ function buildSectionRows(options) {
528
+ const { choices, selected } = options;
529
+ const query = options.query ?? "";
530
+ if (query.length > 0) {
531
+ const needle = query.toLowerCase();
532
+ return choices.filter((choice) => choice.name.toLowerCase().includes(needle)).map((choice) => ({
533
+ kind: "choice",
534
+ choice,
535
+ indent: false
536
+ }));
537
+ }
538
+ const groups = options.groups ?? [];
539
+ if (groups.length === 0) return choices.map((choice) => ({
540
+ kind: "choice",
541
+ choice,
542
+ indent: false
543
+ }));
544
+ const known = new Set(groups.map((group) => group.id));
545
+ const extra = [...new Set(choices.map((choice) => choice.group).filter((group) => group !== void 0 && !known.has(group)))].sort((a, b) => a.localeCompare(b));
546
+ const ordered = [...groups, ...extra.map((id) => ({
547
+ id,
548
+ label: id
549
+ }))];
550
+ const byGroup = /* @__PURE__ */ new Map();
551
+ const own = [];
552
+ for (const choice of choices) if (choice.group === void 0) own.push(choice);
553
+ else {
554
+ const bucket = byGroup.get(choice.group);
555
+ if (bucket) bucket.push(choice);
556
+ else byGroup.set(choice.group, [choice]);
557
+ }
558
+ const rows = own.map((choice) => ({
559
+ kind: "choice",
560
+ choice,
561
+ indent: false
562
+ }));
563
+ for (const group of ordered) {
564
+ const members = byGroup.get(group.id);
565
+ if (!members || members.length === 0) continue;
566
+ const expanded = options.expanded.has(group.id);
567
+ rows.push({
568
+ kind: "header",
569
+ group,
570
+ count: members.length,
571
+ selectedCount: selected ? members.filter((choice) => selected.has(choice.value)).length : 0,
572
+ expanded
573
+ });
574
+ if (expanded) for (const choice of members) rows.push({
575
+ kind: "choice",
576
+ choice,
577
+ indent: true
578
+ });
579
+ }
580
+ return rows;
581
+ }
582
+ /**
583
+ * The groups that start EXPANDED: every group holding a choice the
584
+ * user has already set (the editor's `defaultValues` -- CLI/env/saved
585
+ * default/previous commit). State must never hide behind a collapsed
586
+ * header; own options need no expansion.
587
+ */
588
+ function initialExpanded(groups, choices, defaultValues) {
589
+ const valued = new Set(defaultValues);
590
+ const expanded = /* @__PURE__ */ new Set();
591
+ for (const choice of choices) if (choice.group !== void 0 && valued.has(choice.value)) expanded.add(choice.group);
592
+ const known = new Set(groups.map((group) => group.id));
593
+ return new Set([...expanded].filter((id) => known.has(id)));
594
+ }
595
+ /** The row index of the choice with this value (-1 when absent). */
596
+ function rowIndexOf(rows, value) {
597
+ return rows.findIndex((row) => row.kind === "choice" && row.choice.value === value);
598
+ }
599
+ //#endregion
600
+ //#region src/utils/interactive/EscapableMultiSelectPrompt.ts
601
+ /**
602
+ * Distinct return value `escapableMultiSelect` resolves with when the user
603
+ * presses Escape instead of committing -- callers branch on this to back
604
+ * out (skip the editor entirely) instead of treating it as a real
605
+ * selection. Nothing selected + Enter commits the empty set (a deliberate
606
+ * "run with defaults"), distinct from Escape's "don't touch this step".
607
+ * The ← key (query empty) is an alias for Escape -- the "return
608
+ * to the segment that invoked this editor" key; with text typed it stays
609
+ * readline cursor movement.
610
+ */
611
+ const MULTISEL_ESCAPE = Symbol("escapableMultiSelect:escape");
612
+ const escapableMultiSelectImpl = require_EscapableSelectPrompt.createPrompt((config, done) => {
613
+ const { pageSize = 20, choices } = config;
614
+ const [status, setStatus] = require_EscapableSelectPrompt.useState("idle");
615
+ const prefix = require_EscapableSelectPrompt.usePrefix({ status: status === "escaped" ? "done" : status });
616
+ const [query, setQuery] = require_EscapableSelectPrompt.useState("");
617
+ const [expandedState, setExpandedState] = require_EscapableSelectPrompt.useState(() => (config.groups?.length ?? 0) > 0 ? initialExpanded(config.groups ?? [], choices, config.defaultValues ?? []) : /* @__PURE__ */ new Set());
618
+ const [selected, setSelected] = require_EscapableSelectPrompt.useState(() => new Set(config.defaultValues ?? []));
619
+ const [editing, setEditing] = require_EscapableSelectPrompt.useState(null);
620
+ const [editingChoices, setEditingChoices] = require_EscapableSelectPrompt.useState([]);
621
+ const [draft, setDraft] = require_EscapableSelectPrompt.useState("");
622
+ const [pickerActive, setPickerActive] = require_EscapableSelectPrompt.useState(0);
623
+ const rows = require_EscapableSelectPrompt.useMemo(() => buildSectionRows({
624
+ choices,
625
+ groups: config.groups,
626
+ expanded: expandedState,
627
+ query,
628
+ selected
629
+ }), [
630
+ choices,
631
+ config.groups,
632
+ query,
633
+ selected,
634
+ expandedState
635
+ ]);
636
+ const lastQueryRef = require_EscapableSelectPrompt.useRef(query);
637
+ require_EscapableSelectPrompt.useEffect(() => {
638
+ if (lastQueryRef.current === query) return;
639
+ lastQueryRef.current = query;
640
+ setActive(0);
641
+ }, [query]);
642
+ const expandedRef2 = expandedState;
643
+ const [active, setActive] = require_EscapableSelectPrompt.useState(0);
644
+ const highlighted = rows[active];
645
+ const highlightedChoice = highlighted?.kind === "choice" ? highlighted.choice : void 0;
646
+ const escapeGraceRef = require_EscapableSelectPrompt.useRef(void 0);
647
+ const [escapeGraceOpen, setEscapeGraceOpen] = require_EscapableSelectPrompt.useState(false);
648
+ const [leftGuard, setLeftGuard] = require_EscapableSelectPrompt.useState("");
649
+ require_EscapableSelectPrompt.useEffect(() => () => escapeGraceRef.current?.dispose(), []);
650
+ const closeInlineEditor = (rl, returnTo) => {
651
+ setEditing(null);
652
+ setEditingChoices([]);
653
+ setDraft("");
654
+ setPickerActive(0);
655
+ lastQueryRef.current = "";
656
+ setQuery("");
657
+ if (returnTo !== void 0) {
658
+ const groupId = choices.find((choice) => choice.value === returnTo)?.group;
659
+ if (groupId !== void 0 && !expandedRef2.has(groupId)) setExpandedState((previous) => {
660
+ const next = new Set(previous);
661
+ next.add(groupId);
662
+ return next;
663
+ });
664
+ const index = rowIndexOf(buildSectionRows({
665
+ choices,
666
+ groups: config.groups,
667
+ expanded: groupId !== void 0 && !expandedRef2.has(groupId) ? /* @__PURE__ */ new Set([...expandedRef2, groupId]) : expandedRef2,
668
+ query: "",
669
+ selected
670
+ }), returnTo);
671
+ if (index >= 0) setActive(index);
672
+ }
673
+ rl.write(null, {
674
+ ctrl: true,
675
+ name: "u"
676
+ });
677
+ rl.clearLine(0);
678
+ };
679
+ require_EscapableSelectPrompt.useKeypress((key, rl) => {
680
+ if (editing !== null) {
681
+ if (editingChoices.length > 0) {
682
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
683
+ escapeGraceRef.current?.otherKey();
684
+ escapeGraceRef.current = void 0;
685
+ const value = editingChoices[pickerActive] ?? editingChoices[0];
686
+ config.onValue?.(editing, value);
687
+ setSelected((previous) => {
688
+ const next = new Set(previous);
689
+ next.add(editing);
690
+ return next;
691
+ });
692
+ closeInlineEditor(rl, editing);
693
+ return;
694
+ }
695
+ if (key.name === "escape") {
696
+ if (escapeGraceRef.current) {
697
+ const grace = escapeGraceRef.current;
698
+ escapeGraceRef.current = void 0;
699
+ grace.secondEscape();
700
+ return;
701
+ }
702
+ setEscapeGraceOpen(true);
703
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
704
+ onSecondEscape: () => {
705
+ closeInlineEditor(rl, editing);
706
+ setStatus("escaped");
707
+ done(require_EscapableSelectPrompt.EXIT_ALL);
708
+ },
709
+ onGraceExpire: () => {
710
+ setEscapeGraceOpen(false);
711
+ closeInlineEditor(rl, editing);
712
+ }
713
+ });
714
+ return;
715
+ }
716
+ if (require_EscapableSelectPrompt.isUpKey(key) || require_EscapableSelectPrompt.isDownKey(key)) {
717
+ escapeGraceRef.current?.otherKey();
718
+ escapeGraceRef.current = void 0;
719
+ const offset = require_EscapableSelectPrompt.isUpKey(key) ? -1 : 1;
720
+ setPickerActive((previous) => Math.min(editingChoices.length - 1, Math.max(0, previous + offset)));
721
+ return;
722
+ }
723
+ return;
724
+ }
725
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
726
+ escapeGraceRef.current?.otherKey();
727
+ escapeGraceRef.current = void 0;
728
+ const line = draft || rl.line || "";
729
+ if (line.trim().length === 0) return;
730
+ config.onValue?.(editing, line);
731
+ setSelected((previous) => {
732
+ const next = new Set(previous);
733
+ next.add(editing);
734
+ return next;
735
+ });
736
+ closeInlineEditor(rl, editing);
737
+ return;
738
+ }
739
+ if (key.name === "escape") {
740
+ if (escapeGraceRef.current) {
741
+ const grace = escapeGraceRef.current;
742
+ escapeGraceRef.current = void 0;
743
+ grace.secondEscape();
744
+ return;
745
+ }
746
+ setEscapeGraceOpen(true);
747
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
748
+ onSecondEscape: () => {
749
+ closeInlineEditor(rl, editing);
750
+ setStatus("escaped");
751
+ done(require_EscapableSelectPrompt.EXIT_ALL);
752
+ },
753
+ onGraceExpire: () => {
754
+ setEscapeGraceOpen(false);
755
+ closeInlineEditor(rl, editing);
756
+ }
757
+ });
758
+ return;
759
+ }
760
+ escapeGraceRef.current?.otherKey();
761
+ escapeGraceRef.current = void 0;
762
+ setDraft(rl.line);
763
+ return;
764
+ }
765
+ if (key.name === "escape" || key.name === "left" && rl.line.length === 0) {
766
+ if (rl.line.length > 0) {
767
+ rl.clearLine(0);
768
+ setQuery("");
769
+ escapeGraceRef.current?.otherKey();
770
+ escapeGraceRef.current = void 0;
771
+ return;
772
+ }
773
+ const uncommitted = [...selected].filter((value) => !config.defaultValues?.includes(value));
774
+ if (uncommitted.length > 0) {
775
+ if (key.name === "left") {
776
+ setLeftGuard(`select or reset first -- ${uncommitted.length} option${uncommitted.length === 1 ? "" : "s"} not committed ([ESC] resets, [ENTER] commits)`);
777
+ return;
778
+ }
779
+ const resetThenResolve = () => {
780
+ setSelected((previous) => {
781
+ const next = new Set(previous);
782
+ for (const value of uncommitted) next.delete(value);
783
+ return next;
784
+ });
785
+ setStatus("escaped");
786
+ done(MULTISEL_ESCAPE);
787
+ };
788
+ if (escapeGraceRef.current) {
789
+ const grace = escapeGraceRef.current;
790
+ escapeGraceRef.current = void 0;
791
+ grace.secondEscape();
792
+ return;
793
+ }
794
+ setEscapeGraceOpen(true);
795
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
796
+ onSecondEscape: () => {
797
+ setEscapeGraceOpen(false);
798
+ setStatus("escaped");
799
+ done(require_EscapableSelectPrompt.EXIT_ALL);
800
+ },
801
+ onGraceExpire: resetThenResolve
802
+ });
803
+ return;
804
+ }
805
+ if (key.name === "escape") {
806
+ if (escapeGraceRef.current) {
807
+ const grace = escapeGraceRef.current;
808
+ escapeGraceRef.current = void 0;
809
+ grace.secondEscape();
810
+ return;
811
+ }
812
+ setEscapeGraceOpen(true);
813
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
814
+ onSecondEscape: () => {
815
+ setEscapeGraceOpen(false);
816
+ setStatus("escaped");
817
+ done(require_EscapableSelectPrompt.EXIT_ALL);
818
+ },
819
+ onGraceExpire: () => {
820
+ setEscapeGraceOpen(false);
821
+ setStatus("escaped");
822
+ done(MULTISEL_ESCAPE);
823
+ }
824
+ });
825
+ return;
826
+ }
827
+ escapeGraceRef.current?.otherKey();
828
+ escapeGraceRef.current = void 0;
829
+ setStatus("escaped");
830
+ done(MULTISEL_ESCAPE);
831
+ } else if (require_EscapableSelectPrompt.isEnterKey(key)) {
832
+ escapeGraceRef.current?.otherKey();
833
+ escapeGraceRef.current = void 0;
834
+ setLeftGuard("");
835
+ setStatus("done");
836
+ done([...selected]);
837
+ } else if (require_EscapableSelectPrompt.isSpaceKey(key)) {
838
+ escapeGraceRef.current?.otherKey();
839
+ escapeGraceRef.current = void 0;
840
+ setLeftGuard("");
841
+ if (!highlighted) return;
842
+ rl.write(null, {
843
+ ctrl: true,
844
+ name: "u"
845
+ });
846
+ rl.clearLine(0);
847
+ if (highlighted.kind === "header") {
848
+ const id = highlighted.group.id;
849
+ setExpandedState((previous) => {
850
+ const next = new Set(previous);
851
+ if (next.has(id)) next.delete(id);
852
+ else next.add(id);
853
+ return next;
854
+ });
855
+ return;
856
+ }
857
+ if (!selected.has(highlighted.choice.value)) {
858
+ const groupId = highlighted.choice.group;
859
+ if (groupId !== void 0 && !expandedRef2.has(groupId)) setExpandedState((previous) => {
860
+ const next = new Set(previous);
861
+ next.add(groupId);
862
+ return next;
863
+ });
864
+ }
865
+ if (!selected.has(highlighted.choice.value) && config.needsValue?.(highlighted.choice.value)) {
866
+ const choicesFor = config.choicesFor?.(highlighted.choice.value) ?? void 0;
867
+ const current = config.currentValueFor?.(highlighted.choice.value) ?? "";
868
+ setEditing(highlighted.choice.value);
869
+ setEditingChoices(choicesFor ?? []);
870
+ setPickerActive(choicesFor ? Math.max(0, choicesFor.indexOf(current)) : 0);
871
+ setDraft(current);
872
+ rl.write(null, {
873
+ ctrl: true,
874
+ name: "u"
875
+ });
876
+ rl.clearLine(0);
877
+ return;
878
+ }
879
+ setSelected((previous) => {
880
+ const next = new Set(previous);
881
+ if (next.has(highlighted.choice.value)) next.delete(highlighted.choice.value);
882
+ else next.add(highlighted.choice.value);
883
+ return next;
884
+ });
885
+ } else if (require_EscapableSelectPrompt.isUpKey(key) || require_EscapableSelectPrompt.isDownKey(key)) {
886
+ escapeGraceRef.current?.otherKey();
887
+ escapeGraceRef.current = void 0;
888
+ setLeftGuard("");
889
+ if (rows.length === 0) return;
890
+ const offset = require_EscapableSelectPrompt.isUpKey(key) ? -1 : 1;
891
+ setActive((previous) => Math.min(rows.length - 1, Math.max(0, previous + offset)));
892
+ } else {
893
+ escapeGraceRef.current?.otherKey();
894
+ escapeGraceRef.current = void 0;
895
+ setLeftGuard("");
896
+ setQuery(rl.line);
897
+ }
898
+ });
899
+ if (status === "escaped") return `${prefix} ${config.message} ${require_Console.theme.muted("(cancelled)")}`;
900
+ if (status === "done") {
901
+ const picked = choices.filter((choice) => selected.has(choice.value));
902
+ const summary = picked.length === 0 ? require_Console.theme.muted("(none -- run with defaults)") : require_Console.theme.positive(picked.map((choice) => choice.name).join(", "));
903
+ return `${prefix} ${config.message} ${summary}`;
904
+ }
905
+ const page = require_EscapableSelectPrompt.usePagination({
906
+ items: rows,
907
+ active,
908
+ renderItem: ({ item, isActive }) => {
909
+ if (item.kind === "header") {
910
+ const twisty = item.expanded ? "▾" : "▸";
911
+ const badge = !item.expanded && item.selectedCount > 0 ? ` · ${item.selectedCount} selected` : "";
912
+ const line = `${twisty} ${item.group.label} (${item.count})${badge}`;
913
+ return isActive ? require_Console.theme.command(line) : line;
914
+ }
915
+ const line = `${selected.has(item.choice.value) ? "◉" : "○"} ${isActive ? "› " : " "}${item.indent ? " " : ""}${item.choice.name}`;
916
+ return isActive ? require_Console.theme.command(line) : line;
917
+ },
918
+ pageSize,
919
+ loop: false
920
+ });
921
+ const queryEcho = query.length > 0 ? require_Console.theme.command(` query: ${query}`) : "";
922
+ const editingName = editing !== null ? choices.find((choice) => choice.value === editing)?.name ?? String(editing) : "";
923
+ const menu = require_EscapableSelectPrompt.renderNavigationMenu(require_EscapableSelectPrompt.navigationMenuItems(editing !== null ? {
924
+ enter: editingChoices.length > 0 ? "pick" : "commit value",
925
+ escape: "rejects"
926
+ } : {
927
+ filter: true,
928
+ space: highlighted?.kind === "header" ? highlighted.expanded ? "collapse" : "expand" : "select",
929
+ enter: "commit",
930
+ left: true,
931
+ escape: "back · [ESC]×2 exit all"
932
+ }));
933
+ const panelLines = [];
934
+ if (leftGuard) panelLines.push({
935
+ text: require_Console.theme.negative(leftGuard),
936
+ plain: leftGuard
937
+ });
938
+ else if (escapeGraceOpen) panelLines.push({
939
+ text: require_Console.theme.muted("esc again to exit all -- or wait to go back one level"),
940
+ plain: "esc again to exit all -- or wait to go back one level"
941
+ });
942
+ if (rows.length > 0) for (const row of page.split("\n")) panelLines.push({
943
+ text: row,
944
+ plain: require_EscapableSelectPrompt.stripAnsi(row)
945
+ });
946
+ else panelLines.push({
947
+ text: require_Console.theme.muted("(no matches -- backspace to edit)"),
948
+ plain: "(no matches -- backspace to edit)"
949
+ });
950
+ if (highlighted?.kind === "header") {
951
+ const members = choices.filter((choice) => choice.group === highlighted.group.id);
952
+ panelLines.push({
953
+ text: "",
954
+ plain: ""
955
+ });
956
+ panelLines.push(...require_EscapableSelectPrompt.descriptionPanelLines(`${highlighted.group.label}: ${members.map((choice) => choice.name).join(", ")}`));
957
+ } else if (highlightedChoice?.description) {
958
+ panelLines.push({
959
+ text: "",
960
+ plain: ""
961
+ });
962
+ panelLines.push(...require_EscapableSelectPrompt.descriptionPanelLines(highlightedChoice.description));
963
+ }
964
+ const panel = require_EscapableSelectPrompt.renderFramedBox({
965
+ title: {
966
+ text: `${prefix} ${config.message}${queryEcho}`,
967
+ plain: `? ${config.message}${queryEcho}`
968
+ },
969
+ lines: panelLines
970
+ });
971
+ const valueBox = editing === null ? "" : editingChoices.length > 0 ? require_EscapableSelectPrompt.renderFramedBox({
972
+ title: `Value for ${editingName}`,
973
+ lines: editingChoices.map((choice, index) => {
974
+ const line = `${index === pickerActive ? "›" : " "} ${choice}`;
975
+ return {
976
+ text: index === pickerActive ? require_Console.theme.command(line) : line,
977
+ plain: line
978
+ };
979
+ })
980
+ }) : require_EscapableSelectPrompt.renderFramedBox({
981
+ title: `Value for ${editingName}`,
982
+ lines: [{
983
+ text: require_Console.theme.command(draft || "(type a value)"),
984
+ plain: draft || "(type a value)"
985
+ }]
986
+ });
987
+ return [
988
+ menu,
989
+ panel,
990
+ ...editing !== null ? [valueBox] : [],
991
+ typeof config.preview === "function" ? config.preview(choices.filter((choice) => selected.has(choice.value)).map((choice) => choice.value)) : config.preview
992
+ ].filter(Boolean).join("\n");
993
+ });
994
+ const escapableMultiSelect = ((config) => {
995
+ require_EscapableSelectPrompt.notePromptRendered();
996
+ return escapableMultiSelectImpl(config, { clearPromptOnDone: true });
997
+ });
998
+ //#endregion
999
+ //#region src/utils/interactive/PositionalArgs.ts
1000
+ /**
1001
+ * Index of the default positional argument of that name on this command
1002
+ * (commands omit default args via the FrodoCommand omits list, so the
1003
+ * index differs per command), or -1 when the command doesn't declare it.
1004
+ */
1005
+ function positionalIndex(command, name) {
1006
+ return command.registeredArguments.findIndex((argument) => argument.name() === name);
1007
+ }
1008
+ function positionalValue(command, name) {
1009
+ const index = positionalIndex(command, name);
1010
+ if (index === -1) return void 0;
1011
+ const value = command.processedArgs?.[index];
1012
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1013
+ }
1014
+ /**
1015
+ * Writes `value` into BOTH surfaces the CLI reads for a positional:
1016
+ *
1017
+ * - `processedArgs` is what the action handler's positional parameters
1018
+ * are sliced from (commander's action() wrapper slices
1019
+ * this.processedArgs).
1020
+ * - `args` (raw, options-removed user args) is what
1021
+ * handleDefaultArgsAndOpts iterates to copy default arguments into
1022
+ * frodo-lib state INSIDE the action body -- it does NOT read
1023
+ * processedArgs, so a processedArgs-only injection would be
1024
+ * overwritten with `undefined` the moment the action starts.
1025
+ * Verified against commander's _processArguments (fills processedArgs
1026
+ * from args, never writes back) and this repo's
1027
+ * handleDefaultArgsAndOpts (iterates command.args).
1028
+ *
1029
+ * `args` holds only user-supplied positional values; a gap-fill by
1030
+ * definition fills a position the user left empty, so extending/padding
1031
+ * with the injected value is safe. Pad with nulls for any inner
1032
+ * positions the user skipped (rare: inner default args are optional),
1033
+ * since args is positional.
1034
+ */
1035
+ function setPositionalValue(command, name, value) {
1036
+ const index = positionalIndex(command, name);
1037
+ if (index === -1) return;
1038
+ if (command.processedArgs) command.processedArgs[index] = value;
1039
+ if (Array.isArray(command.args)) {
1040
+ while (command.args.length < index) command.args.push(null);
1041
+ if (index === command.args.length) command.args.push(value);
1042
+ else if (command.args[index] == null) command.args[index] = value;
1043
+ }
1044
+ }
1045
+ //#endregion
1046
+ //#region src/utils/SettingsStore.ts
1047
+ const SETTINGS_FILENAME = "Settings.json";
1048
+ function getSettingsPath() {
1049
+ return path.default.join(os.default.homedir(), ".frodo", SETTINGS_FILENAME);
1050
+ }
1051
+ function readSettings() {
1052
+ try {
1053
+ const parsed = JSON.parse(fs.default.readFileSync(getSettingsPath(), "utf8"));
1054
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
1055
+ } catch {
1056
+ return {};
1057
+ }
1058
+ }
1059
+ function writeSettings(settings) {
1060
+ const file = getSettingsPath();
1061
+ fs.default.mkdirSync(path.default.dirname(file), { recursive: true });
1062
+ fs.default.writeFileSync(file, JSON.stringify(settings, null, 2));
1063
+ }
1064
+ /**
1065
+ * Whether the invocation editor should run by default on this invocation:
1066
+ * the persisted guided-mode toggle, with --no-prompt / FRODO_NO_PROMPT /
1067
+ * FRODO_TEST still gating everything downstream (the editor itself runs
1068
+ * behind canPrompt, so those environments ignore guided mode exactly as
1069
+ * they ignore --edit).
1070
+ */
1071
+ function guidedModeEnabled() {
1072
+ return readSettings().guidedMode === true;
1073
+ }
1074
+ function setGuidedMode(enabled) {
1075
+ const settings = readSettings();
1076
+ settings.guidedMode = enabled;
1077
+ writeSettings(settings);
1078
+ }
1079
+ //#endregion
1080
+ //#region src/cli/ResolveInteractiveInputs.ts
1081
+ /**
1082
+ * The "zero-touch" resolution pass: fills missing command input
1083
+ * interactively before the action body runs (see
1084
+ * docs/INTERACTIVE-COMMANDS.md). Wired from FrodoCommand's preAction
1085
+ * hook; never modifies frodo-lib.
1086
+ *
1087
+ * Two resolver kinds run here, connection arguments first (the host gives
1088
+ * the later prompts their context), then deferred mandatory options:
1089
+ *
1090
+ * 1. Connection arguments. Missing `host` (dropdown of saved connection
1091
+ * profiles, single profile silently assumed, free-text entry when none
1092
+ * exist -- see runInteractivePreferredCredentialPicker for the
1093
+ * precedent), missing `username`/`password` -- but ONLY when no saved
1094
+ * profile can supply credentials for the resolved host, since frodo-lib
1095
+ * already falls back to profile-stored credentials on its own
1096
+ * (AuthenticateOps loadConnectionProfile); prompting when a profile
1097
+ * would answer anyway would be pure friction. `--browser`/`--device`
1098
+ * likewise suppress the username/password prompts (their flow is the
1099
+ * interactive part) but not the host prompt, which those flows still
1100
+ * need.
1101
+ *
1102
+ * 2. Deferred mandatory options. Commander's
1103
+ * `missingMandatoryOptionValue()` normally throws during parsing --
1104
+ * BEFORE the preAction hook chain runs. FrodoCommand overrides it to
1105
+ * record the violation instead, which makes all 57 existing
1106
+ * `makeOptionMandatory()` call sites prompt-capable with zero syntax
1107
+ * change. Options carrying commander `choices()` are offered as a
1108
+ * dropdown instead of free typing.
1109
+ *
1110
+ * Everything here is gap-filling, and every gap-fill writes into the
1111
+ * command's own `processedArgs`/option values -- NOT into frodo-lib state
1112
+ * -- because `handleDefaultArgsAndOpts` (which copies positional args into
1113
+ * state) runs INSIDE the action body, after this pass; writing state here
1114
+ * would be overwritten by `undefined` a moment later. A fully-specified
1115
+ * invocation reaches the action untouched, and outside the prompt gate
1116
+ * (see PromptGate) the pass degrades to exactly the old error behavior.
1117
+ */
1118
+ var ResolveInteractiveInputs_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
1119
+ MISSING_MANDATORY_OPTION_CODE: () => MISSING_MANDATORY_OPTION_CODE,
1120
+ ONE_OF_UNSATISFIED_CODE: () => ONE_OF_UNSATISFIED_CODE,
1121
+ commandPreviewFor: () => commandPreviewFor,
1122
+ commandReadinessFor: () => commandReadinessFor,
1123
+ deferMissingMandatoryOption: () => deferMissingMandatoryOption,
1124
+ deferOneOfGroups: () => deferOneOfGroups,
1125
+ getOneOfGroups: () => getOneOfGroups,
1126
+ liveOptionPreviewFor: () => liveOptionPreviewFor,
1127
+ livePositionalPreviewFor: () => livePositionalPreviewFor,
1128
+ resolveInteractiveInputs: () => resolveInteractiveInputs,
1129
+ runInvocationEditorForCommand: () => runInvocationEditorForCommand,
1130
+ setPositionalValueForCommand: () => setPositionalValue
1131
+ });
1132
+ const { getConnectionProfilesPath, getConnectionProfileByHost } = require_Console.frodo.conn;
1133
+ const { probeDeploymentType } = require_Console.frodo.login;
1134
+ const { isValidUrl } = require_Console.frodo.utils;
1135
+ /**
1136
+ * A mandatory-option violation that commander's parse recorded instead of
1137
+ * throwing on. Lives here rather than on the command instance so the
1138
+ * deferred state survives the parse->hook handoff regardless of how
1139
+ * commander clones or nests commands.
1140
+ */
1141
+ const pendingMandatoryViolations = /* @__PURE__ */ new WeakMap();
1142
+ /**
1143
+ * Whether the connection level (host/username/password) resolved for this
1144
+ * command this session -- set by resolveConnectionArgs, whether the values
1145
+ * came from argv, env fallbacks, saved profiles, or the prompts. The
1146
+ * preview's readiness keys on THIS, not on the positionals: env/profile
1147
+ * resolution leaves the command object's positionals empty while the
1148
+ * connection is fully resolved. Lives beside pendingMandatoryViolations
1149
+ * for the same parse->hook handoff reasons.
1150
+ */
1151
+ const connectionReadiness = /* @__PURE__ */ new WeakMap();
1152
+ const pendingOneOfGroups = /* @__PURE__ */ new WeakMap();
1153
+ /**
1154
+ * Registers option-requiredness groups on a command for resolution-pass
1155
+ * evaluation. Called from FrodoCommand.requireOneOf/requireAllOf.
1156
+ */
1157
+ function deferOneOfGroups(command, groups) {
1158
+ pendingOneOfGroups.set(command, [...pendingOneOfGroups.get(command) ?? [], ...groups]);
1159
+ }
1160
+ /**
1161
+ * The option-requiredness groups registered on a command (empty when
1162
+ * none). Read by FrodoStubHelp to render the rule in help output -- the
1163
+ * help annotation and the resolver consume the same metadata.
1164
+ */
1165
+ function getOneOfGroups(command) {
1166
+ return pendingOneOfGroups.get(command) ?? [];
1167
+ }
1168
+ /**
1169
+ * Records a mandatory option that was missing at parse time, instead of
1170
+ * throwing. Called from FrodoCommand's `missingMandatoryOptionValue`
1171
+ * override. `optionLabel` is the option's full flags string (e.g.
1172
+ * `-s, --schema <schema>`), matching what commander's own error message
1173
+ * embeds.
1174
+ */
1175
+ function deferMissingMandatoryOption(command, optionLabel) {
1176
+ const pending = pendingMandatoryViolations.get(command) ?? [];
1177
+ pending.push(optionLabel);
1178
+ pendingMandatoryViolations.set(command, pending);
1179
+ }
1180
+ /**
1181
+ * The CommanderError code commander itself uses for this failure; the
1182
+ * re-throw preserves it so scripts can match on it.
1183
+ */
1184
+ const MISSING_MANDATORY_OPTION_CODE = "commander.missingMandatoryOptionValue";
1185
+ /**
1186
+ * Rebuilds commander's exact error message for a deferred violation (see
1187
+ * missingMandatoryOptionValue in commander's lib/command.js).
1188
+ */
1189
+ function missingMandatoryOptionMessage(optionLabel) {
1190
+ return `error: required option '${optionLabel}' not specified`;
1191
+ }
1192
+ /**
1193
+ * Runs the interactive resolution pass for `command` (the leaf command
1194
+ * about to execute).
1195
+ *
1196
+ * When prompting is disallowed, any deferred mandatory violation is
1197
+ * re-thrown with commander's own message/code (identical to pre-Phase-1
1198
+ * behavior -- commander would have thrown during parsing) and everything
1199
+ * else is a no-op. When the user backs out of a prompt (Escape/empty
1200
+ * Enter), any deferred violations are re-thrown the same way (matching
1201
+ * the old parse order, where the mandatory check ran first) and missing
1202
+ * connection args are left for the action's getTokens() to fail on
1203
+ * exactly as before.
1204
+ */
1205
+ async function resolveInteractiveInputs(command) {
1206
+ const violations = pendingMandatoryViolations.get(command) ?? [];
1207
+ if (!require_EscapableSelectPrompt.canPrompt()) {
1208
+ if (violations.length > 0) throwMissingMandatory(command, violations[0]);
1209
+ const unsatisfiedGroups = findUnsatisfiedOneOfGroups(command);
1210
+ if (unsatisfiedGroups.length > 0) throwOneOfUnsatisfied(command, unsatisfiedGroups[0]);
1211
+ return;
1212
+ }
1213
+ applyPersistedDefaults(command);
1214
+ require_RealmPickers.noteRealmProvenance();
1215
+ setDeploymentTypeForPreview(require_Console.state.getDeploymentType());
1216
+ const explicitlyInteractive = command.getOptionValue("prompt") === true && command.getOptionValueSource("prompt") === "cli" || guidedModeEnabled();
1217
+ connectionReadiness.set(command, false);
1218
+ const connectionResolved = await resolveConnectionArgs(command);
1219
+ connectionReadiness.set(command, connectionResolved);
1220
+ const mandatoryResolved = connectionResolved ? await resolveMandatoryOptions(command) : false;
1221
+ if (!connectionResolved || !mandatoryResolved) {
1222
+ if (violations.length > 0) throwMissingMandatory(command, violations[0]);
1223
+ return;
1224
+ }
1225
+ if (!await resolveOneOfGroups(command)) {
1226
+ const unsatisfied = findUnsatisfiedOneOfGroups(command);
1227
+ if (unsatisfied.length > 0) throwOneOfUnsatisfied(command, unsatisfied[0]);
1228
+ }
1229
+ if (explicitlyInteractive) await runInvocationEditor(command);
1230
+ require_AuthoringPrintState.armAuthoringPrint();
1231
+ require_AuthoringPrintState.setAuthoringPrintFlush(() => {
1232
+ if (require_EscapableSelectPrompt.promptsRendered() === 0 && !explicitlyInteractive) return;
1233
+ require_Console.printMessage(renderCommandPreview(command, {
1234
+ missingMandatoryOptionLabels: [],
1235
+ oneOfUnsatisfied: false
1236
+ }), "text");
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Emits commander's exact mandatory-option failure: same message, same
1241
+ * CommanderError code, same stderr output and exit path as pre-Phase-1.
1242
+ */
1243
+ function throwMissingMandatory(command, optionLabel) {
1244
+ command.error(missingMandatoryOptionMessage(optionLabel), { code: MISSING_MANDATORY_OPTION_CODE });
1245
+ }
1246
+ /**
1247
+ * Commander-style failure for an unsatisfied one-of group. The message
1248
+ * mirrors commander's own error shape (message + help + exit 1), which is
1249
+ * also the UX the replaced `Unrecognized combination` else-branches had
1250
+ * (they printed, showed help, and exited 1).
1251
+ */
1252
+ function throwOneOfUnsatisfied(command, group) {
1253
+ const members = group.options.map((name) => {
1254
+ const option = command.options.find((candidate) => candidate.attributeName() === name);
1255
+ return option ? option.flags : `--${name}`;
1256
+ }).join(group.all ? " + " : " | ");
1257
+ command.error(`error: ${group.all ? `all of '${members}' are required` : `one of '${members}' is required`}${group.purpose ? ` to choose ${group.purpose}` : ""}`, { code: ONE_OF_UNSATISFIED_CODE });
1258
+ }
1259
+ /**
1260
+ * The CommanderError code for an unsatisfied one-of group. Namespaced like
1261
+ * commander's own codes (`commander.missingArgument`,
1262
+ * `commander.missingMandatoryOptionValue`) so scripts can match on it, but
1263
+ * distinct from any commander code since this rule is frodo-specific.
1264
+ */
1265
+ const ONE_OF_UNSATISFIED_CODE = "frodo.oneOfUnsatisfied";
1266
+ /**
1267
+ * The `→` routing for pickers inside the resolution pass: runs
1268
+ * `escapableSelect` with the command's discoverability hint attached,
1269
+ * and when the user presses → (resolve `RIGHT`), opens the invocation
1270
+ * editor, then re-prompts -- so a user who landed in a mandatory/one-of/
1271
+ * profile picker can discover and edit everything else from there (the
1272
+ * segment navigation described in docs/INTERACTIVE-COMMANDS.md). Without
1273
+ * a hint (nothing to configure) this is exactly `escapableSelect`: the
1274
+ * → key stays readline's business and the loop never engages.
1275
+ *
1276
+ * Re-prompting after the editor keeps the picker's own contract intact
1277
+ * (the caller sees a plain value or ESCAPE); the editor's ←/Esc re-enter
1278
+ * this loop, where the user can still decline with Escape.
1279
+ */
1280
+ async function selectWithEditorRouting(command, config) {
1281
+ const hint = require_EscapableSelectPrompt.editableOptionsHint(command);
1282
+ const preview = config.preview ?? (() => commandPreviewFor(command) ?? "");
1283
+ for (;;) {
1284
+ const choice = await require_EscapableSelectPrompt.escapableSelect({
1285
+ ...config,
1286
+ hint,
1287
+ preview
1288
+ });
1289
+ if (choice === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1290
+ if (choice === require_EscapableSelectPrompt.ESCAPE) return require_EscapableSelectPrompt.ESCAPE;
1291
+ if (choice !== require_EscapableSelectPrompt.RIGHT) return choice;
1292
+ await runInvocationEditor(command);
1293
+ }
1294
+ }
1295
+ /**
1296
+ * The command preview footer for `command`'s prompts: the
1297
+ * command-so-far, red + cursive while mandatory input is missing, green/
1298
+ * white when validated and ready. Readiness derives from this module's
1299
+ * registries (deferred mandatory violations, one-of groups, connection
1300
+ * resolution); undefined when prompting is disallowed (the preview is an
1301
+ * interactive affordance only).
1302
+ */
1303
+ function commandPreviewFor(command) {
1304
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
1305
+ const readiness = commandReadinessFor(command);
1306
+ return readiness ? renderCommandPreview(command, readiness) : void 0;
1307
+ }
1308
+ /**
1309
+ * The resolver's current readiness input for `command` (the data behind
1310
+ * commandPreviewFor's render), for callers building LIVE preview
1311
+ * callbacks (livePositionalPreview/liveOptionPreview need the readiness
1312
+ * at every re-render, not a one-shot string). Undefined when prompting
1313
+ * is disallowed -- same gate as commandPreviewFor.
1314
+ */
1315
+ function commandReadinessFor(command) {
1316
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
1317
+ const missingMandatoryOptionLabels = (pendingMandatoryViolations.get(command) ?? []).filter((label) => {
1318
+ const option = command.options.find((candidate) => candidate.flags === label);
1319
+ if (!option) return true;
1320
+ const value = command.getOptionValue(option.attributeName());
1321
+ return value === void 0 || value === false || value === "";
1322
+ });
1323
+ const oneOfUnsatisfied = findUnsatisfiedOneOfGroups(command).length > 0;
1324
+ const connectionResolved = connectionReadiness.get(command);
1325
+ return {
1326
+ missingMandatoryOptionLabels,
1327
+ oneOfUnsatisfied,
1328
+ ...connectionResolved !== void 0 ? { connectionResolved } : {}
1329
+ };
1330
+ }
1331
+ /**
1332
+ * LIVE preview callbacks for `command`'s pickers (the footer shows what
1333
+ * the user is INFLUENCING -- arrowing through a list re-renders the
1334
+ * command with the highlighted value shadowed in). Built fresh per
1335
+ * picker open; the readiness THUNK re-derives per render (footer color
1336
+ * answers "valid as shown right now" -- user decision 2026-10-14: a
1337
+ * highlighted value that completes the command reads green before any
1338
+ * commit), so the callbacks stay valid across the picker's renders even
1339
+ * as mandatory/one-of state moves. Undefined when prompting is
1340
+ * disallowed -- same gate as commandPreviewFor.
1341
+ */
1342
+ function livePositionalPreviewFor(command, positionalName) {
1343
+ if (!commandReadinessFor(command)) return void 0;
1344
+ return livePositionalPreview(command, positionalName, () => commandReadinessFor(command));
1345
+ }
1346
+ function liveOptionPreviewFor(command, optionName, toValue) {
1347
+ if (!commandReadinessFor(command)) return void 0;
1348
+ return liveOptionPreview(command, optionName, () => commandReadinessFor(command), toValue);
1349
+ }
1350
+ /**
1351
+ * Prompts for a value from a closed choice set. A ONE-item set auto-commits
1352
+ * (a single choice is no choice; commander would accept only that value
1353
+ * anyway -- the plan's single-option refinement); otherwise a searchable
1354
+ * dropdown. Returns ESCAPE only from the interactive picker, so a
1355
+ * single-choice set can never decline. With `optionName`, the picker's
1356
+ * footer is LIVE: arrowing through the values re-renders the command with
1357
+ * the highlighted value shadowed into that option.
1358
+ */
1359
+ async function selectFromChoices(command, message, choices, optionName) {
1360
+ if (choices.length === 1) {
1361
+ require_Console.verboseMessage(`Only one value available: ${choices[0]}`);
1362
+ return choices[0];
1363
+ }
1364
+ return selectWithEditorRouting(command, {
1365
+ message,
1366
+ ...optionName ? { preview: liveOptionPreviewFor(command, optionName) } : {},
1367
+ choices: choices.map((choiceValue) => ({
1368
+ name: choiceValue,
1369
+ value: choiceValue
1370
+ }))
1371
+ });
1372
+ }
1373
+ /**
1374
+ * Prompts for each deferred mandatory option violation. Options with a
1375
+ * closed value set (commander `choices()`) get a dropdown; everything
1376
+ * else free text. Returns false as soon as the user declines one (Escape
1377
+ * or empty Enter) -- the caller then restores the old error semantics.
1378
+ */
1379
+ async function resolveMandatoryOptions(command) {
1380
+ const violations = pendingMandatoryViolations.get(command) ?? [];
1381
+ for (const violation of violations) {
1382
+ const option = command.options.find((candidate) => {
1383
+ return candidate.flags === violation;
1384
+ });
1385
+ if (!option) throwMissingMandatory(command, violation);
1386
+ const attributeName = option.attributeName();
1387
+ if (require_EntityPickers.hasEntityPick(command, attributeName)) {
1388
+ require_Console.verboseMessage(`${option.flags} will be offered from the target system after login.`);
1389
+ continue;
1390
+ }
1391
+ let value;
1392
+ if (option.argChoices && option.argChoices.length > 0) {
1393
+ const choice = await selectFromChoices(command, `Choose a value for ${option.flags}:`, option.argChoices, option.attributeName());
1394
+ if (choice === require_EscapableSelectPrompt.ESCAPE) return false;
1395
+ value = choice;
1396
+ } else {
1397
+ const answer = await promptInput({ message: `Enter a value for ${option.flags}:` });
1398
+ if (!answer) return false;
1399
+ value = answer;
1400
+ }
1401
+ command.setOptionValueWithSource(attributeName, value, "cli");
1402
+ require_Console.verboseMessage(`Using ${value} for ${option.flags}.`);
1403
+ }
1404
+ return true;
1405
+ }
1406
+ /**
1407
+ * Whether an option-requiredness group is satisfied by the current option
1408
+ * values: every member for requireAllOf groups, at least one for
1409
+ * requireOneOf groups. Values are read via getOptionValue so injected
1410
+ * gap-fills count.
1411
+ */
1412
+ function groupSatisfied(command, group) {
1413
+ const defined = (name) => {
1414
+ const value = command.getOptionValue(name);
1415
+ return value !== void 0 && value !== false && value !== "";
1416
+ };
1417
+ return group.all ? group.options.every(defined) : group.options.some(defined);
1418
+ }
1419
+ /**
1420
+ * All registered option-requiredness groups the current invocation does
1421
+ * not satisfy.
1422
+ */
1423
+ function findUnsatisfiedOneOfGroups(command) {
1424
+ return (pendingOneOfGroups.get(command) ?? []).filter((group) => !groupSatisfied(command, group));
1425
+ }
1426
+ /**
1427
+ * Interactive resolution of unsatisfied one-of groups: the user picks WHICH
1428
+ * member to supply (dropdown over the group's members, defaulting to the
1429
+ * first), then a value step matched to the member's type -- dropdown for
1430
+ * commander `choices()`, free text otherwise (booleans resolve by the pick
1431
+ * itself). Mirrors resolveMandatoryOptions' decline semantics: Escape or
1432
+ * empty Enter returns false and the caller restores the error.
1433
+ */
1434
+ async function resolveOneOfGroups(command) {
1435
+ const unsatisfied = findUnsatisfiedOneOfGroups(command);
1436
+ for (const group of unsatisfied) {
1437
+ const memberOptions = group.options.map((name) => {
1438
+ const option = command.options.find((candidate) => candidate.attributeName() === name);
1439
+ return option ? {
1440
+ name,
1441
+ option
1442
+ } : void 0;
1443
+ }).filter((member) => member !== void 0);
1444
+ if (memberOptions.length === 0) continue;
1445
+ const picked = await selectWithEditorRouting(command, {
1446
+ message: `Choose ${group.purpose ?? "what to act on"}:`,
1447
+ ...commandReadinessFor(command) ? { preview: (highlighted) => {
1448
+ const member = memberOptions.find((candidate) => candidate.name === highlighted);
1449
+ const readiness = commandReadinessFor(command);
1450
+ if (!member || !readiness) return readiness ? renderCommandPreview(command, readiness) : "";
1451
+ const isBoolean = !/<[^>]+>|\[[^\]]+\]/.test(member.option.flags);
1452
+ return liveOptionPreview(command, member.name, () => commandReadinessFor(command), isBoolean ? () => true : () => void 0)(highlighted);
1453
+ } } : {},
1454
+ choices: memberOptions.map((member) => ({
1455
+ value: member.name,
1456
+ name: `${member.option.flags}${member.option.description ? ` -- ${member.option.description}` : ""}`
1457
+ }))
1458
+ });
1459
+ if (picked === require_EscapableSelectPrompt.ESCAPE) return false;
1460
+ const chosen = memberOptions.find((member) => member.name === picked);
1461
+ if (require_EntityPickers.hasEntityPick(command, chosen.name)) {
1462
+ require_Console.verboseMessage(`${chosen.option.flags} will be offered from the target system after login.`);
1463
+ continue;
1464
+ }
1465
+ if (chosen.option.argChoices && chosen.option.argChoices.length > 0) {
1466
+ const value = await selectFromChoices(command, `Choose a value for ${chosen.option.flags}:`, chosen.option.argChoices, chosen.name);
1467
+ if (value === require_EscapableSelectPrompt.ESCAPE) return false;
1468
+ command.setOptionValueWithSource(chosen.name, value, "cli");
1469
+ } else if (!/<[^>]+>|\[[^\]]+\]/.test(chosen.option.flags)) command.setOptionValueWithSource(chosen.name, true, "cli");
1470
+ else {
1471
+ const answer = await promptInput({ message: `Enter a value for ${chosen.option.flags}:` });
1472
+ if (!answer) return false;
1473
+ command.setOptionValueWithSource(chosen.name, answer, "cli");
1474
+ }
1475
+ require_Console.verboseMessage(`Using ${chosen.option.flags}.`);
1476
+ }
1477
+ return true;
1478
+ }
1479
+ /**
1480
+ * Whether the invocation carries an explicit interactive-auth mode
1481
+ * (--browser/--device). Read from the parsed option values, NOT from
1482
+ * frodo-lib state: `handleDefaultArgsAndOpts` sets authMode from these
1483
+ * same options inside the action body, i.e. after this pass runs.
1484
+ */
1485
+ function isInteractiveAuthMode(command) {
1486
+ return !!command.getOptionValue("browser") || !!command.getOptionValue("device");
1487
+ }
1488
+ /**
1489
+ * Reads the saved connection profiles file directly (no auth, no network)
1490
+ * to enumerate candidates for the host dropdown. Returns a sorted list;
1491
+ * empty when the file is missing or unreadable.
1492
+ */
1493
+ function listSavedProfiles() {
1494
+ const filename = getConnectionProfilesPath();
1495
+ let connectionsData;
1496
+ try {
1497
+ connectionsData = JSON.parse(fs.default.readFileSync(filename, "utf8"));
1498
+ } catch {
1499
+ return [];
1500
+ }
1501
+ return Object.keys(connectionsData).sort().map((host) => ({
1502
+ host,
1503
+ alias: connectionsData[host].alias
1504
+ }));
1505
+ }
1506
+ const ENTER_MANUALLY = Symbol("resolveConnectionArgs:enterManually");
1507
+ /**
1508
+ * Prompts for the missing connection-level positional arguments: host,
1509
+ * then username/password -- the latter only when no saved profile can
1510
+ * supply credentials for the resolved host. Returns false when the user
1511
+ * declines a prompt (Escape or empty Enter); the caller then restores the
1512
+ * pre-Phase-1 error semantics.
1513
+ *
1514
+ * Skipped per-argument when: the command doesn't declare the argument,
1515
+ * the value is already present (positional arg, or env var via frodo-lib
1516
+ * state's own env fallback), or --browser/--device makes the
1517
+ * username/password prompts redundant.
1518
+ */
1519
+ async function resolveConnectionArgs(command) {
1520
+ if (positionalIndex(command, "host") !== -1 && !positionalValue(command, "host") && !require_Console.state.getHost()) {
1521
+ const profiles = listSavedProfiles();
1522
+ let picked;
1523
+ if (profiles.length === 1) {
1524
+ picked = profiles[0].host;
1525
+ require_Console.verboseMessage(`No host given; using the only saved connection profile: ${picked}`);
1526
+ } else if (profiles.length > 1) {
1527
+ const readiness = commandReadinessFor(command);
1528
+ const choice = await selectWithEditorRouting(command, {
1529
+ message: "Choose a connection profile:",
1530
+ ...readiness ? { preview: livePositionalPreview(command, "host", readiness) } : {},
1531
+ search: ({ value, name }, query) => {
1532
+ const needle = query.toLowerCase();
1533
+ if (value === ENTER_MANUALLY) return name.length === 0;
1534
+ return value.toLowerCase().includes(needle) || (profiles.find((p) => p.host === value)?.alias ?? "").toLowerCase().includes(needle);
1535
+ },
1536
+ choices: [{
1537
+ value: ENTER_MANUALLY,
1538
+ name: "Enter a host manually...",
1539
+ description: "Type an AM base URL (or a profile substring)."
1540
+ }, ...profiles.map((profile) => ({
1541
+ value: profile.host,
1542
+ name: profile.alias ? `${profile.host} (${profile.alias})` : profile.host
1543
+ }))]
1544
+ });
1545
+ if (choice === require_EscapableSelectPrompt.ESCAPE) return false;
1546
+ if (choice === ENTER_MANUALLY) {
1547
+ const answer = await promptInput({ message: "AM base URL (or profile alias/substring):" });
1548
+ if (!answer) return false;
1549
+ picked = answer;
1550
+ } else picked = choice;
1551
+ } else {
1552
+ const answer = await promptInput({ message: "AM base URL:" });
1553
+ if (!answer) return false;
1554
+ picked = answer;
1555
+ }
1556
+ setPositionalValue(command, "host", picked);
1557
+ }
1558
+ {
1559
+ const host = positionalValue(command, "host") ?? require_Console.state.getHost();
1560
+ if (!require_Console.state.getDeploymentType() && host) try {
1561
+ setDeploymentTypeForPreview((await getConnectionProfileByHost(host)).deploymentType);
1562
+ } catch {
1563
+ if (require_EscapableSelectPrompt.canPrompt() && isValidUrl(host)) try {
1564
+ const probe = await probeDeploymentType(host);
1565
+ require_Console.state.setDeploymentType(probe.deploymentType);
1566
+ setDeploymentTypeForPreview(probe.deploymentType);
1567
+ } catch {}
1568
+ }
1569
+ }
1570
+ const usernameNeeded = positionalIndex(command, "username") !== -1 && !positionalValue(command, "username") && !require_Console.state.getUsername() && !isInteractiveAuthMode(command);
1571
+ const passwordNeeded = positionalIndex(command, "password") !== -1 && !positionalValue(command, "password") && !require_Console.state.getPassword() && !isInteractiveAuthMode(command);
1572
+ if (!usernameNeeded && !passwordNeeded) return true;
1573
+ const host = positionalValue(command, "host") ?? require_Console.state.getHost();
1574
+ if (!host) return true;
1575
+ let savedUsername;
1576
+ let profileNote;
1577
+ try {
1578
+ const profile = await getConnectionProfileByHost(host);
1579
+ if (profile.username && profile.password || profile.svcacctId || profile.amsterPrivateKey) return true;
1580
+ savedUsername = profile.username ?? void 0;
1581
+ profileNote = profile.alias ? `from profile ${profile.alias}` : "from profile";
1582
+ } catch {}
1583
+ const result = await connectionPage({
1584
+ message: "Connection:",
1585
+ preview: commandPreviewFor(command),
1586
+ rows: [
1587
+ {
1588
+ key: "host",
1589
+ label: "host",
1590
+ value: host,
1591
+ note: profileNote ?? void 0
1592
+ },
1593
+ {
1594
+ key: "username",
1595
+ label: "username",
1596
+ value: positionalValue(command, "username") ?? require_Console.state.getUsername(),
1597
+ note: require_Console.state.getUsername() ? "from FRODO_USERNAME" : profileNote ?? void 0
1598
+ },
1599
+ {
1600
+ key: "password",
1601
+ label: "password",
1602
+ value: positionalValue(command, "password") ?? require_Console.state.getPassword(),
1603
+ note: require_Console.state.getPassword() ? "from FRODO_PASSWORD" : profileNote ?? void 0
1604
+ }
1605
+ ],
1606
+ onHostChange: async (newHost) => {
1607
+ setPositionalValue(command, "host", newHost);
1608
+ let note;
1609
+ let savedUser;
1610
+ try {
1611
+ const profile = await getConnectionProfileByHost(newHost);
1612
+ note = profile.alias ? `from profile ${profile.alias}` : "from profile";
1613
+ savedUser = profile.username ?? void 0;
1614
+ } catch {
1615
+ note = void 0;
1616
+ }
1617
+ return [
1618
+ {
1619
+ key: "host",
1620
+ label: "host",
1621
+ value: newHost,
1622
+ note
1623
+ },
1624
+ {
1625
+ key: "username",
1626
+ label: "username",
1627
+ value: positionalValue(command, "username") ?? savedUser,
1628
+ note
1629
+ },
1630
+ {
1631
+ key: "password",
1632
+ label: "password",
1633
+ value: void 0,
1634
+ note
1635
+ }
1636
+ ];
1637
+ }
1638
+ });
1639
+ if (result === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1640
+ if (result === PAGE_ESCAPE) {
1641
+ if (usernameNeeded) {
1642
+ const answer = await promptInput({
1643
+ message: "Username:",
1644
+ default: savedUsername
1645
+ });
1646
+ if (!answer) return false;
1647
+ setPositionalValue(command, "username", answer);
1648
+ }
1649
+ if (passwordNeeded) {
1650
+ const answer = await promptPassword({ message: "Password:" });
1651
+ if (!answer) return false;
1652
+ setPositionalValue(command, "password", answer);
1653
+ }
1654
+ return true;
1655
+ }
1656
+ if (result.username) setPositionalValue(command, "username", result.username);
1657
+ if (result.password) setPositionalValue(command, "password", result.password);
1658
+ return true;
1659
+ }
1660
+ /**
1661
+ * Public entry for utils/interactive picker modules (EntityPickers,
1662
+ * RealmPickers): their `→` key opens this editor, then re-prompts. Kept
1663
+ * as a named export because those modules import this file lazily (the
1664
+ * cycle is otherwise static: this file imports their registries).
1665
+ */
1666
+ async function runInvocationEditorForCommand(command) {
1667
+ await runInvocationEditor(command);
1668
+ }
1669
+ /**
1670
+ * Applies the command's persisted defaults (~/.frodo/
1671
+ * Defaults.json) to every option the user did NOT provide this
1672
+ * invocation (flag or env -- the precedence gate is
1673
+ * optionMissingUserValue: source undefined or 'default'). Values land
1674
+ * with source 'cli': persisted defaults are user-authored
1675
+ * configuration, and everything downstream (editor display, preview
1676
+ * footer, the eventual-command serializer) must treat them as real
1677
+ * input. Interactive only -- non-interactive runs keep byte-identical
1678
+ * behavior (built-in defaults).
1679
+ */
1680
+ function applyPersistedDefaults(command) {
1681
+ if (!require_EscapableSelectPrompt.canPrompt()) return;
1682
+ const persisted = require_DefaultsStore.applicableCommandDefaults(command);
1683
+ for (const option of command.options) {
1684
+ const value = persisted[option.attributeName()];
1685
+ if (value === void 0) continue;
1686
+ if (!require_DefaultsStore.optionMissingUserValue(command, option)) continue;
1687
+ const collectsArrays = Array.isArray(command.getOptionValue(option.attributeName())) || Array.isArray(option.defaultValue);
1688
+ if (Array.isArray(value) !== collectsArrays) continue;
1689
+ command.setOptionValueWithSource(option.attributeName(), value, "cli");
1690
+ require_Console.verboseMessage(`Using saved default ${option.flags} ${String(value)} (frodo settings defaults to change).`);
1691
+ }
1692
+ }
1693
+ async function runInvocationEditor(command) {
1694
+ const candidates = require_EscapableSelectPrompt.editableOptionalOptions(command);
1695
+ if (candidates.length === 0) {
1696
+ require_Console.verboseMessage("No optional options left to edit.");
1697
+ return;
1698
+ }
1699
+ const preselected = candidates.filter((option) => command.getOptionValueSource(option.attributeName()) === "cli").map((option) => option.attributeName());
1700
+ const runValueStep = async (attributeName) => {
1701
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1702
+ if (!option) return void 0;
1703
+ const current = command.getOptionValue(attributeName);
1704
+ const currentText = current === void 0 || current === false ? void 0 : String(current);
1705
+ if (option.argChoices && option.argChoices.length > 0) {
1706
+ const value = await require_EscapableSelectPrompt.escapableSelect({
1707
+ message: `Choose a value for ${option.flags}:`,
1708
+ preview: liveOptionPreviewFor(command, attributeName),
1709
+ choices: option.argChoices.map((choiceValue) => ({
1710
+ name: choiceValue,
1711
+ value: choiceValue
1712
+ })),
1713
+ default: currentText
1714
+ });
1715
+ if (value === require_EscapableSelectPrompt.EXIT_ALL) return require_EscapableSelectPrompt.EXIT_ALL;
1716
+ if (value === require_EscapableSelectPrompt.ESCAPE || value === require_EscapableSelectPrompt.RIGHT) return void 0;
1717
+ command.setOptionValueWithSource(attributeName, value, "cli");
1718
+ return value;
1719
+ }
1720
+ if (!/<[^>]+>|\[[^\]]+\]/.test(option.flags)) {
1721
+ command.setOptionValueWithSource(attributeName, true, "cli");
1722
+ return true;
1723
+ }
1724
+ const answer = await promptInput({
1725
+ message: `Enter a value for ${option.flags}:`,
1726
+ default: currentText
1727
+ });
1728
+ if (!answer) return void 0;
1729
+ command.setOptionValueWithSource(attributeName, answer, "cli");
1730
+ return answer;
1731
+ };
1732
+ const committed = {};
1733
+ const picked = await escapableMultiSelect({
1734
+ message: `Optional options for '${command.name()}' (space to select):`,
1735
+ defaultValues: preselected,
1736
+ preview: (() => {
1737
+ if (!commandReadinessFor(command)) return void 0;
1738
+ return liveMultiOptionPreview(command, () => commandReadinessFor(command));
1739
+ })(),
1740
+ needsValue: (attributeName) => {
1741
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1742
+ return !!option && /<[^>]+>|\[[^\]]+\]/.test(option.flags);
1743
+ },
1744
+ choicesFor: (attributeName) => {
1745
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1746
+ return option?.argChoices && option.argChoices.length > 0 ? option.argChoices.map(String) : void 0;
1747
+ },
1748
+ currentValueFor: (attributeName) => {
1749
+ if (!command.options.find((candidate) => candidate.attributeName() === attributeName)) return void 0;
1750
+ const current = command.getOptionValue(attributeName);
1751
+ if (current === void 0 || current === false || Array.isArray(current)) return void 0;
1752
+ return String(current);
1753
+ },
1754
+ onValue: (attributeName, value) => {
1755
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1756
+ if (!option) return;
1757
+ if (Array.isArray(option.defaultValue)) {
1758
+ const existing = command.getOptionValue(attributeName);
1759
+ command.setOptionValueWithSource(attributeName, [...Array.isArray(existing) ? existing : [], value], "cli");
1760
+ } else command.setOptionValueWithSource(attributeName, value, "cli");
1761
+ committed[attributeName] = command.getOptionValue(attributeName);
1762
+ require_Console.verboseMessage(`Using ${option.flags} ${value}.`);
1763
+ },
1764
+ groups: require_EscapableSelectPrompt.editableOptionGroups(candidates),
1765
+ choices: require_EscapableSelectPrompt.sortEditableOptions(candidates).map((option) => {
1766
+ const current = command.getOptionValue(option.attributeName());
1767
+ const sourced = current === void 0 || current === false ? void 0 : command.getOptionValueSource(option.attributeName()) === "default" ? ` (default: ${current})` : ` (current: ${current})`;
1768
+ return {
1769
+ value: option.attributeName(),
1770
+ name: option.flags,
1771
+ group: require_EscapableSelectPrompt.editableOptionGroupOf(option),
1772
+ description: option.description ? `${option.description}${sourced ?? ""}` : sourced?.trim()
1773
+ };
1774
+ })
1775
+ });
1776
+ if (picked === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1777
+ if (picked === MULTISEL_ESCAPE) {
1778
+ require_Console.verboseMessage("Invocation editor dismissed; values unchanged.");
1779
+ return;
1780
+ }
1781
+ const savingDefaults = command.getOptionValue("saveDefaults") === true && command.getOptionValueSource("saveDefaults") === "cli";
1782
+ for (const attributeName of picked) {
1783
+ if (command.getOptionValueSource(attributeName) === "cli" && command.getOptionValue(attributeName) !== void 0) {
1784
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1785
+ require_Console.verboseMessage(`Using ${option.flags}.`);
1786
+ continue;
1787
+ }
1788
+ const value = await runValueStep(attributeName);
1789
+ if (value === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1790
+ if (value === void 0) continue;
1791
+ committed[attributeName] = value;
1792
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1793
+ require_Console.verboseMessage(`Using ${option.flags}.`);
1794
+ }
1795
+ if (picked.length > 0) {
1796
+ const { replayEditorOptionStates } = await Promise.resolve().then(() => require("./FrodoCommand-DueD-n-I.cjs")).then((n) => n.FrodoCommand_exports);
1797
+ replayEditorOptionStates(command);
1798
+ }
1799
+ if (savingDefaults && Object.keys(committed).length > 0) {
1800
+ const { saveCommandDefaults } = await Promise.resolve().then(() => require("./DefaultsStore-RlEkAWqT.cjs")).then((n) => n.DefaultsStore_exports);
1801
+ saveCommandDefaults(command, committed);
1802
+ require_Console.successMessage(`Saved ${Object.keys(committed).length} option${Object.keys(committed).length === 1 ? "" : "s"} as defaults for '${commandStorePath(command)}'.`);
1803
+ }
1804
+ }
1805
+ /** The `frodo x y z` path -- the store's key (DefaultsStore's own helper,
1806
+ * re-imported lazily beside its save call). */
1807
+ function commandStorePath(command) {
1808
+ const names = [];
1809
+ for (let cursor = command; cursor; cursor = cursor.parent) names.unshift(cursor.name());
1810
+ return names.join(" ");
1811
+ }
1812
+ //#endregion
1813
+ Object.defineProperty(exports, "ResolveInteractiveInputs_exports", {
1814
+ enumerable: true,
1815
+ get: function() {
1816
+ return ResolveInteractiveInputs_exports;
1817
+ }
1818
+ });
1819
+ Object.defineProperty(exports, "deferMissingMandatoryOption", {
1820
+ enumerable: true,
1821
+ get: function() {
1822
+ return deferMissingMandatoryOption;
1823
+ }
1824
+ });
1825
+ Object.defineProperty(exports, "deferOneOfGroups", {
1826
+ enumerable: true,
1827
+ get: function() {
1828
+ return deferOneOfGroups;
1829
+ }
1830
+ });
1831
+ Object.defineProperty(exports, "getOneOfGroups", {
1832
+ enumerable: true,
1833
+ get: function() {
1834
+ return getOneOfGroups;
1835
+ }
1836
+ });
1837
+ Object.defineProperty(exports, "readSettings", {
1838
+ enumerable: true,
1839
+ get: function() {
1840
+ return readSettings;
1841
+ }
1842
+ });
1843
+ Object.defineProperty(exports, "resolveInteractiveInputs", {
1844
+ enumerable: true,
1845
+ get: function() {
1846
+ return resolveInteractiveInputs;
1847
+ }
1848
+ });
1849
+ Object.defineProperty(exports, "setGuidedMode", {
1850
+ enumerable: true,
1851
+ get: function() {
1852
+ return setGuidedMode;
1853
+ }
1854
+ });
1855
+
1856
+ //# sourceMappingURL=ResolveInteractiveInputs-D_-5704M.cjs.map