codepen-commander 1.3.0 → 1.4.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.
Files changed (92) hide show
  1. package/README.md +103 -11
  2. package/api/client.js +129 -106
  3. package/cli.js +34 -29
  4. package/commands/auth/default.js +40 -0
  5. package/commands/auth/index.js +83 -0
  6. package/commands/auth/list.js +78 -0
  7. package/commands/auth/login.js +136 -0
  8. package/commands/auth/logout.js +186 -0
  9. package/commands/auth/status.js +212 -0
  10. package/commands/build.js +256 -0
  11. package/commands/clone.js +13 -581
  12. package/commands/delete.js +548 -80
  13. package/commands/deploy.js +164 -169
  14. package/commands/domains.js +83 -39
  15. package/commands/fork.js +13 -317
  16. package/commands/info.js +152 -0
  17. package/commands/init.js +375 -0
  18. package/commands/list.js +95 -78
  19. package/commands/new.js +155 -83
  20. package/commands/open.js +29 -19
  21. package/commands/privacy.js +52 -36
  22. package/commands/pull.js +123 -110
  23. package/commands/push.js +221 -376
  24. package/commands/restore.js +251 -0
  25. package/commands/rollback.js +141 -0
  26. package/commands/serve.js +119 -0
  27. package/commands/settings.js +126 -0
  28. package/commands/shell.js +305 -0
  29. package/commands/status.js +133 -39
  30. package/commands/sync.js +330 -0
  31. package/commands/undeploy.js +102 -0
  32. package/commands/unlink.js +191 -0
  33. package/commands/versions.js +100 -163
  34. package/config/auth.js +4 -374
  35. package/config/pen-blocks.js +166 -0
  36. package/config/project.js +103 -231
  37. package/config/user-store.js +364 -0
  38. package/constants.js +42 -0
  39. package/errors.js +17 -0
  40. package/package.json +1 -1
  41. package/shell/index.html +79 -0
  42. package/shell/scripts.js +276 -0
  43. package/shell/styles.css +492 -0
  44. package/site/blocks/classic.js +270 -0
  45. package/site/blocks/context.js +63 -0
  46. package/site/blocks/index.js +4 -0
  47. package/site/blocks/packages.js +242 -0
  48. package/site/blocks/unsupported-page.js +328 -0
  49. package/site/builder.js +475 -0
  50. package/site/detect.js +65 -0
  51. package/site/ignore-files.js +90 -0
  52. package/site/manifest.js +227 -0
  53. package/site/server.js +483 -0
  54. package/site/shell.js +363 -0
  55. package/sync/fs.js +19 -17
  56. package/sync/info.js +6 -81
  57. package/utils/browser.js +17 -10
  58. package/utils/cli-options.js +79 -0
  59. package/utils/codepen-url.js +183 -0
  60. package/utils/format.js +39 -30
  61. package/utils/fs-safe.js +95 -0
  62. package/utils/html.js +40 -1
  63. package/utils/json.js +4 -19
  64. package/utils/output.js +37 -0
  65. package/utils/package-paths.js +51 -0
  66. package/utils/prompts/index.js +5 -0
  67. package/utils/prompts/multi-select.js +185 -0
  68. package/utils/prompts/secret.js +65 -0
  69. package/utils/prompts/select.js +141 -0
  70. package/utils/prompts/text.js +99 -0
  71. package/utils/prompts/tty-list.js +165 -0
  72. package/utils/prompts/types.js +35 -0
  73. package/utils/strings.js +98 -0
  74. package/utils/watcher.js +82 -0
  75. package/{commands → workflows}/auth-context.js +13 -7
  76. package/workflows/batch-pens.js +1647 -0
  77. package/workflows/batch-target.js +184 -0
  78. package/workflows/classic-convert.js +241 -0
  79. package/workflows/clone-pen.js +381 -0
  80. package/{commands → workflows}/create-pen.js +59 -84
  81. package/workflows/discover-pens.js +91 -0
  82. package/workflows/fork-pen.js +314 -0
  83. package/workflows/missing-pen.js +212 -0
  84. package/workflows/pull-pen.js +204 -0
  85. package/workflows/push-pen.js +318 -0
  86. package/{commands → workflows}/scaffold.js +4 -3
  87. package/workflows/sync-pen.js +227 -0
  88. package/{commands → workflows}/unowned-pen.js +16 -12
  89. package/commands/auth.js +0 -593
  90. package/commands/meta.js +0 -184
  91. package/utils/prompts.js +0 -316
  92. /package/{types.js → api/types.js} +0 -0
