repown 0.1.0 → 0.2.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.
package/dist/ui/format.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // saying which check spoke, then the message.
3
3
  //
4
4
  // OK identity octocat <...> push-as:octocat
5
- // WARN gh active as someone else, so `gh pr create` would act as them
5
+ // NOTE gh active as someone else, so `gh pr create` would act as them
6
6
  // fix: gh auth switch -u octocat
7
7
  const COLOURS = {
8
8
  green: '\x1b[32m',
@@ -43,6 +43,10 @@ export function pass(tag, message) {
43
43
  export function warn(tag, message) {
44
44
  status({ stream: process.stderr, word: 'WARN', colour: 'yellow' }, tag, message);
45
45
  }
46
+ /** Optional advice. Same columns as warn, on stderr. Dim when that stream has colour. */
47
+ export function noted(tag, message) {
48
+ status({ stream: process.stderr, word: 'NOTE', colour: 'dim' }, tag, message);
49
+ }
46
50
  export function fail(tag, message) {
47
51
  status({ stream: process.stderr, word: 'FAIL', colour: 'red' }, tag, message);
48
52
  }
@@ -50,6 +54,10 @@ export function fail(tag, message) {
50
54
  export function detail(message) {
51
55
  process.stderr.write(' ' + message + '\n');
52
56
  }
57
+ /** Stderr with no indent. `detail`'s seven spaces would attach a closing tally to the row above. */
58
+ export function note(message) {
59
+ process.stderr.write(message + '\n');
60
+ }
53
61
  export function line(message = '') {
54
62
  process.stdout.write(message + '\n');
55
63
  }
@@ -67,6 +75,12 @@ export function heading(text) {
67
75
  export function dim(text) {
68
76
  return paint(process.stdout, 'dim', text);
69
77
  }
78
+ /** Shown to a person. Windows uses native separators; any other platform is unchanged. */
79
+ export function displayPath(path) {
80
+ if (process.platform !== 'win32')
81
+ return path;
82
+ return path.replaceAll('/', '\\');
83
+ }
70
84
  /**
71
85
  * A reader closing early (`repown help | head -3`) delivers EPIPE on the next
72
86
  * write. That is the reader's choice, not a fault in repown, so the write is
package/dist/ui/help.js CHANGED
@@ -20,7 +20,9 @@ function topHeader(entries) {
20
20
  const lines = ['', ' repown <command> [options]', ''];
21
21
  for (const [name, entry] of entries)
22
22
  lines.push(' ' + name.padEnd(10) + entry.summary);
23
- lines.push('', ' Run `repown` with no command for the state of this repository.');
23
+ lines.push('', ' Bare `repown`, in a terminal: `repown setup` in a clone that isn\'t set up, status in');
24
+ lines.push(' one that is, and this help outside a clone (exit 0). Without a terminal, or with its');
25
+ lines.push(' output redirected, it is always status (exit 1 outside a clone).');
24
26
  lines.push(' Run `repown help <command>` for its options.', '');
25
27
  return lines;
26
28
  }
@@ -42,7 +44,7 @@ function environmentHelp() {
42
44
  '',
43
45
  ];
44
46
  }
45
- export function renderCommandHelp(path, command, program = 'repown') {
47
+ export function renderCommandHelp(path, command, program) {
46
48
  const lines = ['', ' ' + usageFor(program, path, command), '', ' ' + command.summary, ''];
47
49
  if (optionsOf(command).length > 0)
48
50
  lines.push(...optionsHelp(command), '');
@@ -51,7 +53,7 @@ export function renderCommandHelp(path, command, program = 'repown') {
51
53
  lines.push(...examplesHelp(command.examples), '');
52
54
  return lines;
53
55
  }
54
- export function renderGroupHelp(path, group, program = 'repown') {
56
+ export function renderGroupHelp(path, group, program) {
55
57
  const lines = ['', ' ' + program + ' ' + path.join(' ') + ' <action>', '', ' Actions:'];
56
58
  for (const [name, action] of Object.entries(group.actions)) {
57
59
  const marker = name === group.defaultAction ? ' (default)' : '';
@@ -60,7 +62,7 @@ export function renderGroupHelp(path, group, program = 'repown') {
60
62
  lines.push('', ' Run `' + program + ' help ' + path.join(' ') + ' <action>` for its options.', '');
61
63
  return lines;
62
64
  }
63
- export function renderHelpFor(path, entry, program = 'repown') {
65
+ export function renderHelpFor(path, entry, program) {
64
66
  return isGroup(entry) ? renderGroupHelp(path, entry, program) : renderCommandHelp(path, entry, program);
65
67
  }
66
68
  function usageFor(program, path, command) {
@@ -93,5 +95,7 @@ function optionHelp(option) {
93
95
  const value = option.kind === 'boolean' ? '' : ' <value>';
94
96
  const choices = option.choices ? ' (' + option.choices.join('|') + ')' : '';
95
97
  const fallback = option.default !== undefined && option.default !== '' ? ' [default: ' + option.default + ']' : '';
96
- return ('--' + option.name + value).padEnd(20) + option.help + choices + fallback;
98
+ const head = '--' + option.name + value;
99
+ // A name too long for the column still gets a gap before its help.
100
+ return (head.length >= 20 ? head + ' ' : head.padEnd(20)) + option.help + choices + fallback;
97
101
  }
@@ -0,0 +1,117 @@
1
+ // The wizard drawn with @clack/prompts: arrow-key choices with a hint each, defaults,
2
+ // a line while state is read, the review in a box. The ONLY file that imports the
3
+ // library, and it is loaded with a dynamic import() by `repown setup` alone (ADR-016),
4
+ // so no other command -- and never the pre-push hook -- depends on it.
5
+ //
6
+ // Everything is drawn on the stream it's given (stderr), so stdout keeps carrying only
7
+ // what the commands print. Back is the engine's: a "← Back" choice, or `<` typed at a
8
+ // text question, offered from the second question on. Esc and Ctrl-C cancel.
9
+ import { styleText } from 'node:util';
10
+ import * as p from '@clack/prompts';
11
+ import { BACK, CANCEL } from "./engine.js";
12
+ import { BACK_WORD } from "./plain.js";
13
+ import { BACK_TO_REVIEW, PICK_QUESTION, RUN_THIS_STEP, reviewDefault, reviewLines, reviewOptions, reviewQuestion, stepConfirmLines, stepOptions, textWidth, wrap } from "./review-text.js";
14
+ /** A value no real choice can have. */
15
+ const GO_BACK = '\u0000back';
16
+ export function clackPrompter(streams) {
17
+ const io = { input: streams.input, output: streams.output };
18
+ return {
19
+ ask: (step, asked) => {
20
+ if (asked.detail)
21
+ p.log.info(wrap(asked.detail, widthOf(io, GUTTER)).join('\n'), io);
22
+ return askStep(step, asked, io);
23
+ },
24
+ review: (review) => showReview(review, io),
25
+ pickStep: async (steps) => {
26
+ const id = await p.select({ ...io, message: PICK_QUESTION,
27
+ options: [...steps.map((step) => ({ value: step.id, label: step.message })), { value: GO_BACK, label: '← ' + BACK_TO_REVIEW }] });
28
+ if (p.isCancel(id))
29
+ return CANCEL;
30
+ return id === GO_BACK ? BACK : id;
31
+ },
32
+ note: (message) => p.log.warn(wrap(message, widthOf(io, GUTTER)).join('\n'), io),
33
+ confirmStep: (confirm) => showStep(confirm, io),
34
+ close: () => { },
35
+ intro: (title) => p.intro(title, io),
36
+ // After a cancel, clack has already drawn the gutter's last line.
37
+ outro: (message, cancelled) => (cancelled ? p.cancel(message, io) : p.outro(message, io)),
38
+ // A line, not clack's spinner: the spinner takes over Ctrl-C and exits 0, where a
39
+ // cancel must exit 130.
40
+ busy: (message) => p.log.step(message, io),
41
+ };
42
+ }
43
+ /**
44
+ * Columns to leave free. clack wraps a list question 13 columns short of the window and
45
+ * a box's text 6 short, but never a text question's hint or a log line; wrapping every
46
+ * one here, within those widths, keeps them all in the gutter and none wrapped twice.
47
+ */
48
+ const GUTTER = 13;
49
+ const BOX = 6;
50
+ function widthOf(io, margin) {
51
+ return textWidth(io.output.columns, margin);
52
+ }
53
+ function askStep(step, asked, io) {
54
+ if (step.kind === 'select')
55
+ return askSelect(step, asked, io);
56
+ if (step.kind === 'confirm')
57
+ return askConfirm(step, asked, io);
58
+ return askText(step, asked, io);
59
+ }
60
+ /** "← Back", unless this is the first question asked and there is nowhere to go. */
61
+ function backOption(asked) {
62
+ return asked.canGoBack ? [{ value: GO_BACK, label: '← Back', hint: 'to the previous question' }] : [];
63
+ }
64
+ async function askSelect(step, asked, io) {
65
+ const options = [...asked.choices.map((choice) => ({ ...choice })), ...backOption(asked)];
66
+ const preset = typeof asked.initial === 'string' ? { initialValue: asked.initial } : {};
67
+ const value = await p.select({ ...io, ...preset, message: messageOf(step, io), options });
68
+ if (p.isCancel(value))
69
+ return CANCEL;
70
+ return value === GO_BACK ? BACK : value;
71
+ }
72
+ async function askConfirm(step, asked, io) {
73
+ const value = await p.select({ ...io, message: messageOf(step, io), initialValue: asked.initial === true ? 'yes' : 'no',
74
+ options: [{ value: 'yes', label: 'Yes' }, { value: 'no', label: 'No' }, ...backOption(asked)] });
75
+ if (p.isCancel(value))
76
+ return CANCEL;
77
+ return value === GO_BACK ? BACK : value === 'yes';
78
+ }
79
+ async function askText(step, asked, io) {
80
+ const preset = typeof asked.initial === 'string' ? { initialValue: asked.initial } : {};
81
+ const extra = asked.canGoBack ? 'type ' + BACK_WORD + ' to go back' : undefined;
82
+ const value = await p.text({ ...io, ...preset, message: messageOf(step, io, extra),
83
+ validate: (typed) => (isBack(typed, asked) ? undefined : step.validate?.((typed ?? '').trim()) ?? undefined) });
84
+ if (p.isCancel(value))
85
+ return CANCEL;
86
+ return isBack(value, asked) ? BACK : value.trim();
87
+ }
88
+ /** `<` means back only where there is somewhere to go; on the first question it is just text. */
89
+ function isBack(typed, asked) {
90
+ return asked.canGoBack && typed?.trim() === BACK_WORD;
91
+ }
92
+ /**
93
+ * clack draws its gutter in front of a select's second line but not a text prompt's,
94
+ * so a text question draws it itself.
95
+ */
96
+ const TEXT_GUTTER = styleText('gray', '│') + ' ';
97
+ /** The question, and under it the hint, wrapped in the gutter -- visible whatever the answer shows. */
98
+ function messageOf(step, io, extra) {
99
+ const hint = [step.hint, extra].filter((part) => part).join(' · ');
100
+ const gutter = step.kind === 'text' ? TEXT_GUTTER : '';
101
+ return [step.message, ...(hint ? wrap(hint, widthOf(io, GUTTER)) : [])].join('\n' + gutter);
102
+ }
103
+ async function showStep(confirm, io) {
104
+ const lines = stepConfirmLines(confirm).flatMap((text) => wrap(text, widthOf(io, GUTTER)));
105
+ p.log.message(lines.join('\n'), io);
106
+ return chosen(confirm, io);
107
+ }
108
+ async function chosen(confirm, io) {
109
+ const choice = await p.select({ ...io, message: RUN_THIS_STEP, options: stepOptions(), initialValue: confirm.initial });
110
+ return p.isCancel(choice) ? CANCEL : choice;
111
+ }
112
+ async function showReview(review, io) {
113
+ p.note(reviewLines(review, widthOf(io, BOX), (text) => styleText('dim', text)).join('\n'), review.title, io);
114
+ const choice = await p.select({ ...io, message: reviewQuestion(review), options: reviewOptions(review),
115
+ initialValue: reviewDefault(review) });
116
+ return p.isCancel(choice) ? CANCEL : choice;
117
+ }
@@ -0,0 +1,244 @@
1
+ // The wizard's navigation: which step comes next, going back, skipping what was
2
+ // given as a flag, and the review loop. It draws nothing itself -- a Prompter does
3
+ // (src/wizard/plain.ts, src/wizard/clack.ts, or a scripted one in the tests) -- and
4
+ // it writes nothing: it only returns the answers the review accepted. What those
5
+ // answers turn into is the flow's job (src/wizard/setup-flow.ts).
6
+ //
7
+ // WHY THE ENGINE OWNS "BACK". No prompt library draws navigation across questions
8
+ // (@clack/prompts has none), so the history lives here, where the scripted tests
9
+ // can drive it without a terminal.
10
+ export const BACK = Symbol('back');
11
+ export const CANCEL = Symbol('cancel');
12
+ /** Asks every reachable step from `pass.start` on, with a history for going back. */
13
+ export async function runFlow(flow, context, pass, prompter) {
14
+ const answers = { ...pass.answers };
15
+ const asked = [...pass.history];
16
+ let index = pass.start;
17
+ while (index < flow.steps.length) {
18
+ const step = flow.steps[index];
19
+ if (!shouldAsk(step, { answers, context, given: pass.given, resume: index === pass.start })) {
20
+ index++;
21
+ continue;
22
+ }
23
+ const reply = await ask(step, { answers, canGoBack: asked.length > 0 || pass.toOpening }, context, prompter);
24
+ if (reply === CANCEL)
25
+ return { status: 'cancelled' };
26
+ if (reply === BACK) {
27
+ const back = retreat(asked, pass.toOpening, index);
28
+ if (back.walk)
29
+ return back.walk;
30
+ index = back.index;
31
+ continue;
32
+ }
33
+ if (keep(step, reply, prompter, { answers, asked, index }))
34
+ index++;
35
+ }
36
+ return { status: 'answered', answers: filled(flow, answers, context, pass.given), asked };
37
+ }
38
+ function retreat(asked, toOpening, index) {
39
+ if (asked.length > 0)
40
+ return { index: asked.pop() };
41
+ return toOpening ? { walk: { status: 'opening' }, index } : { index };
42
+ }
43
+ function keep(step, reply, prompter, bag) {
44
+ const problem = step.validate?.(reply) ?? null;
45
+ if (problem) {
46
+ prompter.note(problem);
47
+ return false;
48
+ }
49
+ bag.answers[step.id] = reply;
50
+ bag.asked.push(bag.index);
51
+ return true;
52
+ }
53
+ /** The step this walk resumed on is asked even when `auto` would skip it. */
54
+ function shouldAsk(step, at) {
55
+ if (!applicable(step, at.answers, at.context, at.given))
56
+ return false;
57
+ if (at.resume)
58
+ return true;
59
+ if (step.skip?.(at.answers, at.context))
60
+ return false;
61
+ return !step.auto?.(at.answers, at.context);
62
+ }
63
+ function applicable(step, answers, context, given) {
64
+ return !given.has(step.id) && (step.when?.(answers, context) ?? true);
65
+ }
66
+ function filled(flow, answers, context, given) {
67
+ return prune(flow, flow.fill?.(answers, context) ?? answers, context, given);
68
+ }
69
+ async function ask(step, at, context, prompter) {
70
+ const { answers, canGoBack } = at;
71
+ const initial = answers[step.id] ?? await step.initial?.(answers, context);
72
+ const choices = step.choices?.(answers, context) ?? [];
73
+ const detail = step.detail?.(answers, context);
74
+ return prompter.ask(drawn(step, answers, context), { initial, choices, detail, canGoBack });
75
+ }
76
+ function drawn(step, answers, context) {
77
+ const shown = {
78
+ id: step.id, kind: step.kind, flag: step.flag,
79
+ message: wording(step.message, answers, context), hint: wording(step.hint, answers, context),
80
+ };
81
+ return step.validate ? { ...shown, validate: step.validate } : shown;
82
+ }
83
+ function wording(text, answers, context) {
84
+ return typeof text === 'function' ? text(answers, context) : text;
85
+ }
86
+ /** Drops answers whose step is no longer reachable, so a stale branch never reaches the plan. */
87
+ export function prune(flow, answers, context, given) {
88
+ const kept = {};
89
+ for (const step of flow.steps) {
90
+ const value = answers[step.id];
91
+ if (value === undefined)
92
+ continue;
93
+ if (given.has(step.id) || (step.when?.(kept, context) ?? true))
94
+ kept[step.id] = value;
95
+ }
96
+ return kept;
97
+ }
98
+ /** A value given as a flag passes the same check a typed answer would: one message per refusal. */
99
+ export function refusedGiven(flow, given) {
100
+ return flow.steps.flatMap((step) => {
101
+ const value = given[step.id];
102
+ const problem = value === undefined ? null : step.validate?.(value) ?? null;
103
+ return problem ? [step.flag + ': ' + problem] : [];
104
+ });
105
+ }
106
+ /** Steps the user can return to from the review: reachable, and not given as a flag. */
107
+ export function reachable(flow, answers, context, given) {
108
+ return flow.steps.filter((step) => answers[step.id] !== undefined && applicable(step, answers, context, given));
109
+ }
110
+ function fresh(given, fixed) {
111
+ return { answers: { ...given }, start: 0, given: fixed, history: [], toOpening: false, showOpening: fixed.size === 0 };
112
+ }
113
+ /** The whole wizard: an opening review when the flow has one, then ask, review, and loop. */
114
+ export async function wizard(flow, context, given, prompter) {
115
+ const fixed = new Set(Object.keys(given));
116
+ let pass = fresh(given, fixed);
117
+ for (;;) {
118
+ const opened = await takeOpening(flow, context, pass, prompter);
119
+ if (opened.outcome)
120
+ return opened.outcome;
121
+ pass = opened.pass;
122
+ const walked = await takePass(flow, context, pass, prompter);
123
+ if (walked.outcome)
124
+ return walked.outcome;
125
+ pass = walked.pass;
126
+ }
127
+ }
128
+ async function takeOpening(flow, context, pass, prompter) {
129
+ if (!pass.showOpening)
130
+ return { outcome: null, pass };
131
+ const opening = flow.opening?.(context) ?? null;
132
+ if (!opening)
133
+ return { outcome: null, pass: { ...pass, showOpening: false } };
134
+ return openingChoice({ flow, context, pass, prompter }, await prompter.review(opening));
135
+ }
136
+ function openingChoice(scene, choice) {
137
+ const stopped = stoppedChoice(choice);
138
+ if (stopped)
139
+ return { outcome: stopped, pass: scene.pass };
140
+ if (choice === 'account' || choice === 'gh')
141
+ return { outcome: null, pass: resumed(scene, choice, null) };
142
+ if (choice === 'edit')
143
+ scene.prompter.note('nothing has been asked yet');
144
+ return { outcome: null, pass: scene.pass };
145
+ }
146
+ function stoppedChoice(choice) {
147
+ if (choice === 'done')
148
+ return { status: 'done' };
149
+ if (choice === 'decline')
150
+ return { status: 'declined' };
151
+ if (choice === CANCEL)
152
+ return { status: 'cancelled' };
153
+ return null;
154
+ }
155
+ function resumed(scene, choice, walk) {
156
+ const spot = scene.flow.resume?.(choice, scene.context);
157
+ const start = spot?.start ?? 0;
158
+ return {
159
+ answers: branchAnswers(choice, spot?.answers ?? {}, walk), start, given: scene.pass.given,
160
+ history: walk ? walk.asked.filter((index) => index < start) : [],
161
+ toOpening: walk === null, showOpening: false,
162
+ };
163
+ }
164
+ function branchAnswers(choice, freshAnswers, walk) {
165
+ if (!walk)
166
+ return freshAnswers;
167
+ return choice === 'gh' ? { ...walk.answers, gh: true } : walk.answers;
168
+ }
169
+ async function takePass(flow, context, pass, prompter) {
170
+ const walk = await runFlow(flow, context, pass, prompter);
171
+ if (walk.status === 'cancelled')
172
+ return { outcome: { status: 'cancelled' }, pass };
173
+ if (walk.status === 'opening')
174
+ return { outcome: null, pass: fresh({}, pass.given) };
175
+ return afterReview({ flow, context, pass, prompter }, walk);
176
+ }
177
+ async function afterReview(scene, walk) {
178
+ const shown = scene.flow.review(walk.answers, scene.context);
179
+ const choice = await scene.prompter.review(shown);
180
+ const direct = directChoice(choice, shown, walk.answers);
181
+ if (direct)
182
+ return { outcome: direct, pass: scene.pass };
183
+ if (choice === 'account' || choice === 'gh')
184
+ return { outcome: null, pass: resumed(scene, choice, walk) };
185
+ return restart(scene, walk, choice);
186
+ }
187
+ /** Done promises "nothing needed changing": on a review with work left, it changes nothing either way. */
188
+ function directChoice(choice, shown, answers) {
189
+ if (choice === 'run')
190
+ return { status: 'run', answers };
191
+ if (choice === 'done')
192
+ return { status: shown.settled ? 'done' : 'declined' };
193
+ if (choice === 'decline')
194
+ return { status: 'declined' };
195
+ if (choice === CANCEL)
196
+ return { status: 'cancelled' };
197
+ return null;
198
+ }
199
+ async function restart(scene, walk, choice) {
200
+ if (choice !== 'back' && choice !== 'edit')
201
+ return { outcome: null, pass: scene.pass };
202
+ const how = { walk, given: scene.pass.given, choice, toOpening: scene.pass.toOpening };
203
+ const start = await restartAt(scene.flow, scene.context, how, scene.prompter);
204
+ if (start === CANCEL)
205
+ return { outcome: { status: 'cancelled' }, pass: scene.pass };
206
+ if (start === 'opening')
207
+ return { outcome: null, pass: fresh({}, scene.pass.given) };
208
+ return { outcome: null, pass: continued(scene.pass, walk, start) };
209
+ }
210
+ function continued(pass, walk, start) {
211
+ return {
212
+ answers: walk.answers, start, given: pass.given,
213
+ history: walk.asked.filter((index) => index < start),
214
+ toOpening: false, showOpening: false,
215
+ };
216
+ }
217
+ /**
218
+ * Where to resume: the last step asked (Back), or the one the user picks (Change an
219
+ * answer). With nothing asked -- every value given as a flag -- Back has nowhere to go
220
+ * and simply shows the review again. Back from a pass that came from the opening
221
+ * review returns there.
222
+ */
223
+ async function restartAt(flow, context, how, prompter) {
224
+ if (how.choice === 'back')
225
+ return backIndex(how, flow);
226
+ const steps = reachable(flow, how.walk.answers, context, how.given).map((step) => drawn(step, how.walk.answers, context));
227
+ if (steps.length === 0) {
228
+ prompter.note('every answer came from a flag: there is nothing here to change');
229
+ return flow.steps.length;
230
+ }
231
+ const id = await prompter.pickStep(steps);
232
+ if (id === CANCEL)
233
+ return CANCEL;
234
+ if (id === BACK)
235
+ return flow.steps.length;
236
+ const index = flow.steps.findIndex((step) => step.id === id);
237
+ return index < 0 ? flow.steps.length : index;
238
+ }
239
+ function backIndex(how, flow) {
240
+ const last = how.walk.asked.at(-1);
241
+ if (last !== undefined)
242
+ return last;
243
+ return how.toOpening ? 'opening' : flow.steps.length;
244
+ }
@@ -0,0 +1,172 @@
1
+ // The wizard drawn with plain lines: numbered choices, words instead of symbols, no
2
+ // colour needed. Used when the richer prompter can't be (NO_COLOR or FORCE_COLOR=0,
3
+ // always TERM=dumb, or @clack/prompts fails to load) and by the tests, which drive it
4
+ // through ordinary streams.
5
+ //
6
+ // Everything goes to the output stream it's given -- stderr in real use -- so stdout
7
+ // keeps carrying only what the commands themselves print. End of input or Ctrl-C at a
8
+ // question is a cancel, never an answer.
9
+ import { createInterface } from 'node:readline/promises';
10
+ import { BACK, CANCEL } from "./engine.js";
11
+ import { BACK_TO_REVIEW, PICK_QUESTION, RUN_THIS_STEP, reviewDefault, reviewLines, reviewOptions, reviewQuestion, stepConfirmLines, stepOptions, textWidth, wrap } from "./review-text.js";
12
+ /** Typed at a text question, it means "go back" (never used for a real answer here). */
13
+ export const BACK_WORD = '<';
14
+ export function plainPrompter(streams) {
15
+ const session = plainSession(streams);
16
+ // Text is indented two spaces, the review's four.
17
+ const width = textWidth(streams.output.columns, 4);
18
+ const wide = () => ({ ...session.io(), width });
19
+ return {
20
+ ask: (step, asked) => askStep(wide(), step, asked),
21
+ review: (review) => showReview(session.io(), review, width),
22
+ pickStep: (steps) => pickPlain(session.io(), steps),
23
+ note: (message) => { for (const line of wrap(message, width))
24
+ session.io().say(' ' + line); },
25
+ close: () => session.close(),
26
+ outro: (message) => session.io().say(message),
27
+ confirmStep: (confirm) => askStepConfirm(wide(), confirm),
28
+ suspend: () => session.suspend(),
29
+ };
30
+ }
31
+ function plainSession(streams) {
32
+ // On a real terminal, readline must own it: only then does Ctrl-C arrive as its
33
+ // SIGINT event (a cancel) instead of ending the process with a signal.
34
+ const terminal = streams.input.isTTY === true;
35
+ let rl = openReadline(streams, terminal);
36
+ let io = ioFor(rl, streams.output, terminal);
37
+ let held = true;
38
+ const reopen = () => {
39
+ if (held)
40
+ return io;
41
+ rl = openReadline(streams, terminal);
42
+ io = ioFor(rl, streams.output, terminal);
43
+ held = true;
44
+ return io;
45
+ };
46
+ const shut = () => { if (!held)
47
+ return; held = false; rl.close(); };
48
+ return { io: reopen, close: shut, suspend: shut };
49
+ }
50
+ function openReadline(streams, terminal) {
51
+ return createInterface({ input: streams.input, output: streams.output, terminal });
52
+ }
53
+ /** On a terminal, readline shows the prompt, so it can redraw it while the line is edited. */
54
+ function ioFor(rl, output, terminal) {
55
+ const lines = queue(rl);
56
+ let closed = false;
57
+ rl.on('close', () => { closed = true; });
58
+ const write = (text) => { output.write(text); };
59
+ const show = (text) => {
60
+ if (!terminal || closed) {
61
+ write(text);
62
+ return;
63
+ }
64
+ rl.setPrompt(text);
65
+ rl.prompt();
66
+ };
67
+ return { lines, write: show, say: (text) => write(text + '\n') };
68
+ }
69
+ /** The input as a queue of lines; null once it has ended or Ctrl-C was pressed. */
70
+ function queue(rl) {
71
+ const waiting = [];
72
+ const buffered = [];
73
+ const push = (line) => { const take = waiting.shift(); if (take)
74
+ take(line);
75
+ else
76
+ buffered.push(line); };
77
+ let ended = false;
78
+ rl.on('line', (line) => push(line));
79
+ rl.on('close', () => { ended = true; push(null); });
80
+ rl.on('SIGINT', () => { push(null); rl.close(); });
81
+ return () => {
82
+ if (buffered.length > 0)
83
+ return Promise.resolve(buffered[0] === null ? null : buffered.shift());
84
+ // Every read after the end is a cancel too, not a wait for a line that can't come.
85
+ if (ended)
86
+ return Promise.resolve(null);
87
+ return new Promise((resolve) => waiting.push(resolve));
88
+ };
89
+ }
90
+ /** The question, its hint and any detail under it, each wrapped and indented. */
91
+ async function askStep(io, step, asked) {
92
+ const { initial, detail } = asked;
93
+ io.say(step.message);
94
+ for (const line of [step.hint, detail].filter((text) => text).flatMap((text) => wrap(text, io.width)))
95
+ io.say(' ' + line);
96
+ if (step.kind === 'select')
97
+ return askSelect(io, asked);
98
+ if (step.kind === 'confirm')
99
+ return askConfirm(io, initial === true, asked.canGoBack);
100
+ const shown = typeof initial === 'string' && initial ? ' [' + initial + ']' : '';
101
+ if (asked.canGoBack)
102
+ io.say(' type ' + BACK_WORD + ' to go back');
103
+ const line = await prompt(io, ' >' + shown + ' ');
104
+ if (line === null)
105
+ return CANCEL;
106
+ if (line === BACK_WORD && asked.canGoBack)
107
+ return BACK;
108
+ return line || (typeof initial === 'string' ? initial : '');
109
+ }
110
+ async function pickPlain(io, steps) {
111
+ io.say(PICK_QUESTION);
112
+ const index = await pickNumber(io, [...steps.map((step) => step.message), BACK_TO_REVIEW], 1);
113
+ if (index === CANCEL)
114
+ return CANCEL;
115
+ return index === steps.length ? BACK : steps[index].id;
116
+ }
117
+ async function askStepConfirm(io, confirm) {
118
+ for (const line of stepConfirmLines(confirm).flatMap((text) => wrap(text, io.width)))
119
+ io.say(' ' + line);
120
+ io.say(RUN_THIS_STEP);
121
+ const options = stepOptions();
122
+ const preset = options.findIndex((option) => option.value === confirm.initial) + 1;
123
+ const index = await pickNumber(io, options.map((option) => option.label), preset);
124
+ return index === CANCEL ? CANCEL : options[index].value;
125
+ }
126
+ async function askSelect(io, { choices, initial, canGoBack }) {
127
+ const labels = choices.map((choice) => choice.label + (choice.hint ? ' -- ' + choice.hint : ''));
128
+ const current = choices.findIndex((choice) => choice.value === initial);
129
+ const index = await pickNumber(io, canGoBack ? [...labels, 'Back'] : labels, current >= 0 ? current + 1 : 1);
130
+ if (index === CANCEL)
131
+ return CANCEL;
132
+ return index === choices.length ? BACK : choices[index].value;
133
+ }
134
+ async function askConfirm(io, yes, canGoBack) {
135
+ const index = await pickNumber(io, canGoBack ? ['Yes', 'No', 'Back'] : ['Yes', 'No'], yes ? 1 : 2);
136
+ if (index === CANCEL)
137
+ return CANCEL;
138
+ return index === 2 ? BACK : index === 0;
139
+ }
140
+ async function showReview(io, review, width) {
141
+ io.say('');
142
+ io.say(review.title);
143
+ for (const line of reviewLines(review, width))
144
+ io.say(line ? ' ' + line : '');
145
+ io.say('');
146
+ io.say(reviewQuestion(review));
147
+ const options = reviewOptions(review);
148
+ const preset = options.findIndex((option) => option.value === reviewDefault(review)) + 1;
149
+ const index = await pickNumber(io, options.map((option) => option.label + (option.hint ? ' -- ' + option.hint : '')), preset);
150
+ return index === CANCEL ? CANCEL : options[index].value;
151
+ }
152
+ /** Lists numbered options and reads a number until it's valid; Enter takes the default. */
153
+ async function pickNumber(io, labels, preset) {
154
+ labels.forEach((label, index) => io.say(' ' + (index + 1) + ') ' + label));
155
+ for (;;) {
156
+ const line = await prompt(io, ' choice [' + preset + ']: ');
157
+ if (line === null)
158
+ return CANCEL;
159
+ const picked = line === '' ? preset : Number(line);
160
+ if (Number.isInteger(picked) && picked >= 1 && picked <= labels.length)
161
+ return picked - 1;
162
+ io.say(' type a number from 1 to ' + labels.length);
163
+ }
164
+ }
165
+ /** A line typed after `text`; null after Ctrl-C or the end of input, which leave the line unfinished. */
166
+ async function prompt(io, text) {
167
+ io.write(text);
168
+ const line = await io.lines();
169
+ if (line === null)
170
+ io.say('');
171
+ return line === null ? null : line.trim();
172
+ }