@@ -0,0 +1,185 @@
1
+ import readlinePromises from 'node:readline/promises';
2
+ import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
3
+ import { createFormatter } from '../format.js';
4
+ import { runInteractiveListPrompt } from './tty-list.js';
5
+ import { canUseInteractiveTty, } from './types.js';
6
+ async function promptMultiSelectFallback(question, options, input, output) {
7
+ const f = createFormatter(output);
8
+ const selected = new Set();
9
+ options.forEach((opt, idx) => {
10
+ if (opt.locked || opt.checked) {
11
+ selected.add(idx);
12
+ }
13
+ });
14
+ output.write(`${f.cyan('◆')} ${f.bold(question)}\n`);
15
+ options.forEach((opt, idx) => {
16
+ const num = f.cyan(`${idx + 1})`);
17
+ const mark = selected.has(idx) ? (opt.locked ? f.dim('[✓]') : f.boldGreen('[✓]')) : f.dim('[ ]');
18
+ const desc = opt.description ? ` ${f.dim(`— ${opt.description}`)}` : '';
19
+ output.write(` ${num} ${mark} ${opt.label}${desc}\n`);
20
+ });
21
+ const rl = readlinePromises.createInterface({ input, output });
22
+ try {
23
+ const answer = (await rl.question(` ${f.dim('Toggle numbers/names (comma-separated) or press Enter to keep defaults:')} `)).trim();
24
+ if (answer && answer.toLowerCase() !== 'none') {
25
+ for (const token of answer.split(',').map((t) => t.trim()).filter(Boolean)) {
26
+ let idx = -1;
27
+ const num = Number.parseInt(token, 10);
28
+ if (!Number.isNaN(num) && num >= 1 && num <= options.length && String(num) === token) {
29
+ idx = num - 1;
30
+ }
31
+ else {
32
+ const lower = token.toLowerCase();
33
+ idx = options.findIndex((opt) => opt.value.toLowerCase() === lower || opt.label.toLowerCase() === lower);
34
+ }
35
+ if (idx === -1)
36
+ continue;
37
+ const opt = options[idx];
38
+ if (opt.locked) {
39
+ selected.add(idx);
40
+ continue;
41
+ }
42
+ if (selected.has(idx)) {
43
+ selected.delete(idx);
44
+ }
45
+ else {
46
+ selected.add(idx);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ finally {
52
+ rl.close();
53
+ }
54
+ const chosen = options.filter((_, idx) => selected.has(idx));
55
+ const summary = chosen.length > 0 ? chosen.map((o) => o.label).join(', ') : '(none)';
56
+ output.write(` ${f.boldGreen('→')} ${f.boldGreen(summary)}\n`);
57
+ return chosen.map((o) => o.value);
58
+ }
59
+ function promptMultiSelectInteractive(question, options, input, output) {
60
+ const selected = new Set();
61
+ options.forEach((opt, idx) => {
62
+ if (opt.locked || opt.checked) {
63
+ selected.add(idx);
64
+ }
65
+ });
66
+ const firstUnlocked = options.findIndex((opt) => !opt.locked);
67
+ const initialCursor = firstUnlocked !== -1 ? firstUnlocked : 0;
68
+ let notice = null;
69
+ return runInteractiveListPrompt({
70
+ question,
71
+ itemCount: options.length,
72
+ initialCursor,
73
+ reserveRows: 6,
74
+ input,
75
+ output,
76
+ onBeforeNavigate() {
77
+ notice = null;
78
+ },
79
+ renderActiveLines({ cursorIndex, windowStart, windowEnd, fmt: f }) {
80
+ const lines = [
81
+ `${f.cyan('◆')} ${f.bold(question)} ${f.dim('(↑/↓, Space toggle, Enter confirm)')}`,
82
+ ];
83
+ if (windowStart > 0) {
84
+ lines.push(` ${f.dim(`↑ ${windowStart} more`)}`);
85
+ }
86
+ for (let i = windowStart; i < windowEnd; i++) {
87
+ const opt = options[i];
88
+ const isCursor = i === cursorIndex;
89
+ const isChecked = selected.has(i);
90
+ const box = isChecked
91
+ ? opt.locked
92
+ ? f.dim('[✓]')
93
+ : f.boldGreen('[✓]')
94
+ : f.dim('[ ]');
95
+ if (isCursor) {
96
+ const desc = opt.description ? ` ${f.cyan(`— ${opt.description}`)}` : '';
97
+ lines.push(` ${f.boldCyan('→')} ${box} ${f.boldCyan(opt.label)}${desc}`);
98
+ }
99
+ else {
100
+ const labelText = opt.locked ? f.dim(opt.label) : opt.label;
101
+ const desc = opt.description ? ` ${f.dim(`— ${opt.description}`)}` : '';
102
+ lines.push(` ${box} ${labelText}${desc}`);
103
+ }
104
+ }
105
+ const hiddenBelow = options.length - windowEnd;
106
+ if (hiddenBelow > 0) {
107
+ lines.push(` ${f.dim(`↓ ${hiddenBelow} more`)}`);
108
+ }
109
+ if (notice) {
110
+ lines.push(` ${f.yellow(notice)}`);
111
+ }
112
+ return lines;
113
+ },
114
+ renderConfirmedLines(_cursorIndex, f) {
115
+ const chosen = options.filter((_, idx) => selected.has(idx));
116
+ const summary = chosen.length > 0 ? chosen.map((o) => o.label).join(', ') : '(none)';
117
+ return [
118
+ `${f.cyan('◆')} ${f.bold(question)}`,
119
+ ` ${f.boldGreen('→')} ${f.boldGreen(summary)}`,
120
+ ];
121
+ },
122
+ getConfirmedValue() {
123
+ return options.filter((_, idx) => selected.has(idx)).map((o) => o.value);
124
+ },
125
+ onCustomKey(str, key, ctx) {
126
+ if (key?.name === 'space' || str === ' ') {
127
+ const opt = options[ctx.cursorIndex];
128
+ if (opt.locked) {
129
+ notice = `"${opt.label}" is required and cannot be unselected.`;
130
+ }
131
+ else {
132
+ notice = null;
133
+ if (selected.has(ctx.cursorIndex)) {
134
+ selected.delete(ctx.cursorIndex);
135
+ }
136
+ else {
137
+ selected.add(ctx.cursorIndex);
138
+ }
139
+ }
140
+ ctx.rerender();
141
+ return;
142
+ }
143
+ if (!key?.ctrl && !key?.meta && str && str.toLowerCase() === 'a') {
144
+ notice = null;
145
+ const unlockedIndices = options
146
+ .map((opt, idx) => (opt.locked ? -1 : idx))
147
+ .filter((idx) => idx !== -1);
148
+ const allUnlockedSelected = unlockedIndices.every((idx) => selected.has(idx));
149
+ for (const idx of unlockedIndices) {
150
+ if (allUnlockedSelected) {
151
+ selected.delete(idx);
152
+ }
153
+ else {
154
+ selected.add(idx);
155
+ }
156
+ }
157
+ ctx.rerender();
158
+ return;
159
+ }
160
+ if (str && /^[1-9]$/.test(str) && !key?.ctrl && !key?.meta) {
161
+ notice = null;
162
+ const idx = Number.parseInt(str, 10) - 1;
163
+ if (idx >= 0 && idx < options.length && idx !== ctx.cursorIndex) {
164
+ ctx.setCursorIndex(idx);
165
+ ctx.rerender();
166
+ }
167
+ }
168
+ },
169
+ });
170
+ }
171
+ export async function promptMultiSelectWithIO(question, options, io = {}) {
172
+ if (options.length === 0) {
173
+ throw new Error('promptMultiSelect requires at least one option.');
174
+ }
175
+ const input = io.input ?? defaultInput;
176
+ const output = io.output ?? defaultOutput;
177
+ const term = io.term ?? process.env.TERM;
178
+ if (canUseInteractiveTty(input, output, term)) {
179
+ return promptMultiSelectInteractive(question, options, input, output);
180
+ }
181
+ return promptMultiSelectFallback(question, options, input, output);
182
+ }
183
+ export async function promptMultiSelect(question, options) {
184
+ return promptMultiSelectWithIO(question, options);
185
+ }
@@ -0,0 +1,65 @@
1
+ import readlinePromises from 'node:readline/promises';
2
+ import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
3
+ import { createFormatter } from '../format.js';
4
+ import { PromptCanceledError } from './types.js';
5
+ /**
6
+ * Prompts for a secret (such as an API key) without echoing the raw characters to the terminal.
7
+ */
8
+ export async function promptSecret(question) {
9
+ const f = createFormatter(defaultOutput);
10
+ if (!defaultInput.isTTY) {
11
+ defaultOutput.write(`${f.cyan('◆')} ${f.bold(question)}\n`);
12
+ const rl = readlinePromises.createInterface({ input: defaultInput, output: defaultOutput });
13
+ try {
14
+ return (await rl.question(` ${f.boldCyan('→')} `)).trim();
15
+ }
16
+ finally {
17
+ rl.close();
18
+ }
19
+ }
20
+ return new Promise((resolve, reject) => {
21
+ defaultOutput.write(`${f.cyan('◆')} ${f.bold(question)}\n ${f.boldCyan('→')} `);
22
+ let value = '';
23
+ const wasRaw = defaultInput.isRaw;
24
+ defaultInput.setRawMode(true);
25
+ defaultInput.resume();
26
+ defaultInput.setEncoding('utf8');
27
+ const cleanup = () => {
28
+ defaultInput.removeListener('data', onData);
29
+ defaultInput.setRawMode(Boolean(wasRaw));
30
+ defaultInput.pause();
31
+ };
32
+ const onData = (chunk) => {
33
+ for (const ch of chunk) {
34
+ if (ch === '\r' || ch === '\n') {
35
+ cleanup();
36
+ const masked = value.trim() ? '•'.repeat(Math.min(value.trim().length, 16)) : '(empty)';
37
+ defaultOutput.write(`\r\x1b[K ${f.boldGreen('→')} ${f.dim(masked)}\n`);
38
+ resolve(value.trim());
39
+ return;
40
+ }
41
+ if (ch === '\u0003') {
42
+ // Ctrl+C
43
+ cleanup();
44
+ defaultOutput.write(`\r\x1b[K ${f.red('×')} ${f.dim('Canceled')}\n`);
45
+ reject(new PromptCanceledError());
46
+ return;
47
+ }
48
+ if (ch === '\u007f' || ch === '\b') {
49
+ if (value.length > 0) {
50
+ value = value.slice(0, -1);
51
+ defaultOutput.write('\b \b');
52
+ }
53
+ continue;
54
+ }
55
+ // Ignore non-printable escape sequences
56
+ if (ch.charCodeAt(0) < 32) {
57
+ continue;
58
+ }
59
+ value += ch;
60
+ defaultOutput.write('•');
61
+ }
62
+ };
63
+ defaultInput.on('data', onData);
64
+ });
65
+ }
@@ -0,0 +1,141 @@
1
+ import readlinePromises from 'node:readline/promises';
2
+ import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
3
+ import { createFormatter } from '../format.js';
4
+ import { runInteractiveListPrompt } from './tty-list.js';
5
+ import { canUseInteractiveTty, } from './types.js';
6
+ async function promptSelectFallback(question, options, defaultIndex, input, output) {
7
+ const f = createFormatter(output);
8
+ output.write(`${f.cyan('◆')} ${f.bold(question)}\n`);
9
+ options.forEach((opt, idx) => {
10
+ const num = f.cyan(`${idx + 1})`);
11
+ const desc = opt.description ? ` ${f.dim(`— ${opt.description}`)}` : '';
12
+ output.write(` ${num} ${opt.label}${desc}\n`);
13
+ });
14
+ const rl = readlinePromises.createInterface({ input, output });
15
+ try {
16
+ for (;;) {
17
+ const answer = (await rl.question(` ${f.dim(`Choose [1-${options.length}] (default ${defaultIndex + 1}):`)} `)).trim();
18
+ let matched;
19
+ if (!answer) {
20
+ matched = options[defaultIndex];
21
+ }
22
+ else {
23
+ const num = Number.parseInt(answer, 10);
24
+ if (!Number.isNaN(num) && num >= 1 && num <= options.length && String(num) === answer) {
25
+ matched = options[num - 1];
26
+ }
27
+ else {
28
+ const lower = answer.toLowerCase();
29
+ matched = options.find((opt) => opt.value.toLowerCase() === lower ||
30
+ opt.label.toLowerCase() === lower ||
31
+ (opt.shortcut !== undefined && opt.shortcut.toLowerCase() === lower));
32
+ }
33
+ }
34
+ if (matched) {
35
+ const desc = matched.description ? ` ${f.dim(`— ${matched.description}`)}` : '';
36
+ output.write(` ${f.boldGreen('→')} ${f.boldGreen(matched.label)}${desc}\n`);
37
+ return matched.value;
38
+ }
39
+ output.write(` ${f.yellow(`Please enter a number between 1 and ${options.length} (or an option name).`)}\n`);
40
+ }
41
+ }
42
+ finally {
43
+ rl.close();
44
+ }
45
+ }
46
+ function promptSelectInteractive(question, options, defaultIndex, input, output) {
47
+ return runInteractiveListPrompt({
48
+ question,
49
+ itemCount: options.length,
50
+ initialCursor: defaultIndex,
51
+ reserveRows: 5,
52
+ input,
53
+ output,
54
+ renderActiveLines({ cursorIndex, windowStart, windowEnd, fmt: f }) {
55
+ const lines = [
56
+ `${f.cyan('◆')} ${f.bold(question)} ${f.dim('(↑/↓, Enter)')}`,
57
+ ];
58
+ if (windowStart > 0) {
59
+ lines.push(` ${f.dim(`↑ ${windowStart} more`)}`);
60
+ }
61
+ for (let i = windowStart; i < windowEnd; i++) {
62
+ const opt = options[i];
63
+ const isSelected = i === cursorIndex;
64
+ if (isSelected) {
65
+ const desc = opt.description ? ` ${f.cyan(`— ${opt.description}`)}` : '';
66
+ lines.push(` ${f.boldCyan('→')} ${f.boldCyan(opt.label)}${desc}`);
67
+ }
68
+ else {
69
+ const desc = opt.description ? ` ${f.dim(`— ${opt.description}`)}` : '';
70
+ lines.push(` ${opt.label}${desc}`);
71
+ }
72
+ }
73
+ const hiddenBelow = options.length - windowEnd;
74
+ if (hiddenBelow > 0) {
75
+ lines.push(` ${f.dim(`↓ ${hiddenBelow} more`)}`);
76
+ }
77
+ return lines;
78
+ },
79
+ renderConfirmedLines(cursorIndex, f) {
80
+ const chosen = options[cursorIndex];
81
+ const desc = chosen.description ? ` ${f.dim(`— ${chosen.description}`)}` : '';
82
+ return [
83
+ `${f.cyan('◆')} ${f.bold(question)}`,
84
+ ` ${f.boldGreen('→')} ${f.boldGreen(chosen.label)}${desc}`,
85
+ ];
86
+ },
87
+ getConfirmedValue(cursorIndex) {
88
+ return options[cursorIndex].value;
89
+ },
90
+ onCustomKey(str, key, ctx) {
91
+ if (!str || key?.ctrl || key?.meta)
92
+ return;
93
+ if (/^[1-9]$/.test(str)) {
94
+ const idx = Number.parseInt(str, 10) - 1;
95
+ if (idx >= 0 && idx < options.length && idx !== ctx.cursorIndex) {
96
+ ctx.setCursorIndex(idx);
97
+ ctx.rerender();
98
+ }
99
+ return;
100
+ }
101
+ const lower = str.toLowerCase();
102
+ const shortcutIdx = options.findIndex((opt) => opt.shortcut !== undefined && opt.shortcut.toLowerCase() === lower);
103
+ if (shortcutIdx !== -1 && shortcutIdx !== ctx.cursorIndex) {
104
+ ctx.setCursorIndex(shortcutIdx);
105
+ ctx.rerender();
106
+ }
107
+ },
108
+ });
109
+ }
110
+ export async function promptSelectWithIO(question, options, defaultIndex = 0, io = {}) {
111
+ if (options.length === 0) {
112
+ throw new Error('promptSelect requires at least one option.');
113
+ }
114
+ const clampedDefault = Math.min(Math.max(0, Math.trunc(defaultIndex)), options.length - 1);
115
+ const input = io.input ?? defaultInput;
116
+ const output = io.output ?? defaultOutput;
117
+ const term = io.term ?? process.env.TERM;
118
+ if (canUseInteractiveTty(input, output, term)) {
119
+ return promptSelectInteractive(question, options, clampedDefault, input, output);
120
+ }
121
+ return promptSelectFallback(question, options, clampedDefault, input, output);
122
+ }
123
+ export async function promptSelect(question, options, defaultIndex = 0) {
124
+ return promptSelectWithIO(question, options, defaultIndex);
125
+ }
126
+ export async function promptConfirmWithIO(question, defaultYes = false, io = {}) {
127
+ const options = defaultYes
128
+ ? [
129
+ { value: 'yes', label: 'Yes', shortcut: 'y' },
130
+ { value: 'no', label: 'No', shortcut: 'n' },
131
+ ]
132
+ : [
133
+ { value: 'no', label: 'No', shortcut: 'n' },
134
+ { value: 'yes', label: 'Yes', shortcut: 'y' },
135
+ ];
136
+ const choice = await promptSelectWithIO(question, options, 0, io);
137
+ return choice === 'yes';
138
+ }
139
+ export async function promptConfirm(question, defaultYes = false) {
140
+ return promptConfirmWithIO(question, defaultYes);
141
+ }
@@ -0,0 +1,99 @@
1
+ import readlinePromises from 'node:readline/promises';
2
+ import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
3
+ import { createFormatter } from '../format.js';
4
+ import { PromptCanceledError, canUseInteractiveTty, countTerminalRows, formatQuestionHeader, } from './types.js';
5
+ async function readInteractiveLine(promptText, input, output, f) {
6
+ const rl = readlinePromises.createInterface({ input, output });
7
+ const abortController = new AbortController();
8
+ const onSigint = () => {
9
+ abortController.abort();
10
+ rl.close();
11
+ };
12
+ const onClose = () => {
13
+ abortController.abort();
14
+ };
15
+ rl.on('SIGINT', onSigint);
16
+ rl.once('close', onClose);
17
+ try {
18
+ return await rl.question(promptText, { signal: abortController.signal });
19
+ }
20
+ catch (err) {
21
+ const code = err?.code;
22
+ const name = err?.name;
23
+ if (abortController.signal.aborted ||
24
+ name === 'AbortError' ||
25
+ code === 'ABORT_ERR' ||
26
+ code === 'ERR_USE_AFTER_CLOSE') {
27
+ output.write(`\r\x1b[K ${f.red('×')} ${f.dim('Canceled')}\n`);
28
+ throw new PromptCanceledError();
29
+ }
30
+ throw err;
31
+ }
32
+ finally {
33
+ rl.off('SIGINT', onSigint);
34
+ rl.off('close', onClose);
35
+ rl.close();
36
+ }
37
+ }
38
+ export async function promptValidatedTextWithIO(question, options) {
39
+ const input = options.io?.input ?? defaultInput;
40
+ const output = options.io?.output ?? defaultOutput;
41
+ const term = options.io?.term ?? process.env.TERM;
42
+ const f = createFormatter(output);
43
+ const interactive = canUseInteractiveTty(input, output, term);
44
+ output.write(`${formatQuestionHeader(question, options.defaultValue, f)}\n`);
45
+ if (interactive) {
46
+ const promptPrefix = ` ${f.boldCyan('→')} `;
47
+ const getColumns = () => Math.max(20, output.columns || 80);
48
+ for (;;) {
49
+ const raw = await readInteractiveLine(promptPrefix, input, output, f);
50
+ const result = await options.validate(raw);
51
+ if (!result.ok) {
52
+ output.write(` ${f.yellow(result.error)}\n`);
53
+ continue;
54
+ }
55
+ const displayText = result.displayValue ?? String(result.value);
56
+ const enteredRows = countTerminalRows([` → ${raw}`], getColumns());
57
+ output.write(`\x1b[${enteredRows}A\r\x1b[J ${f.boldGreen('→')} ${f.boldGreen(displayText)}\n`);
58
+ return result.value;
59
+ }
60
+ }
61
+ const rl = readlinePromises.createInterface({ input, output });
62
+ try {
63
+ for (;;) {
64
+ const raw = await rl.question(` ${f.boldCyan('→')} `);
65
+ const result = await options.validate(raw);
66
+ if (!result.ok) {
67
+ output.write(` ${f.yellow(result.error)}\n`);
68
+ continue;
69
+ }
70
+ const displayText = result.displayValue ?? String(result.value);
71
+ output.write(` ${f.boldGreen('→')} ${f.boldGreen(displayText)}\n`);
72
+ return result.value;
73
+ }
74
+ }
75
+ catch (err) {
76
+ const code = err?.code;
77
+ if (code === 'ERR_USE_AFTER_CLOSE') {
78
+ throw new PromptCanceledError();
79
+ }
80
+ throw err;
81
+ }
82
+ finally {
83
+ rl.close();
84
+ }
85
+ }
86
+ export async function promptTextWithIO(question, defaultValue, io = {}) {
87
+ return promptValidatedTextWithIO(question, {
88
+ defaultValue,
89
+ io,
90
+ validate(raw) {
91
+ const trimmed = raw.trim();
92
+ const value = trimmed || defaultValue || '';
93
+ return { ok: true, value, displayValue: value || '(empty)' };
94
+ },
95
+ });
96
+ }
97
+ export async function promptText(question, defaultValue) {
98
+ return promptTextWithIO(question, defaultValue);
99
+ }
@@ -0,0 +1,165 @@
1
+ import readline from 'node:readline';
2
+ import { createFormatter } from '../format.js';
3
+ import { PromptCanceledError, countTerminalRows, } from './types.js';
4
+ /**
5
+ * Shared raw-mode TTY viewport, ANSI redraw, resize/SIGINT cleanup, and navigation engine
6
+ * powering both single-select and multi-select interactive prompts.
7
+ */
8
+ export function runInteractiveListPrompt(config) {
9
+ const { question, itemCount, initialCursor, reserveRows, input, output, renderActiveLines, renderConfirmedLines, getConfirmedValue, onBeforeNavigate, onCustomKey, } = config;
10
+ const f = createFormatter(output);
11
+ readline.emitKeypressEvents(input);
12
+ let cursorIndex = initialCursor;
13
+ let windowStart = 0;
14
+ let lastRenderedRows = 0;
15
+ let settled = false;
16
+ const getColumns = () => Math.max(20, output.columns || 80);
17
+ const getMaxVisible = () => {
18
+ const termRows = output.rows || 24;
19
+ const available = Math.max(3, termRows - reserveRows);
20
+ return Math.min(itemCount, available, 12);
21
+ };
22
+ const syncWindow = (maxVisible) => {
23
+ if (itemCount <= maxVisible) {
24
+ windowStart = 0;
25
+ return;
26
+ }
27
+ if (cursorIndex < windowStart) {
28
+ windowStart = cursorIndex;
29
+ }
30
+ else if (cursorIndex >= windowStart + maxVisible) {
31
+ windowStart = cursorIndex - maxVisible + 1;
32
+ }
33
+ const maxStart = Math.max(0, itemCount - maxVisible);
34
+ if (windowStart > maxStart) {
35
+ windowStart = maxStart;
36
+ }
37
+ };
38
+ const erasePrevious = () => {
39
+ if (lastRenderedRows <= 0)
40
+ return '';
41
+ return `\x1b[${lastRenderedRows}A\r\x1b[J`;
42
+ };
43
+ const renderActive = (hideCursor) => {
44
+ const columns = getColumns();
45
+ const maxVisible = getMaxVisible();
46
+ syncWindow(maxVisible);
47
+ const windowEnd = Math.min(itemCount, windowStart + maxVisible);
48
+ const lines = renderActiveLines({
49
+ cursorIndex,
50
+ windowStart,
51
+ windowEnd,
52
+ fmt: f,
53
+ });
54
+ const prefix = `${hideCursor ? '\x1b[?25l' : ''}${erasePrevious()}`;
55
+ output.write(`${prefix}${lines.join('\n')}\n`);
56
+ lastRenderedRows = countTerminalRows(lines, columns);
57
+ };
58
+ const renderFinal = (lines) => {
59
+ const prefix = erasePrevious();
60
+ output.write(`${prefix}${lines.join('\n')}\n\x1b[?25h`);
61
+ lastRenderedRows = 0;
62
+ };
63
+ const wasRaw = Boolean(input.isRaw);
64
+ input.setRawMode?.(true);
65
+ input.resume();
66
+ return new Promise((resolve, reject) => {
67
+ const cleanup = () => {
68
+ input.removeListener('keypress', onKeypress);
69
+ input.removeListener('end', onEnd);
70
+ output.removeListener('resize', onResize);
71
+ process.removeListener('SIGINT', onSigint);
72
+ try {
73
+ input.setRawMode?.(wasRaw);
74
+ }
75
+ catch {
76
+ // Ignore if stream already closed
77
+ }
78
+ input.pause();
79
+ };
80
+ const cancel = () => {
81
+ if (settled)
82
+ return;
83
+ settled = true;
84
+ cleanup();
85
+ renderFinal([
86
+ `${f.cyan('◆')} ${f.bold(question)}`,
87
+ ` ${f.red('×')} ${f.dim('Canceled')}`,
88
+ ]);
89
+ reject(new PromptCanceledError());
90
+ };
91
+ const confirm = () => {
92
+ if (settled)
93
+ return;
94
+ settled = true;
95
+ cleanup();
96
+ renderFinal(renderConfirmedLines(cursorIndex, f));
97
+ resolve(getConfirmedValue(cursorIndex));
98
+ };
99
+ const onResize = () => {
100
+ if (settled)
101
+ return;
102
+ renderActive(false);
103
+ };
104
+ const onSigint = () => {
105
+ cancel();
106
+ };
107
+ const onEnd = () => {
108
+ cancel();
109
+ };
110
+ const onKeypress = (str, key) => {
111
+ if (settled)
112
+ return;
113
+ if (str === '\u0003' || (key?.ctrl && key.name === 'c') || key?.name === 'escape') {
114
+ cancel();
115
+ return;
116
+ }
117
+ if (key?.name === 'return' || key?.name === 'enter') {
118
+ confirm();
119
+ return;
120
+ }
121
+ if (key?.name === 'up' || (!key?.ctrl && !key?.meta && key?.name === 'k')) {
122
+ onBeforeNavigate?.();
123
+ cursorIndex = (cursorIndex - 1 + itemCount) % itemCount;
124
+ renderActive(false);
125
+ return;
126
+ }
127
+ if (key?.name === 'down' || (!key?.ctrl && !key?.meta && key?.name === 'j')) {
128
+ onBeforeNavigate?.();
129
+ cursorIndex = (cursorIndex + 1) % itemCount;
130
+ renderActive(false);
131
+ return;
132
+ }
133
+ if (key?.name === 'home' || key?.name === 'pageup') {
134
+ onBeforeNavigate?.();
135
+ if (cursorIndex !== 0) {
136
+ cursorIndex = 0;
137
+ renderActive(false);
138
+ }
139
+ return;
140
+ }
141
+ if (key?.name === 'end' || key?.name === 'pagedown') {
142
+ onBeforeNavigate?.();
143
+ if (cursorIndex !== itemCount - 1) {
144
+ cursorIndex = itemCount - 1;
145
+ renderActive(false);
146
+ }
147
+ return;
148
+ }
149
+ onCustomKey?.(str, key, {
150
+ cursorIndex,
151
+ setCursorIndex(nextIdx) {
152
+ cursorIndex = nextIdx;
153
+ },
154
+ rerender: () => renderActive(false),
155
+ confirm,
156
+ cancel,
157
+ });
158
+ };
159
+ input.on('keypress', onKeypress);
160
+ input.once('end', onEnd);
161
+ output.on('resize', onResize);
162
+ process.on('SIGINT', onSigint);
163
+ renderActive(true);
164
+ });
165
+ }
@@ -0,0 +1,35 @@
1
+ import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
2
+ import { createFormatter, stripAnsi } from '../format.js';
3
+ export class PromptCanceledError extends Error {
4
+ constructor() {
5
+ super('Prompt canceled by user.');
6
+ this.name = 'PromptCanceledError';
7
+ }
8
+ }
9
+ export function isPromptCanceledError(error) {
10
+ return error instanceof PromptCanceledError;
11
+ }
12
+ export function isInteractive() {
13
+ return Boolean(defaultInput.isTTY && defaultOutput.isTTY);
14
+ }
15
+ export function canUseInteractiveTty(input, output, term) {
16
+ return (Boolean(input.isTTY) &&
17
+ Boolean(output.isTTY) &&
18
+ typeof input.setRawMode === 'function' &&
19
+ term !== 'dumb');
20
+ }
21
+ export function countTerminalRows(lines, columns) {
22
+ const safeCols = Math.max(1, columns);
23
+ let total = 0;
24
+ for (const rawLine of lines) {
25
+ for (const subLine of rawLine.split('\n')) {
26
+ const visibleLength = stripAnsi(subLine).length;
27
+ total += visibleLength === 0 ? 1 : Math.ceil(visibleLength / safeCols);
28
+ }
29
+ }
30
+ return total;
31
+ }
32
+ export function formatQuestionHeader(question, defaultValue, f) {
33
+ const hint = defaultValue ? ` ${f.dim(`(${defaultValue})`)}` : '';
34
+ return `${f.cyan('◆')} ${f.bold(question)}${hint}`;
35
+ }