react-devbelt 0.1.0 → 0.3.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/cli.js ADDED
@@ -0,0 +1,2174 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+
32
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
33
+ var require_picocolors = __commonJS({
34
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
35
+ "use strict";
36
+ var p = process || {};
37
+ var argv = p.argv || [];
38
+ var env = p.env || {};
39
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
40
+ var formatter = (open, close, replace = open) => (input) => {
41
+ let string = "" + input, index = string.indexOf(close, open.length);
42
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
43
+ };
44
+ var replaceClose = (string, close, replace, index) => {
45
+ let result = "", cursor2 = 0;
46
+ do {
47
+ result += string.substring(cursor2, index) + replace;
48
+ cursor2 = index + close.length;
49
+ index = string.indexOf(close, cursor2);
50
+ } while (~index);
51
+ return result + string.substring(cursor2);
52
+ };
53
+ var createColors = (enabled = isColorSupported) => {
54
+ let f = enabled ? formatter : () => String;
55
+ return {
56
+ isColorSupported: enabled,
57
+ reset: f("\x1B[0m", "\x1B[0m"),
58
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
59
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
60
+ italic: f("\x1B[3m", "\x1B[23m"),
61
+ underline: f("\x1B[4m", "\x1B[24m"),
62
+ inverse: f("\x1B[7m", "\x1B[27m"),
63
+ hidden: f("\x1B[8m", "\x1B[28m"),
64
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
65
+ black: f("\x1B[30m", "\x1B[39m"),
66
+ red: f("\x1B[31m", "\x1B[39m"),
67
+ green: f("\x1B[32m", "\x1B[39m"),
68
+ yellow: f("\x1B[33m", "\x1B[39m"),
69
+ blue: f("\x1B[34m", "\x1B[39m"),
70
+ magenta: f("\x1B[35m", "\x1B[39m"),
71
+ cyan: f("\x1B[36m", "\x1B[39m"),
72
+ white: f("\x1B[37m", "\x1B[39m"),
73
+ gray: f("\x1B[90m", "\x1B[39m"),
74
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
75
+ bgRed: f("\x1B[41m", "\x1B[49m"),
76
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
77
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
78
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
79
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
80
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
81
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
82
+ blackBright: f("\x1B[90m", "\x1B[39m"),
83
+ redBright: f("\x1B[91m", "\x1B[39m"),
84
+ greenBright: f("\x1B[92m", "\x1B[39m"),
85
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
86
+ blueBright: f("\x1B[94m", "\x1B[39m"),
87
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
88
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
89
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
90
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
91
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
92
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
93
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
94
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
95
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
96
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
97
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
98
+ };
99
+ };
100
+ module.exports = createColors();
101
+ module.exports.createColors = createColors;
102
+ }
103
+ });
104
+
105
+ // src/cli/index.ts
106
+ import { mkdirSync, writeFileSync } from "fs";
107
+ import { dirname as dirname4, join as join4, resolve } from "path";
108
+ import { parseArgs } from "util";
109
+
110
+ // ../../node_modules/.pnpm/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs
111
+ import { styleText } from "util";
112
+ import { stdout, stdin } from "process";
113
+ import * as f$1 from "readline";
114
+ import f__default from "readline";
115
+
116
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js
117
+ var getCodePointsLength = /* @__PURE__ */ (() => {
118
+ const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
119
+ return (input) => {
120
+ let surrogatePairsNr = 0;
121
+ SURROGATE_PAIR_RE.lastIndex = 0;
122
+ while (SURROGATE_PAIR_RE.test(input)) {
123
+ surrogatePairsNr += 1;
124
+ }
125
+ return input.length - surrogatePairsNr;
126
+ };
127
+ })();
128
+ var isFullWidth = (x) => {
129
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
130
+ };
131
+ var isWideNotCJKTNotEmoji = (x) => {
132
+ return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
133
+ };
134
+
135
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js
136
+ var ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
137
+ var CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
138
+ var CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu;
139
+ var TAB_RE = /\t{1,1000}/y;
140
+ var EMOJI_RE = new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*", "yu");
141
+ var LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
142
+ var MODIFIER_RE = new RegExp("\\p{M}+", "gu");
143
+ var NO_TRUNCATION = { limit: Infinity, ellipsis: "" };
144
+ var getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
145
+ const LIMIT = truncationOptions.limit ?? Infinity;
146
+ const ELLIPSIS = truncationOptions.ellipsis ?? "";
147
+ const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);
148
+ const ANSI_WIDTH = 0;
149
+ const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
150
+ const TAB_WIDTH = widthOptions.tabWidth ?? 8;
151
+ const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
152
+ const FULL_WIDTH_WIDTH = 2;
153
+ const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
154
+ const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
155
+ const PARSE_BLOCKS = [
156
+ [LATIN_RE, REGULAR_WIDTH],
157
+ [ANSI_RE, ANSI_WIDTH],
158
+ [CONTROL_RE, CONTROL_WIDTH],
159
+ [TAB_RE, TAB_WIDTH],
160
+ [EMOJI_RE, EMOJI_WIDTH],
161
+ [CJKT_WIDE_RE, WIDE_WIDTH]
162
+ ];
163
+ let indexPrev = 0;
164
+ let index = 0;
165
+ let length = input.length;
166
+ let lengthExtra = 0;
167
+ let truncationEnabled = false;
168
+ let truncationIndex = length;
169
+ let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
170
+ let unmatchedStart = 0;
171
+ let unmatchedEnd = 0;
172
+ let width = 0;
173
+ let widthExtra = 0;
174
+ outer: while (true) {
175
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
176
+ const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
177
+ lengthExtra = 0;
178
+ for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
179
+ const codePoint = char.codePointAt(0) || 0;
180
+ if (isFullWidth(codePoint)) {
181
+ widthExtra = FULL_WIDTH_WIDTH;
182
+ } else if (isWideNotCJKTNotEmoji(codePoint)) {
183
+ widthExtra = WIDE_WIDTH;
184
+ } else {
185
+ widthExtra = REGULAR_WIDTH;
186
+ }
187
+ if (width + widthExtra > truncationLimit) {
188
+ truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
189
+ }
190
+ if (width + widthExtra > LIMIT) {
191
+ truncationEnabled = true;
192
+ break outer;
193
+ }
194
+ lengthExtra += char.length;
195
+ width += widthExtra;
196
+ }
197
+ unmatchedStart = unmatchedEnd = 0;
198
+ }
199
+ if (index >= length) {
200
+ break outer;
201
+ }
202
+ for (let i2 = 0, l = PARSE_BLOCKS.length; i2 < l; i2++) {
203
+ const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i2];
204
+ BLOCK_RE.lastIndex = index;
205
+ if (BLOCK_RE.test(input)) {
206
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
207
+ widthExtra = lengthExtra * BLOCK_WIDTH;
208
+ if (width + widthExtra > truncationLimit) {
209
+ truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
210
+ }
211
+ if (width + widthExtra > LIMIT) {
212
+ truncationEnabled = true;
213
+ break outer;
214
+ }
215
+ width += widthExtra;
216
+ unmatchedStart = indexPrev;
217
+ unmatchedEnd = index;
218
+ index = indexPrev = BLOCK_RE.lastIndex;
219
+ continue outer;
220
+ }
221
+ }
222
+ index += 1;
223
+ }
224
+ return {
225
+ width: truncationEnabled ? truncationLimit : width,
226
+ index: truncationEnabled ? truncationIndex : length,
227
+ truncated: truncationEnabled,
228
+ ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
229
+ };
230
+ };
231
+ var dist_default = getStringTruncatedWidth;
232
+
233
+ // ../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js
234
+ var NO_TRUNCATION2 = {
235
+ limit: Infinity,
236
+ ellipsis: "",
237
+ ellipsisWidth: 0
238
+ };
239
+ var fastStringWidth = (input, options = {}) => {
240
+ return dist_default(input, NO_TRUNCATION2, options).width;
241
+ };
242
+ var dist_default2 = fastStringWidth;
243
+
244
+ // ../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js
245
+ var ESC = "\x1B";
246
+ var CSI = "\x9B";
247
+ var END_CODE = 39;
248
+ var ANSI_ESCAPE_BELL = "\x07";
249
+ var ANSI_CSI = "[";
250
+ var ANSI_OSC = "]";
251
+ var ANSI_SGR_TERMINATOR = "m";
252
+ var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
253
+ var GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
254
+ var getClosingCode = (openingCode) => {
255
+ if (openingCode >= 30 && openingCode <= 37)
256
+ return 39;
257
+ if (openingCode >= 90 && openingCode <= 97)
258
+ return 39;
259
+ if (openingCode >= 40 && openingCode <= 47)
260
+ return 49;
261
+ if (openingCode >= 100 && openingCode <= 107)
262
+ return 49;
263
+ if (openingCode === 1 || openingCode === 2)
264
+ return 22;
265
+ if (openingCode === 3)
266
+ return 23;
267
+ if (openingCode === 4)
268
+ return 24;
269
+ if (openingCode === 7)
270
+ return 27;
271
+ if (openingCode === 8)
272
+ return 28;
273
+ if (openingCode === 9)
274
+ return 29;
275
+ if (openingCode === 0)
276
+ return 0;
277
+ return void 0;
278
+ };
279
+ var wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
280
+ var wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
281
+ var wrapWord = (rows, word, columns) => {
282
+ const characters = word[Symbol.iterator]();
283
+ let isInsideEscape = false;
284
+ let isInsideLinkEscape = false;
285
+ let lastRow = rows.at(-1);
286
+ let visible = lastRow === void 0 ? 0 : dist_default2(lastRow);
287
+ let currentCharacter = characters.next();
288
+ let nextCharacter = characters.next();
289
+ let rawCharacterIndex = 0;
290
+ while (!currentCharacter.done) {
291
+ const character = currentCharacter.value;
292
+ const characterLength = dist_default2(character);
293
+ if (visible + characterLength <= columns) {
294
+ rows[rows.length - 1] += character;
295
+ } else {
296
+ rows.push(character);
297
+ visible = 0;
298
+ }
299
+ if (character === ESC || character === CSI) {
300
+ isInsideEscape = true;
301
+ isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
302
+ }
303
+ if (isInsideEscape) {
304
+ if (isInsideLinkEscape) {
305
+ if (character === ANSI_ESCAPE_BELL) {
306
+ isInsideEscape = false;
307
+ isInsideLinkEscape = false;
308
+ }
309
+ } else if (character === ANSI_SGR_TERMINATOR) {
310
+ isInsideEscape = false;
311
+ }
312
+ } else {
313
+ visible += characterLength;
314
+ if (visible === columns && !nextCharacter.done) {
315
+ rows.push("");
316
+ visible = 0;
317
+ }
318
+ }
319
+ currentCharacter = nextCharacter;
320
+ nextCharacter = characters.next();
321
+ rawCharacterIndex += character.length;
322
+ }
323
+ lastRow = rows.at(-1);
324
+ if (!visible && lastRow !== void 0 && lastRow.length && rows.length > 1) {
325
+ rows[rows.length - 2] += rows.pop();
326
+ }
327
+ };
328
+ var stringVisibleTrimSpacesRight = (string) => {
329
+ const words = string.split(" ");
330
+ let last = words.length;
331
+ while (last) {
332
+ if (dist_default2(words[last - 1])) {
333
+ break;
334
+ }
335
+ last--;
336
+ }
337
+ if (last === words.length) {
338
+ return string;
339
+ }
340
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
341
+ };
342
+ var exec = (string, columns, options = {}) => {
343
+ if (options.trim !== false && string.trim() === "") {
344
+ return "";
345
+ }
346
+ let returnValue = "";
347
+ let escapeCode;
348
+ let escapeUrl;
349
+ const words = string.split(" ");
350
+ let rows = [""];
351
+ let rowLength = 0;
352
+ for (let index = 0; index < words.length; index++) {
353
+ const word = words[index];
354
+ if (options.trim !== false) {
355
+ const row = rows.at(-1) ?? "";
356
+ const trimmed = row.trimStart();
357
+ if (row.length !== trimmed.length) {
358
+ rows[rows.length - 1] = trimmed;
359
+ rowLength = dist_default2(trimmed);
360
+ }
361
+ }
362
+ if (index !== 0) {
363
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
364
+ rows.push("");
365
+ rowLength = 0;
366
+ }
367
+ if (rowLength || options.trim === false) {
368
+ rows[rows.length - 1] += " ";
369
+ rowLength++;
370
+ }
371
+ }
372
+ const wordLength = dist_default2(word);
373
+ if (options.hard && wordLength > columns) {
374
+ const remainingColumns = columns - rowLength;
375
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
376
+ const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);
377
+ if (breaksStartingNextLine < breaksStartingThisLine) {
378
+ rows.push("");
379
+ }
380
+ wrapWord(rows, word, columns);
381
+ rowLength = dist_default2(rows.at(-1) ?? "");
382
+ continue;
383
+ }
384
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
385
+ if (options.wordWrap === false && rowLength < columns) {
386
+ wrapWord(rows, word, columns);
387
+ rowLength = dist_default2(rows.at(-1) ?? "");
388
+ continue;
389
+ }
390
+ rows.push("");
391
+ rowLength = 0;
392
+ }
393
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
394
+ wrapWord(rows, word, columns);
395
+ rowLength = dist_default2(rows.at(-1) ?? "");
396
+ continue;
397
+ }
398
+ rows[rows.length - 1] += word;
399
+ rowLength += wordLength;
400
+ }
401
+ if (options.trim !== false) {
402
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
403
+ }
404
+ const preString = rows.join("\n");
405
+ let inSurrogate = false;
406
+ for (let i2 = 0; i2 < preString.length; i2++) {
407
+ const character = preString[i2];
408
+ returnValue += character;
409
+ if (!inSurrogate) {
410
+ inSurrogate = character >= "\uD800" && character <= "\uDBFF";
411
+ if (inSurrogate) {
412
+ continue;
413
+ }
414
+ } else {
415
+ inSurrogate = false;
416
+ }
417
+ if (character === ESC || character === CSI) {
418
+ GROUP_REGEX.lastIndex = i2 + 1;
419
+ const groupsResult = GROUP_REGEX.exec(preString);
420
+ const groups = groupsResult?.groups;
421
+ if (groups?.code !== void 0) {
422
+ const code = Number.parseFloat(groups.code);
423
+ escapeCode = code === END_CODE ? void 0 : code;
424
+ } else if (groups?.uri !== void 0) {
425
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
426
+ }
427
+ }
428
+ if (preString[i2 + 1] === "\n") {
429
+ if (escapeUrl) {
430
+ returnValue += wrapAnsiHyperlink("");
431
+ }
432
+ const closingCode = escapeCode ? getClosingCode(escapeCode) : void 0;
433
+ if (escapeCode && closingCode) {
434
+ returnValue += wrapAnsiCode(closingCode);
435
+ }
436
+ } else if (character === "\n") {
437
+ if (escapeCode && getClosingCode(escapeCode)) {
438
+ returnValue += wrapAnsiCode(escapeCode);
439
+ }
440
+ if (escapeUrl) {
441
+ returnValue += wrapAnsiHyperlink(escapeUrl);
442
+ }
443
+ }
444
+ }
445
+ return returnValue;
446
+ };
447
+ var CRLF_OR_LF = /\r?\n/;
448
+ function wrapAnsi(string, columns, options) {
449
+ return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join("\n");
450
+ }
451
+
452
+ // ../../node_modules/.pnpm/sisteransi@2.0.0/node_modules/sisteransi/dist/index.js
453
+ var ESC2 = "\x1B";
454
+ var CSI2 = `${ESC2}[`;
455
+ var cursor = {
456
+ to(x, y) {
457
+ if (!y)
458
+ return `${CSI2}${x + 1}G`;
459
+ return `${CSI2}${y + 1};${x + 1}H`;
460
+ },
461
+ move(x, y) {
462
+ let ret = "";
463
+ if (x < 0)
464
+ ret += `${CSI2}${-x}D`;
465
+ else if (x > 0)
466
+ ret += `${CSI2}${x}C`;
467
+ if (y < 0)
468
+ ret += `${CSI2}${-y}A`;
469
+ else if (y > 0)
470
+ ret += `${CSI2}${y}B`;
471
+ return ret;
472
+ },
473
+ up: (count = 1) => `${CSI2}${count}A`,
474
+ down: (count = 1) => `${CSI2}${count}B`,
475
+ forward: (count = 1) => `${CSI2}${count}C`,
476
+ backward: (count = 1) => `${CSI2}${count}D`,
477
+ nextLine: (count = 1) => `${CSI2}E`.repeat(count),
478
+ prevLine: (count = 1) => `${CSI2}F`.repeat(count),
479
+ left: `${CSI2}G`,
480
+ hide: `${CSI2}?25l`,
481
+ show: `${CSI2}?25h`,
482
+ save: `${ESC2}7`,
483
+ restore: `${ESC2}8`
484
+ };
485
+ var erase = {
486
+ screen: `${CSI2}2J`,
487
+ up: (count = 1) => `${CSI2}1J`.repeat(count),
488
+ down: (count = 1) => `${CSI2}J`.repeat(count),
489
+ line: `${CSI2}2K`,
490
+ lineEnd: `${CSI2}K`,
491
+ lineStart: `${CSI2}1K`,
492
+ lines(count) {
493
+ let clear2 = "";
494
+ for (let i2 = 0; i2 < count; i2++)
495
+ clear2 += this.line + (i2 < count - 1 ? cursor.up() : "");
496
+ if (count)
497
+ clear2 += cursor.left;
498
+ return clear2;
499
+ }
500
+ };
501
+ var clear = {
502
+ screen: `${ESC2}c`
503
+ };
504
+
505
+ // ../../node_modules/.pnpm/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs
506
+ import { ReadStream } from "tty";
507
+ function findCursor(o, s, l) {
508
+ if (!l.some((r2) => !r2.disabled))
509
+ return o;
510
+ const t2 = o + s, n2 = Math.max(l.length - 1, 0), e = t2 < 0 ? n2 : t2 > n2 ? 0 : t2;
511
+ return l[e]?.disabled ? findCursor(e, s < 0 ? -1 : 1, l) : e;
512
+ }
513
+ var a$1 = ["up", "down", "left", "right", "space", "enter", "cancel"];
514
+ var t = [
515
+ "January",
516
+ "February",
517
+ "March",
518
+ "April",
519
+ "May",
520
+ "June",
521
+ "July",
522
+ "August",
523
+ "September",
524
+ "October",
525
+ "November",
526
+ "December"
527
+ ];
528
+ var settings = {
529
+ actions: new Set(a$1),
530
+ aliases: /* @__PURE__ */ new Map([
531
+ // vim support
532
+ ["k", "up"],
533
+ ["j", "down"],
534
+ ["h", "left"],
535
+ ["l", "right"],
536
+ ["", "cancel"],
537
+ // opinionated defaults!
538
+ ["escape", "cancel"]
539
+ ]),
540
+ messages: {
541
+ cancel: "Canceled",
542
+ error: "Something went wrong"
543
+ },
544
+ withGuide: true,
545
+ accessible: void 0,
546
+ date: {
547
+ monthNames: [...t],
548
+ messages: {
549
+ required: "Please enter a valid date",
550
+ invalidMonth: "There are only 12 months in a year",
551
+ invalidDay: (n2, e) => `There are only ${n2} days in ${e}`,
552
+ afterMin: (n2) => `Date must be on or after ${n2.toISOString().slice(0, 10)}`,
553
+ beforeMax: (n2) => `Date must be on or before ${n2.toISOString().slice(0, 10)}`
554
+ }
555
+ }
556
+ };
557
+ function isAccessible(n2) {
558
+ if (n2 !== void 0) return n2;
559
+ if (settings.accessible !== void 0) return settings.accessible;
560
+ const e = process.env.ACCESSIBLE;
561
+ return e !== void 0 && e !== "" && e !== "0" && e !== "false";
562
+ }
563
+ function isActionKey(n2, e) {
564
+ if (typeof n2 == "string")
565
+ return settings.aliases.get(n2) === e;
566
+ for (const s of n2)
567
+ if (s !== void 0 && isActionKey(s, e))
568
+ return true;
569
+ return false;
570
+ }
571
+ function diffLines(i2, s) {
572
+ if (i2 === s) return;
573
+ const e = i2.split(`
574
+ `), t2 = s.split(`
575
+ `), r2 = Math.max(e.length, t2.length), f = [];
576
+ for (let n2 = 0; n2 < r2; n2++)
577
+ e[n2] !== t2[n2] && f.push(n2);
578
+ return {
579
+ lines: f,
580
+ numLinesBefore: e.length,
581
+ numLinesAfter: t2.length,
582
+ numLines: r2
583
+ };
584
+ }
585
+ var R = globalThis.process.platform.startsWith("win");
586
+ var CANCEL_SYMBOL = /* @__PURE__ */ Symbol("clack:cancel");
587
+ function isCancel(e) {
588
+ return e === CANCEL_SYMBOL;
589
+ }
590
+ function setRawMode(e, r2) {
591
+ const o = e;
592
+ o.isTTY && o.setRawMode(r2);
593
+ }
594
+ function block({
595
+ input: e = stdin,
596
+ output: r2 = stdout,
597
+ overwrite: o = true,
598
+ hideCursor: n2 = true
599
+ } = {}) {
600
+ const s = f$1.createInterface({
601
+ input: e,
602
+ output: r2,
603
+ prompt: "",
604
+ tabSize: 1
605
+ });
606
+ f$1.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
607
+ const t2 = (l, { name: i2, sequence: p }) => {
608
+ const w = String(l);
609
+ if (isActionKey([w, i2, p], "cancel")) {
610
+ n2 && r2.write(cursor.show), process.exit(0);
611
+ return;
612
+ }
613
+ if (!o) return;
614
+ const c2 = i2 === "return" ? 0 : -1, a2 = i2 === "return" ? -1 : 0;
615
+ f$1.moveCursor(r2, c2, a2, () => {
616
+ f$1.clearLine(r2, 1, () => {
617
+ e.once("keypress", t2);
618
+ });
619
+ });
620
+ };
621
+ return n2 && r2.write(cursor.hide), e.once("keypress", t2), () => {
622
+ e.off("keypress", t2), n2 && r2.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
623
+ };
624
+ }
625
+ var getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
626
+ var getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
627
+ function wrapTextWithPrefix(e, r2, o, n2 = o, s = o, t2) {
628
+ const l = getColumns(e ?? stdout), i2 = dist_default2(o);
629
+ return wrapAnsi(r2, l - i2, {
630
+ hard: true,
631
+ trim: false
632
+ }).split(`
633
+ `).map((c2, a2, g) => {
634
+ const m2 = t2 ? t2(c2, a2) : c2;
635
+ return a2 === 0 ? `${n2}${m2}` : a2 === g.length - 1 ? `${s}${m2}` : `${o}${m2}`;
636
+ }).join(`
637
+ `);
638
+ }
639
+ function runValidation(e, a2) {
640
+ if ("~standard" in e) {
641
+ const n2 = e["~standard"].validate(a2);
642
+ return n2 instanceof Promise ? n2.then((r2) => r2.issues?.at(0)?.message) : n2.issues?.at(0)?.message;
643
+ }
644
+ return e(a2);
645
+ }
646
+ var C$1 = class C {
647
+ input;
648
+ output;
649
+ _abortSignal;
650
+ rl;
651
+ opts;
652
+ _render;
653
+ _track = false;
654
+ _prevFrame = "";
655
+ _subscribers = /* @__PURE__ */ new Map();
656
+ _cursor = 0;
657
+ state = "initial";
658
+ error = "";
659
+ value;
660
+ userInput = "";
661
+ /**
662
+ * Whether accessible (static, screen-reader friendly) output is enabled for
663
+ * this prompt, resolved from the `accessible` option, the global setting,
664
+ * and the `ACCESSIBLE` env var.
665
+ */
666
+ get accessible() {
667
+ return isAccessible(this.opts.accessible);
668
+ }
669
+ constructor(t2, e = true) {
670
+ const { input: i2 = stdin, output: s = stdout, render: r2, signal: n2, ...o } = t2;
671
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r2.bind(this), this._track = e, this._abortSignal = n2, this.input = i2, this.output = s;
672
+ }
673
+ /**
674
+ * Unsubscribe all listeners
675
+ */
676
+ unsubscribe() {
677
+ this._subscribers.clear();
678
+ }
679
+ /**
680
+ * Set a subscriber with opts
681
+ * @param event - The event name
682
+ */
683
+ setSubscriber(t2, e) {
684
+ const i2 = this._subscribers.get(t2) ?? [];
685
+ i2.push(e), this._subscribers.set(t2, i2);
686
+ }
687
+ /**
688
+ * Subscribe to an event
689
+ * @param event - The event name
690
+ * @param cb - The callback
691
+ */
692
+ on(t2, e) {
693
+ this.setSubscriber(t2, { cb: e });
694
+ }
695
+ /**
696
+ * Subscribe to an event once
697
+ * @param event - The event name
698
+ * @param cb - The callback
699
+ */
700
+ once(t2, e) {
701
+ this.setSubscriber(t2, { cb: e, once: true });
702
+ }
703
+ /**
704
+ * Emit an event with data
705
+ * @param event - The event name
706
+ * @param data - The data to pass to the callback
707
+ */
708
+ emit(t2, ...e) {
709
+ const i2 = this._subscribers.get(t2) ?? [], s = [];
710
+ for (const r2 of i2)
711
+ r2.cb(...e), r2.once && s.push(() => i2.splice(i2.indexOf(r2), 1));
712
+ for (const r2 of s)
713
+ r2();
714
+ }
715
+ prompt() {
716
+ return new Promise((t2) => {
717
+ if (this._abortSignal) {
718
+ if (this._abortSignal.aborted)
719
+ return this.state = "cancel", this.close(), t2(CANCEL_SYMBOL);
720
+ this._abortSignal.addEventListener(
721
+ "abort",
722
+ () => {
723
+ this.state = "cancel", this.close();
724
+ },
725
+ { once: true }
726
+ );
727
+ }
728
+ this.rl = f__default.createInterface({
729
+ input: this.input,
730
+ tabSize: 2,
731
+ prompt: "",
732
+ escapeCodeTimeout: 50,
733
+ terminal: true
734
+ }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
735
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(this.value);
736
+ }), this.once("cancel", () => {
737
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(CANCEL_SYMBOL);
738
+ });
739
+ });
740
+ }
741
+ _isActionKey(t2, e) {
742
+ return t2 === " ";
743
+ }
744
+ _shouldSubmit(t2, e) {
745
+ return true;
746
+ }
747
+ _setValue(t2) {
748
+ this.value = t2, this.emit("value", this.value);
749
+ }
750
+ _setUserInput(t2, e) {
751
+ this.userInput = t2 ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
752
+ }
753
+ _clearUserInput() {
754
+ this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
755
+ }
756
+ async onKeypress(t2, e) {
757
+ if (this.state !== "validating") {
758
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t2, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t2 && (t2.toLowerCase() === "y" || t2.toLowerCase() === "n") && this.emit("confirm", t2.toLowerCase() === "y"), this.emit("key", t2, e), e?.name === "return" && this._shouldSubmit(t2, e)) {
759
+ if (this.opts.validate) {
760
+ const i2 = runValidation(this.opts.validate, this.value);
761
+ let s;
762
+ i2 instanceof Promise ? (this.state = "validating", this.render(), s = await i2) : s = i2, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
763
+ }
764
+ this.state !== "error" && (this.state = "submit");
765
+ }
766
+ isActionKey([t2, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
767
+ }
768
+ }
769
+ close() {
770
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
771
+ `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
772
+ }
773
+ restoreCursor() {
774
+ const t2 = wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split(`
775
+ `).length - 1;
776
+ this.output.write(cursor.move(-999, t2 * -1));
777
+ }
778
+ render() {
779
+ const t2 = wrapAnsi(this._render(this) ?? "", getColumns(this.output), {
780
+ hard: true,
781
+ trim: false
782
+ });
783
+ if (t2 !== this._prevFrame) {
784
+ if (this.state === "initial")
785
+ this.output.write(cursor.hide);
786
+ else {
787
+ const e = diffLines(this._prevFrame, t2), i2 = getRows(this.output);
788
+ if (this.restoreCursor(), e) {
789
+ const s = Math.max(0, e.numLinesAfter - i2), r2 = Math.max(0, e.numLinesBefore - i2);
790
+ let n2 = e.lines.find((o) => o >= s);
791
+ if (n2 === void 0) {
792
+ this._prevFrame = t2;
793
+ return;
794
+ }
795
+ if (e.lines.length === 1) {
796
+ this.output.write(cursor.move(0, n2 - r2)), this.output.write(erase.lines(1));
797
+ const o = t2.split(`
798
+ `);
799
+ this.output.write(o[n2]), this._prevFrame = t2, this.output.write(cursor.move(0, o.length - n2 - 1));
800
+ return;
801
+ } else if (e.lines.length > 1) {
802
+ if (s < r2)
803
+ n2 = s;
804
+ else {
805
+ const h2 = n2 - r2;
806
+ h2 > 0 && this.output.write(cursor.move(0, h2));
807
+ }
808
+ this.output.write(erase.down());
809
+ const m2 = t2.split(`
810
+ `).slice(n2);
811
+ this.output.write(m2.join(`
812
+ `)), this._prevFrame = t2;
813
+ return;
814
+ }
815
+ }
816
+ this.output.write(erase.down());
817
+ }
818
+ this.output.write(t2), this.state === "initial" && (this.state = "active"), this._prevFrame = t2;
819
+ }
820
+ }
821
+ };
822
+ var r = class extends C$1 {
823
+ get cursor() {
824
+ return this.value ? 0 : 1;
825
+ }
826
+ get _value() {
827
+ return this.cursor === 0;
828
+ }
829
+ constructor(t2) {
830
+ super(t2, false), this.value = !!t2.initialValue, this.on("userInput", () => {
831
+ this.value = this._value;
832
+ }), this.on("confirm", (i2) => {
833
+ this.output.write(cursor.move(0, -1)), this.value = i2, this.state = "submit", this.close();
834
+ }), this.on("cursor", () => {
835
+ this.value = !this.value;
836
+ });
837
+ }
838
+ };
839
+ var a = class extends C$1 {
840
+ options;
841
+ cursor = 0;
842
+ get _value() {
843
+ return this.options[this.cursor]?.value;
844
+ }
845
+ get _enabledOptions() {
846
+ return this.options.filter((e) => e.disabled !== true);
847
+ }
848
+ toggleAll() {
849
+ const e = this._enabledOptions, i2 = this.value !== void 0 && this.value.length === e.length;
850
+ this.value = i2 ? [] : e.map((t2) => t2.value);
851
+ }
852
+ toggleInvert() {
853
+ const e = this.value;
854
+ if (!e)
855
+ return;
856
+ const i2 = this._enabledOptions.filter((t2) => !e.includes(t2.value));
857
+ this.value = i2.map((t2) => t2.value);
858
+ }
859
+ toggleValue() {
860
+ this.value === void 0 && (this.value = []);
861
+ const e = this.value.includes(this._value);
862
+ this.value = e ? this.value.filter((i2) => i2 !== this._value) : [...this.value, this._value];
863
+ }
864
+ constructor(e) {
865
+ super(e, false), this.options = e.options, this.value = [...e.initialValues ?? []];
866
+ const i2 = Math.max(
867
+ this.options.findIndex(({ value: t2 }) => t2 === e.cursorAt),
868
+ 0
869
+ );
870
+ this.cursor = this.options[i2]?.disabled ? findCursor(i2, 1, this.options) : i2, this.on("key", (t2, s) => {
871
+ s.name === "a" && this.toggleAll(), s.name === "i" && this.toggleInvert(), s.name === void 0 && t2 === "\u3000" && this.toggleValue();
872
+ }), this.on("cursor", (t2) => {
873
+ switch (t2) {
874
+ case "left":
875
+ case "up":
876
+ this.cursor = findCursor(this.cursor, -1, this.options);
877
+ break;
878
+ case "down":
879
+ case "right":
880
+ this.cursor = findCursor(this.cursor, 1, this.options);
881
+ break;
882
+ case "space":
883
+ this.toggleValue();
884
+ break;
885
+ }
886
+ });
887
+ }
888
+ };
889
+
890
+ // ../../node_modules/.pnpm/@clack+prompts@1.9.0/node_modules/@clack/prompts/dist/index.mjs
891
+ import { styleText as styleText2, stripVTControlCharacters } from "util";
892
+ import process$1 from "process";
893
+ import { existsSync, lstatSync, readdirSync } from "fs";
894
+ import { dirname, join } from "path";
895
+ function isUnicodeSupported() {
896
+ if (process$1.platform !== "win32") {
897
+ return process$1.env.TERM !== "linux";
898
+ }
899
+ return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
900
+ }
901
+ var unicode = isUnicodeSupported();
902
+ var isCI = () => process.env.CI === "true";
903
+ var unicodeOr = (e, o) => unicode ? e : o;
904
+ var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
905
+ var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
906
+ var S_STEP_ERROR = unicodeOr("\u25B2", "x");
907
+ var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
908
+ var S_BAR_START = unicodeOr("\u250C", "T");
909
+ var S_BAR = unicodeOr("\u2502", "|");
910
+ var S_BAR_END = unicodeOr("\u2514", "\u2014");
911
+ var S_BAR_START_RIGHT = unicodeOr("\u2510", "T");
912
+ var S_BAR_END_RIGHT = unicodeOr("\u2518", "\u2014");
913
+ var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
914
+ var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
915
+ var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
916
+ var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
917
+ var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
918
+ var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
919
+ var S_BAR_H = unicodeOr("\u2500", "-");
920
+ var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
921
+ var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
922
+ var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
923
+ var S_CORNER_BOTTOM_LEFT = unicodeOr("\u2570", "+");
924
+ var S_CORNER_TOP_LEFT = unicodeOr("\u256D", "+");
925
+ var S_INFO = unicodeOr("\u25CF", "\u2022");
926
+ var S_SUCCESS = unicodeOr("\u25C6", "*");
927
+ var S_WARN = unicodeOr("\u25B2", "!");
928
+ var S_ERROR = unicodeOr("\u25A0", "x");
929
+ var symbol = (e) => {
930
+ switch (e) {
931
+ case "initial":
932
+ case "active":
933
+ return styleText2("cyan", S_STEP_ACTIVE);
934
+ case "cancel":
935
+ return styleText2("red", S_STEP_CANCEL);
936
+ case "error":
937
+ return styleText2("yellow", S_STEP_ERROR);
938
+ case "submit":
939
+ return styleText2("green", S_STEP_SUBMIT);
940
+ case "validating":
941
+ return styleText2("dim", S_STEP_ACTIVE);
942
+ }
943
+ };
944
+ var symbolBar = (e) => {
945
+ switch (e) {
946
+ case "initial":
947
+ case "active":
948
+ return styleText2("cyan", S_BAR);
949
+ case "cancel":
950
+ return styleText2("red", S_BAR);
951
+ case "error":
952
+ return styleText2("yellow", S_BAR);
953
+ case "submit":
954
+ return styleText2("green", S_BAR);
955
+ }
956
+ };
957
+ function formatInstructionFooter(e, o, r2) {
958
+ const s = r2 ? `${styleText2("cyan", S_BAR)} ` : "", n2 = wrapTextWithPrefix(e, o.join(" \u2022 "), s).split(`
959
+ `);
960
+ return r2 && n2.push(styleText2("cyan", S_BAR_END)), n2;
961
+ }
962
+ var E$1 = (l, e, w, p, b, C3 = false) => {
963
+ let r2 = e, O = 0;
964
+ if (C3)
965
+ for (let i2 = p - 1; i2 >= w; i2--) {
966
+ const m2 = l[i2];
967
+ if (m2 && (r2 -= m2.length), O++, r2 <= b) break;
968
+ }
969
+ else
970
+ for (let i2 = w; i2 < p; i2++) {
971
+ const m2 = l[i2];
972
+ if (m2 && (r2 -= m2.length), O++, r2 <= b) break;
973
+ }
974
+ return { lineCount: r2, removals: O };
975
+ };
976
+ var limitOptions = ({
977
+ cursor: l,
978
+ options: e,
979
+ style: w,
980
+ output: p = process.stdout,
981
+ maxItems: b = Number.POSITIVE_INFINITY,
982
+ columnPadding: C3 = 0,
983
+ rowPadding: r2 = 4
984
+ }) => {
985
+ const i2 = getColumns(p) - C3, m2 = getRows(p), M = styleText2("dim", "..."), v = Math.max(m2 - r2, 0), a2 = Math.max(Math.min(b, v), 5);
986
+ let f = 0;
987
+ l >= a2 - 3 && (f = Math.max(
988
+ Math.min(l - a2 + 3, e.length - a2),
989
+ 0
990
+ ));
991
+ let d = a2 < e.length && f > 0, c2 = a2 < e.length && f + a2 < e.length;
992
+ const I = Math.min(
993
+ f + a2,
994
+ e.length
995
+ ), s = [];
996
+ let g = 0;
997
+ d && g++, c2 && g++;
998
+ const T = f + (d ? 1 : 0), W2 = I - (c2 ? 1 : 0);
999
+ for (let t2 = T; t2 < W2; t2++) {
1000
+ const n2 = e[t2], o = n2 !== void 0 ? w(n2, t2 === l) : "", h2 = wrapAnsi(o, i2, {
1001
+ hard: true,
1002
+ trim: false
1003
+ }).split(`
1004
+ `);
1005
+ s.push(h2), g += h2.length;
1006
+ }
1007
+ if (g > v) {
1008
+ let t2 = 0, n2 = 0, o = g;
1009
+ const h2 = l - T;
1010
+ let u3 = v;
1011
+ const L = () => E$1(s, o, 0, h2, u3), y = () => E$1(
1012
+ s,
1013
+ o,
1014
+ h2 + 1,
1015
+ s.length,
1016
+ u3,
1017
+ true
1018
+ );
1019
+ d ? ({ lineCount: o, removals: t2 } = L(), o > u3 && (c2 || (u3 -= 1), { lineCount: o, removals: n2 } = y())) : (c2 || (u3 -= 1), { lineCount: o, removals: n2 } = y(), o > u3 && (u3 -= 1, { lineCount: o, removals: t2 } = L())), t2 > 0 && (d = true, s.splice(0, t2)), n2 > 0 && (c2 = true, s.splice(s.length - n2, n2));
1020
+ }
1021
+ const x = [];
1022
+ d && x.push(M);
1023
+ for (const t2 of s)
1024
+ for (const n2 of t2)
1025
+ x.push(n2);
1026
+ return c2 && x.push(M), x;
1027
+ };
1028
+ var confirm = (e) => {
1029
+ const a2 = e.active ?? "Yes", o = e.inactive ?? "No";
1030
+ return new r({
1031
+ active: a2,
1032
+ inactive: o,
1033
+ signal: e.signal,
1034
+ input: e.input,
1035
+ output: e.output,
1036
+ initialValue: e.initialValue ?? true,
1037
+ render() {
1038
+ const i2 = e.withGuide ?? settings.withGuide, u3 = `${symbol(this.state)} `, l = i2 ? `${styleText2("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(
1039
+ e.output,
1040
+ e.message,
1041
+ l,
1042
+ u3
1043
+ ), s = `${i2 ? `${styleText2("gray", S_BAR)}
1044
+ ` : ""}${f}
1045
+ `, c2 = this.value ? a2 : o;
1046
+ switch (this.state) {
1047
+ case "submit": {
1048
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1049
+ return `${s}${r2}${styleText2("dim", c2)}`;
1050
+ }
1051
+ case "cancel": {
1052
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1053
+ return `${s}${r2}${styleText2(["strikethrough", "dim"], c2)}${i2 ? `
1054
+ ${styleText2("gray", S_BAR)}` : ""}`;
1055
+ }
1056
+ default: {
1057
+ const r2 = i2 ? `${styleText2("cyan", S_BAR)} ` : "", g = i2 ? styleText2("cyan", S_BAR_END) : "";
1058
+ return `${s}${r2}${this.value ? `${styleText2("green", S_RADIO_ACTIVE)} ${a2}` : `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", a2)}`}${e.vertical ? i2 ? `
1059
+ ${styleText2("cyan", S_BAR)} ` : `
1060
+ ` : ` ${styleText2("dim", "/")} `}${this.value ? `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", o)}` : `${styleText2("green", S_RADIO_ACTIVE)} ${o}`}
1061
+ ${g}
1062
+ `;
1063
+ }
1064
+ }
1065
+ }
1066
+ }).prompt();
1067
+ };
1068
+ var MULTISELECT_INSTRUCTIONS = [
1069
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1070
+ `${styleText2("dim", "Space:")} select`,
1071
+ `${styleText2("dim", "Enter:")} confirm`
1072
+ ];
1073
+ var m = (n2, u3) => n2.split(`
1074
+ `).map((d) => u3(d)).join(`
1075
+ `);
1076
+ var multiselect = (n2) => {
1077
+ const u3 = (t2, a2) => {
1078
+ const r2 = t2.label ?? String(t2.value);
1079
+ return a2 === "disabled" ? `${styleText2("gray", S_CHECKBOX_INACTIVE)} ${m(r2, (o) => styleText2(["strikethrough", "gray"], o))}${t2.hint ? ` ${styleText2("dim", `(${t2.hint ?? "disabled"})`)}` : ""}` : a2 === "active" ? `${styleText2("cyan", S_CHECKBOX_ACTIVE)} ${r2}${t2.hint ? ` ${styleText2("dim", `(${t2.hint})`)}` : ""}` : a2 === "selected" ? `${styleText2("green", S_CHECKBOX_SELECTED)} ${m(r2, (o) => styleText2("dim", o))}${t2.hint ? ` ${styleText2("dim", `(${t2.hint})`)}` : ""}` : a2 === "cancelled" ? `${m(r2, (o) => styleText2(["strikethrough", "dim"], o))}` : a2 === "active-selected" ? `${styleText2("green", S_CHECKBOX_SELECTED)} ${r2}${t2.hint ? ` ${styleText2("dim", `(${t2.hint})`)}` : ""}` : a2 === "submitted" ? `${m(r2, (o) => styleText2("dim", o))}` : `${styleText2("dim", S_CHECKBOX_INACTIVE)} ${m(r2, (o) => styleText2("dim", o))}`;
1080
+ }, d = n2.required ?? true, x = n2.showInstructions ?? true;
1081
+ return new a({
1082
+ options: n2.options,
1083
+ signal: n2.signal,
1084
+ input: n2.input,
1085
+ output: n2.output,
1086
+ initialValues: n2.initialValues,
1087
+ required: d,
1088
+ cursorAt: n2.cursorAt,
1089
+ validate(t2) {
1090
+ if (d && (t2 === void 0 || t2.length === 0))
1091
+ return `Please select at least one option.
1092
+ ${styleText2(
1093
+ "reset",
1094
+ styleText2(
1095
+ "dim",
1096
+ `Press ${styleText2(["gray", "bgWhite", "inverse"], " space ")} to select, ${styleText2(
1097
+ "gray",
1098
+ styleText2("bgWhite", styleText2("inverse", " enter "))
1099
+ )} to submit`
1100
+ )
1101
+ )}`;
1102
+ },
1103
+ render() {
1104
+ const t2 = n2.withGuide ?? settings.withGuide, a2 = wrapTextWithPrefix(
1105
+ n2.output,
1106
+ n2.message,
1107
+ t2 ? `${symbolBar(this.state)} ` : "",
1108
+ `${symbol(this.state)} `
1109
+ ), r2 = `${t2 ? `${styleText2("gray", S_BAR)}
1110
+ ` : ""}${a2}
1111
+ `, o = this.value ?? [], g = (i2, l) => {
1112
+ if (i2.disabled)
1113
+ return u3(i2, "disabled");
1114
+ const s = o.includes(i2.value);
1115
+ return l && s ? u3(i2, "active-selected") : s ? u3(i2, "selected") : u3(i2, l ? "active" : "inactive");
1116
+ };
1117
+ switch (this.state) {
1118
+ case "submit": {
1119
+ const i2 = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u3(s, "submitted")).join(styleText2("dim", ", ")) || styleText2("dim", "none"), l = wrapTextWithPrefix(
1120
+ n2.output,
1121
+ i2,
1122
+ t2 ? `${styleText2("gray", S_BAR)} ` : ""
1123
+ );
1124
+ return `${r2}${l}`;
1125
+ }
1126
+ case "cancel": {
1127
+ const i2 = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u3(s, "cancelled")).join(styleText2("dim", ", "));
1128
+ if (i2.trim() === "")
1129
+ return `${r2}${styleText2("gray", S_BAR)}`;
1130
+ const l = wrapTextWithPrefix(
1131
+ n2.output,
1132
+ i2,
1133
+ t2 ? `${styleText2("gray", S_BAR)} ` : ""
1134
+ );
1135
+ return `${r2}${l}${t2 ? `
1136
+ ${styleText2("gray", S_BAR)}` : ""}`;
1137
+ }
1138
+ case "error": {
1139
+ const i2 = t2 ? `${styleText2("yellow", S_BAR)} ` : "", l = this.error.split(`
1140
+ `).map(
1141
+ ($, v) => v === 0 ? `${t2 ? `${styleText2("yellow", S_BAR_END)} ` : ""}${styleText2("yellow", $)}` : ` ${$}`
1142
+ ).join(`
1143
+ `), s = r2.split(`
1144
+ `).length, h2 = l.split(`
1145
+ `).length + 1;
1146
+ return `${r2}${i2}${limitOptions({
1147
+ output: n2.output,
1148
+ options: this.options,
1149
+ cursor: this.cursor,
1150
+ maxItems: n2.maxItems,
1151
+ columnPadding: i2.length,
1152
+ rowPadding: s + h2,
1153
+ style: g
1154
+ }).join(`
1155
+ ${i2}`)}
1156
+ ${l}
1157
+ `;
1158
+ }
1159
+ default: {
1160
+ const i2 = t2 ? `${styleText2("cyan", S_BAR)} ` : "", l = r2.split(`
1161
+ `).length, s = x ? formatInstructionFooter(n2.output, MULTISELECT_INSTRUCTIONS, t2) : t2 ? [styleText2("cyan", S_BAR_END)] : [], h2 = s.join(`
1162
+ `), $ = s.length + 1;
1163
+ return `${r2}${i2}${limitOptions({
1164
+ output: n2.output,
1165
+ options: this.options,
1166
+ cursor: this.cursor,
1167
+ maxItems: n2.maxItems,
1168
+ columnPadding: i2.length,
1169
+ rowPadding: l + $,
1170
+ style: g
1171
+ }).join(`
1172
+ ${i2}`)}
1173
+ ${h2}
1174
+ `;
1175
+ }
1176
+ }
1177
+ }
1178
+ }).prompt();
1179
+ };
1180
+ var log = {
1181
+ message: (s = [], {
1182
+ symbol: e = styleText2("gray", S_BAR),
1183
+ secondarySymbol: r2 = styleText2("gray", S_BAR),
1184
+ output: m2 = process.stdout,
1185
+ spacing: l = 1,
1186
+ withGuide: c2
1187
+ } = {}) => {
1188
+ const t2 = [], o = c2 ?? settings.withGuide, f = o ? r2 : "", O = o ? `${e} ` : "", u3 = o ? `${r2} ` : "";
1189
+ for (let i2 = 0; i2 < l; i2++)
1190
+ t2.push(f);
1191
+ const g = Array.isArray(s) ? s : s.split(`
1192
+ `);
1193
+ if (g.length > 0) {
1194
+ const [i2, ...y] = g;
1195
+ i2.length > 0 ? t2.push(`${O}${i2}`) : t2.push(o ? e : "");
1196
+ for (const p of y)
1197
+ p.length > 0 ? t2.push(`${u3}${p}`) : t2.push(o ? r2 : "");
1198
+ }
1199
+ m2.write(`${t2.join(`
1200
+ `)}
1201
+ `);
1202
+ },
1203
+ info: (s, e) => {
1204
+ log.message(s, { ...e, symbol: styleText2("blue", S_INFO) });
1205
+ },
1206
+ success: (s, e) => {
1207
+ log.message(s, { ...e, symbol: styleText2("green", S_SUCCESS) });
1208
+ },
1209
+ step: (s, e) => {
1210
+ log.message(s, { ...e, symbol: styleText2("green", S_STEP_SUBMIT) });
1211
+ },
1212
+ warn: (s, e) => {
1213
+ log.message(s, { ...e, symbol: styleText2("yellow", S_WARN) });
1214
+ },
1215
+ /** alias for `log.warn()`. */
1216
+ warning: (s, e) => {
1217
+ log.warn(s, e);
1218
+ },
1219
+ error: (s, e) => {
1220
+ log.message(s, { ...e, symbol: styleText2("red", S_ERROR) });
1221
+ }
1222
+ };
1223
+ var cancel = (o = "", t2) => {
1224
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR_END)} ` : "";
1225
+ i2.write(`${e}${styleText2("red", o)}
1226
+
1227
+ `);
1228
+ };
1229
+ var intro = (o = "", t2) => {
1230
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR_START)} ` : "";
1231
+ i2.write(`${e}${o}
1232
+ `);
1233
+ };
1234
+ var outro = (o = "", t2) => {
1235
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR)}
1236
+ ${styleText2("gray", S_BAR_END)} ` : "";
1237
+ i2.write(`${e}${o}
1238
+
1239
+ `);
1240
+ };
1241
+ var W = (o) => o;
1242
+ var C2 = (o, e, s) => {
1243
+ const a2 = {
1244
+ hard: true,
1245
+ trim: false
1246
+ }, i2 = wrapAnsi(o, e, a2).split(`
1247
+ `), c2 = i2.reduce((n2, t2) => Math.max(dist_default2(t2), n2), 0), u3 = i2.map(s).reduce((n2, t2) => Math.max(dist_default2(t2), n2), 0), g = e - (u3 - c2);
1248
+ return wrapAnsi(o, g, a2);
1249
+ };
1250
+ var note = (o = "", e = "", s) => {
1251
+ const a2 = s?.output ?? process$1.stdout, i2 = s?.withGuide ?? settings.withGuide, c2 = s?.format ?? W, g = ["", ...C2(o, getColumns(a2) - 6, c2).split(`
1252
+ `).map(c2), ""], n2 = dist_default2(e), t2 = Math.max(
1253
+ g.reduce((m2, F) => {
1254
+ const O = dist_default2(F);
1255
+ return O > m2 ? O : m2;
1256
+ }, 0),
1257
+ n2
1258
+ ) + 2, h2 = g.map(
1259
+ (m2) => `${styleText2("gray", S_BAR)} ${m2}${" ".repeat(t2 - dist_default2(m2))}${styleText2("gray", S_BAR)}`
1260
+ ).join(`
1261
+ `), T = i2 ? `${styleText2("gray", S_BAR)}
1262
+ ` : "", l$1 = i2 ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;
1263
+ a2.write(
1264
+ `${T}${styleText2("green", S_STEP_SUBMIT)} ${styleText2("reset", e)} ${styleText2(
1265
+ "gray",
1266
+ S_BAR_H.repeat(Math.max(t2 - n2 - 1, 1)) + S_CORNER_TOP_RIGHT
1267
+ )}
1268
+ ${h2}
1269
+ ${styleText2("gray", l$1 + S_BAR_H.repeat(t2 + 2) + S_CORNER_BOTTOM_RIGHT)}
1270
+ `
1271
+ );
1272
+ };
1273
+ var Y = 3e4;
1274
+ var Z = (c2) => styleText2("magenta", c2);
1275
+ var spinner = ({
1276
+ indicator: c2 = "dots",
1277
+ onCancel: b,
1278
+ output: n2 = process.stdout,
1279
+ cancelMessage: _,
1280
+ errorMessage: C3,
1281
+ frames: M = unicode ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"],
1282
+ delay: O = unicode ? 80 : 120,
1283
+ signal: g,
1284
+ ...E
1285
+ } = {}) => {
1286
+ const u3 = isCI(), h2 = isAccessible(E.accessible);
1287
+ let x, I, p = false, l = false, r2 = "", v, w = performance.now();
1288
+ const y = getColumns(n2), F = E?.styleFrame ?? Z, S = (e) => {
1289
+ const s = e > 1 ? C3 ?? settings.messages.error : _ ?? settings.messages.cancel;
1290
+ l = e === 1, p && (m2(s, e), l && typeof b == "function" && b());
1291
+ }, $ = () => S(2), a2 = () => S(1), H = () => {
1292
+ process.on("uncaughtExceptionMonitor", $), process.on("unhandledRejection", $), process.on("SIGINT", a2), process.on("SIGTERM", a2), process.on("exit", S), g && g.addEventListener("abort", a2);
1293
+ }, B = () => {
1294
+ process.removeListener("uncaughtExceptionMonitor", $), process.removeListener("unhandledRejection", $), process.removeListener("SIGINT", a2), process.removeListener("SIGTERM", a2), process.removeListener("exit", S), g && g.removeEventListener("abort", a2);
1295
+ }, R2 = () => {
1296
+ if (v === void 0) return;
1297
+ u3 && n2.write(`
1298
+ `);
1299
+ const s = wrapAnsi(v, y, {
1300
+ hard: true,
1301
+ trim: false
1302
+ }).split(`
1303
+ `);
1304
+ s.length > 1 && n2.write(cursor.up(s.length - 1)), n2.write(cursor.to(0)), n2.write(erase.down());
1305
+ }, L = (e) => e.replace(/\.+$/, ""), T = (e) => {
1306
+ const s = (performance.now() - e) / 1e3, i2 = Math.floor(s / 60), t2 = Math.floor(s % 60);
1307
+ return i2 > 0 ? `[${i2}m ${t2}s]` : `[${t2}s]`;
1308
+ }, N = E.withGuide ?? settings.withGuide, P = (e = "") => {
1309
+ if (p = true, l = false, r2 = L(e), w = performance.now(), H(), h2) {
1310
+ r2 !== "" && n2.write(`${r2}
1311
+ `), I = setInterval(() => {
1312
+ n2.write(r2 === "" ? `still working
1313
+ ` : `still working: ${r2}
1314
+ `);
1315
+ }, Y);
1316
+ return;
1317
+ }
1318
+ x = block({ output: n2 }), N && n2.write(`${styleText2("gray", S_BAR)}
1319
+ `);
1320
+ let s = 0, i2 = 0;
1321
+ I = setInterval(() => {
1322
+ if (u3 && r2 === v)
1323
+ return;
1324
+ R2(), v = r2;
1325
+ const t2 = F(M[s]);
1326
+ let o;
1327
+ if (u3)
1328
+ o = `${t2} ${r2}...`;
1329
+ else if (c2 === "timer")
1330
+ o = `${t2} ${r2} ${T(w)}`;
1331
+ else {
1332
+ const j = ".".repeat(Math.floor(i2)).slice(0, 3);
1333
+ o = `${t2} ${r2}${j}`;
1334
+ }
1335
+ const D = wrapAnsi(o, y, {
1336
+ hard: true,
1337
+ trim: false
1338
+ });
1339
+ n2.write(D), s = s + 1 < M.length ? s + 1 : 0, i2 = i2 < 4 ? i2 + 0.125 : 0;
1340
+ }, O);
1341
+ }, m2 = (e = "", s = 0, i2 = false) => {
1342
+ if (p) {
1343
+ if (p = false, l = s === 1, clearInterval(I), h2 || R2(), r2 = e ?? r2, !i2)
1344
+ if (h2) {
1345
+ const t2 = s === 1 ? _ ?? settings.messages.cancel : s === 2 ? C3 ?? settings.messages.error : "Done", o = r2 || t2;
1346
+ c2 === "timer" ? n2.write(`${o} ${T(w)}
1347
+ `) : n2.write(`${o}
1348
+ `);
1349
+ } else {
1350
+ const t2 = s === 0 ? styleText2("green", S_STEP_SUBMIT) : s === 1 ? styleText2("red", S_STEP_CANCEL) : styleText2("red", S_STEP_ERROR);
1351
+ c2 === "timer" ? n2.write(`${t2} ${r2} ${T(w)}
1352
+ `) : n2.write(`${t2} ${r2}
1353
+ `);
1354
+ }
1355
+ B(), x?.();
1356
+ }
1357
+ };
1358
+ return {
1359
+ start: P,
1360
+ stop: (e = "") => m2(e, 0),
1361
+ message: (e = "") => {
1362
+ r2 = L(e ?? r2);
1363
+ },
1364
+ cancel: (e = "") => m2(e, 1),
1365
+ error: (e = "") => m2(e, 2),
1366
+ clear: () => m2("", 0, true),
1367
+ get isCancelled() {
1368
+ return l;
1369
+ }
1370
+ };
1371
+ };
1372
+ var u2 = {
1373
+ light: unicodeOr("\u2500", "-"),
1374
+ heavy: unicodeOr("\u2501", "="),
1375
+ block: unicodeOr("\u2588", "#")
1376
+ };
1377
+ var SELECT_INSTRUCTIONS = [
1378
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1379
+ `${styleText2("dim", "Enter:")} confirm`
1380
+ ];
1381
+ var i = `${styleText2("gray", S_BAR)} `;
1382
+
1383
+ // src/cli/index.ts
1384
+ var import_picocolors = __toESM(require_picocolors(), 1);
1385
+
1386
+ // src/cli/detect.ts
1387
+ import { existsSync as existsSync2, readFileSync } from "fs";
1388
+ import { dirname as dirname2, join as join2 } from "path";
1389
+ function readPackageJson(cwd) {
1390
+ const file = join2(cwd, "package.json");
1391
+ if (!existsSync2(file)) return void 0;
1392
+ return JSON.parse(readFileSync(file, "utf8"));
1393
+ }
1394
+ function dependencyRange(pkg, name) {
1395
+ return pkg.dependencies?.[name] ?? pkg.devDependencies?.[name];
1396
+ }
1397
+ function resolveVersion(cwd, pkg, name) {
1398
+ for (let dir = cwd; ; ) {
1399
+ const file = join2(dir, "node_modules", name, "package.json");
1400
+ if (existsSync2(file)) {
1401
+ const installed = JSON.parse(readFileSync(file, "utf8"));
1402
+ if (installed.version) return installed.version;
1403
+ }
1404
+ const parent = dirname2(dir);
1405
+ if (parent === dir) break;
1406
+ dir = parent;
1407
+ }
1408
+ const range = dependencyRange(pkg, name);
1409
+ return range?.match(/\d+(\.\d+){0,2}/)?.[0];
1410
+ }
1411
+ function atLeast(version, minimum) {
1412
+ const a2 = version.split(".").map((part) => Number.parseInt(part, 10) || 0);
1413
+ const b = minimum.split(".").map((part) => Number.parseInt(part, 10) || 0);
1414
+ for (let i2 = 0; i2 < Math.max(a2.length, b.length); i2++) {
1415
+ const diff = (a2[i2] ?? 0) - (b[i2] ?? 0);
1416
+ if (diff !== 0) return diff > 0;
1417
+ }
1418
+ return true;
1419
+ }
1420
+ var LOCKFILES = [
1421
+ ["pnpm-lock.yaml", "pnpm"],
1422
+ ["bun.lock", "bun"],
1423
+ ["bun.lockb", "bun"],
1424
+ ["yarn.lock", "yarn"],
1425
+ ["package-lock.json", "npm"]
1426
+ ];
1427
+ function detectPackageManager(cwd, pkg, userAgent = process.env.npm_config_user_agent) {
1428
+ const declared = pkg.packageManager?.split("@")[0];
1429
+ if (declared === "pnpm" || declared === "yarn" || declared === "bun" || declared === "npm") {
1430
+ return declared;
1431
+ }
1432
+ for (let dir = cwd; ; ) {
1433
+ for (const [file, manager] of LOCKFILES) {
1434
+ if (existsSync2(join2(dir, file))) return manager;
1435
+ }
1436
+ const parent = dirname2(dir);
1437
+ if (parent === dir) break;
1438
+ dir = parent;
1439
+ }
1440
+ const agent = userAgent?.split("/")[0];
1441
+ if (agent === "pnpm" || agent === "yarn" || agent === "bun") return agent;
1442
+ return "npm";
1443
+ }
1444
+ function detectFramework(cwd, pkg) {
1445
+ if (dependencyRange(pkg, "next")) {
1446
+ const appRouter = ["app", "src/app"].some((dir) => existsSync2(join2(cwd, dir)));
1447
+ return {
1448
+ kind: "next",
1449
+ version: resolveVersion(cwd, pkg, "next"),
1450
+ router: appRouter ? "app" : "pages"
1451
+ };
1452
+ }
1453
+ if (dependencyRange(pkg, "vite")) return { kind: "react", bundler: "vite" };
1454
+ if (dependencyRange(pkg, "react-scripts")) return { kind: "react", bundler: "cra" };
1455
+ return { kind: "react", bundler: "other" };
1456
+ }
1457
+ function detectProject(cwd) {
1458
+ const pkg = readPackageJson(cwd);
1459
+ if (!pkg) return void 0;
1460
+ const framework = detectFramework(cwd, pkg);
1461
+ const usesSrc = framework.kind === "next" ? existsSync2(join2(cwd, "src", framework.router)) : existsSync2(join2(cwd, "src"));
1462
+ return {
1463
+ cwd,
1464
+ pkg,
1465
+ packageManager: detectPackageManager(cwd, pkg),
1466
+ reactVersion: resolveVersion(cwd, pkg, "react"),
1467
+ framework,
1468
+ usesSrc,
1469
+ typescript: existsSync2(join2(cwd, "tsconfig.json")) || Boolean(dependencyRange(pkg, "typescript")),
1470
+ alreadyInstalled: Boolean(dependencyRange(pkg, "react-devbelt"))
1471
+ };
1472
+ }
1473
+ function findFile(cwd, candidates2) {
1474
+ return candidates2.find((file) => existsSync2(join2(cwd, file)));
1475
+ }
1476
+ function installCommand(manager) {
1477
+ switch (manager) {
1478
+ case "pnpm":
1479
+ return ["pnpm", ["add", "-D", "react-devbelt"]];
1480
+ case "yarn":
1481
+ return ["yarn", ["add", "-D", "react-devbelt"]];
1482
+ case "bun":
1483
+ return ["bun", ["add", "-d", "react-devbelt"]];
1484
+ case "npm":
1485
+ return ["npm", ["install", "-D", "react-devbelt"]];
1486
+ }
1487
+ }
1488
+
1489
+ // src/cli/plan.ts
1490
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
1491
+ import { dirname as dirname3, join as join3, relative } from "path";
1492
+
1493
+ // src/cli/plugins.ts
1494
+ var OPT_IN_PLUGINS = [
1495
+ { id: "storage", label: "Storage", hint: "localStorage, sessionStorage and cookies, secrets Redacted" },
1496
+ { id: "breakpoint", label: "Breakpoint", hint: "current breakpoint and width, outline toggle" },
1497
+ { id: "capture", label: "Capture", hint: "screenshots and screen recording" }
1498
+ ];
1499
+ function isOptInPlugin(id) {
1500
+ return OPT_IN_PLUGINS.some((plugin) => plugin.id === id);
1501
+ }
1502
+ function devbeltModule(plugins, options) {
1503
+ const ordered = OPT_IN_PLUGINS.map((plugin) => plugin.id).filter((id) => plugins.includes(id));
1504
+ const imports = ["defaultPlugins", ...ordered].sort().join(", ");
1505
+ const calls = ordered.map((id) => `${id}()`).join(", ");
1506
+ return `${options.useClient ? '"use client";\n\n' : ""}import { DevBelt } from "react-devbelt";
1507
+ import { ${imports} } from "react-devbelt/plugins";
1508
+
1509
+ // Built once, at module level. Add or configure tools here:
1510
+ // https://github.com/ArtifactyNight/react-devbelt#-choosing-and-configuring-plugins
1511
+ const plugins = ${options.production} ? [] : [...defaultPlugins(), ${calls}];
1512
+
1513
+ export function DevBeltToolbar() {
1514
+ return <DevBelt plugins={plugins} />;
1515
+ }
1516
+ `;
1517
+ }
1518
+
1519
+ // src/cli/transform.ts
1520
+ var IMPORT_RE = /^import\s[^;]*?["'][^"'\n]+["'][ \t]*;?[ \t]*$/gm;
1521
+ var DIRECTIVE_RE = /^(?:\s*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/))*\s*["']use (?:client|server)["'];?[ \t]*\n?/;
1522
+ function matchStyle(source, line) {
1523
+ const imports = [...source.matchAll(IMPORT_RE)].map((match) => match[0].trim());
1524
+ if (imports.length === 0) return line;
1525
+ const single = imports.filter((text) => /'[^']+'\s*;?$/.test(text)).length;
1526
+ const bare = imports.filter((text) => !text.endsWith(";")).length;
1527
+ let styled = line;
1528
+ if (single > imports.length / 2) styled = styled.replace(/"([^"]*)"/g, "'$1'");
1529
+ if (bare > imports.length / 2) styled = styled.replace(/;$/, "");
1530
+ return styled;
1531
+ }
1532
+ function addImport(source, rawLine) {
1533
+ const line = matchStyle(source, rawLine);
1534
+ if (source.includes(line)) return source;
1535
+ let end = -1;
1536
+ for (const match of source.matchAll(IMPORT_RE)) end = match.index + match[0].length;
1537
+ if (end >= 0) return `${source.slice(0, end)}
1538
+ ${line}${source.slice(end)}`;
1539
+ const directive = source.match(DIRECTIVE_RE);
1540
+ if (directive) {
1541
+ const at = directive[0].length;
1542
+ return `${source.slice(0, at)}${line}
1543
+ ${source.slice(at)}`;
1544
+ }
1545
+ return `${line}
1546
+ ${source}`;
1547
+ }
1548
+ function addInstallImport(source) {
1549
+ if (source.includes('"react-devbelt/install"') || source.includes("'react-devbelt/install'")) {
1550
+ return source;
1551
+ }
1552
+ const line = matchStyle(source, 'import "react-devbelt/install";');
1553
+ const directive = source.match(DIRECTIVE_RE);
1554
+ const at = directive ? directive[0].length : 0;
1555
+ return `${source.slice(0, at)}${line}
1556
+ ${source.slice(at)}`;
1557
+ }
1558
+ function wrapNextConfig(source) {
1559
+ if (/\bwithDevBelt\b/.test(source)) return source;
1560
+ const match = source.match(/^export default\s+/m);
1561
+ if (match?.index === void 0) return null;
1562
+ const start = match.index + match[0].length;
1563
+ const rest = source.slice(start);
1564
+ if (/^(?:async\s+)?(?:function|class)\b/.test(rest)) return null;
1565
+ const end = expressionEnd(rest);
1566
+ if (end === null) return null;
1567
+ const expression = rest.slice(0, end).trim();
1568
+ if (!expression) return null;
1569
+ const after = rest.slice(end).replace(/^[\s;]*/, "");
1570
+ const wrapped = `${source.slice(0, start)}withDevBelt(${expression});${after ? `
1571
+ ${after}` : "\n"}`;
1572
+ return addImport(wrapped, 'import { withDevBelt } from "react-devbelt/next";');
1573
+ }
1574
+ function expressionEnd(text) {
1575
+ let depth = 0;
1576
+ for (let i2 = 0; i2 < text.length; i2++) {
1577
+ const char = text[i2];
1578
+ if (char === '"' || char === "'" || char === "`") {
1579
+ const close = skipString(text, i2);
1580
+ if (close === null) return null;
1581
+ i2 = close;
1582
+ } else if (char === "/" && text[i2 + 1] === "/") {
1583
+ const newline = text.indexOf("\n", i2);
1584
+ if (depth === 0) return i2;
1585
+ i2 = newline === -1 ? text.length : newline - 1;
1586
+ } else if (char === "/" && text[i2 + 1] === "*") {
1587
+ const close = text.indexOf("*/", i2 + 2);
1588
+ if (close === -1) return null;
1589
+ i2 = close + 1;
1590
+ } else if (char === "(" || char === "[" || char === "{") {
1591
+ depth++;
1592
+ } else if (char === ")" || char === "]" || char === "}") {
1593
+ depth--;
1594
+ if (depth < 0) return null;
1595
+ } else if (depth === 0 && char === ";") {
1596
+ return i2;
1597
+ } else if (depth === 0 && char === "\n") {
1598
+ const next = text.slice(i2 + 1).match(/^\s*(\S)/)?.[1];
1599
+ if (next === void 0 || !/[.?:+\-*/&|=,]/.test(next)) return i2;
1600
+ }
1601
+ }
1602
+ return depth === 0 ? text.length : null;
1603
+ }
1604
+ function skipString(text, start) {
1605
+ const quote = text[start];
1606
+ for (let i2 = start + 1; i2 < text.length; i2++) {
1607
+ if (text[i2] === "\\") i2++;
1608
+ else if (text[i2] === quote) return i2;
1609
+ }
1610
+ return null;
1611
+ }
1612
+ var DEVBELT_MOUNT = {
1613
+ tag: "DevBelt",
1614
+ importLine: 'import { DevBelt } from "react-devbelt";'
1615
+ };
1616
+ function existingMount(source, mount) {
1617
+ if (!/<DevBelt\w*\b/.test(source)) return void 0;
1618
+ if (mount.tag === "DevBelt" || new RegExp(`<${mount.tag}\\b`).test(source)) return source;
1619
+ if (!/<DevBelt\s*\/>/.test(source)) return source;
1620
+ const swapped = source.replace(/<DevBelt\s*\/>/, `<${mount.tag} />`).replace(/^import \{ DevBelt \} from ["']react-devbelt["'];?[ \t]*\n/m, "");
1621
+ return addImport(swapped, mount.importLine);
1622
+ }
1623
+ function addDevBeltToLayout(source, mount = DEVBELT_MOUNT) {
1624
+ const existing = existingMount(source, mount);
1625
+ if (existing !== void 0) return existing;
1626
+ const element = `<${mount.tag} />`;
1627
+ const close = source.lastIndexOf("</body>");
1628
+ if (close === -1) return null;
1629
+ const lineStart = source.lastIndexOf("\n", close) + 1;
1630
+ const beforeClose = source.slice(lineStart, close);
1631
+ let next;
1632
+ if (beforeClose.trim() === "") {
1633
+ const prevEnd = lineStart - 1;
1634
+ const prevStart = source.lastIndexOf("\n", prevEnd - 1) + 1;
1635
+ const prevIndent = source.slice(prevStart, prevEnd).match(/^\s*/)?.[0] ?? "";
1636
+ const indent = prevIndent.length > beforeClose.length ? prevIndent : `${beforeClose} `;
1637
+ next = `${source.slice(0, lineStart)}${indent}${element}
1638
+ ${source.slice(lineStart)}`;
1639
+ } else {
1640
+ next = `${source.slice(0, close)}${element}${source.slice(close)}`;
1641
+ }
1642
+ return addImport(next, mount.importLine);
1643
+ }
1644
+ function addDevBeltBeside(source, tag, mount = DEVBELT_MOUNT) {
1645
+ const existing = existingMount(source, mount);
1646
+ if (existing !== void 0) return existing;
1647
+ const toolbar = `<${mount.tag} />`;
1648
+ let next;
1649
+ const ownLine = source.match(new RegExp(`^([ \\t]*)<${tag}\\b[^>\\n]*\\/>[ \\t]*$`, "m"));
1650
+ const inline = source.match(new RegExp(`(?:render\\(|return\\s+\\(?)\\s*(<${tag}\\b[^>\\n]*\\/>)`));
1651
+ if (ownLine?.index !== void 0) {
1652
+ const indent = ownLine[1];
1653
+ const element = ownLine[0].trim();
1654
+ const start = ownLine.index;
1655
+ const end = start + ownLine[0].length;
1656
+ const before = source.slice(0, start).trimEnd();
1657
+ const hasJsxParent = before.endsWith(">");
1658
+ const replacement = hasJsxParent ? `${ownLine[0]}
1659
+ ${indent}${toolbar}` : `${indent}<>
1660
+ ${indent} ${element}
1661
+ ${indent} ${toolbar}
1662
+ ${indent}</>`;
1663
+ next = source.slice(0, start) + replacement + source.slice(end);
1664
+ } else if (inline?.index !== void 0) {
1665
+ const element = inline[1];
1666
+ const at = inline.index + inline[0].length - element.length;
1667
+ next = `${source.slice(0, at)}<>${element}${toolbar}</>${source.slice(at + element.length)}`;
1668
+ } else {
1669
+ return null;
1670
+ }
1671
+ return addImport(next, mount.importLine);
1672
+ }
1673
+ function addDevBeltToEntry(source, mount = DEVBELT_MOUNT) {
1674
+ const next = addDevBeltBeside(source, "App", mount);
1675
+ return next === null ? null : addInstallImport(next);
1676
+ }
1677
+
1678
+ // src/cli/plan.ts
1679
+ var EXTENSIONS = ["tsx", "ts", "jsx", "js"];
1680
+ function candidates(dir, name, extensions = EXTENSIONS) {
1681
+ return extensions.map((ext) => join3(dir, `${name}.${ext}`));
1682
+ }
1683
+ function editFile(project, plan, file, summary, edit, manual) {
1684
+ const source = readFileSync2(join3(project.cwd, file), "utf8");
1685
+ const next = edit(source);
1686
+ if (next === null) plan.manual.push({ file, instruction: manual });
1687
+ else plan.changes.push({ file, kind: "edit", summary, content: next === source ? void 0 : next });
1688
+ }
1689
+ function toolbarMount(project, plan, plugins, host, moduleDir, production) {
1690
+ if (plugins.length === 0) return DEVBELT_MOUNT;
1691
+ const file = join3(moduleDir, `devbelt.${project.typescript ? "tsx" : "jsx"}`);
1692
+ if (existsSync3(join3(project.cwd, file))) {
1693
+ plan.manual.push({
1694
+ file,
1695
+ instruction: `This file already exists, so it was left as is. Add ${plugins.map((id) => `${id}()`).join(", ")} from "react-devbelt/plugins" to its plugin list.`
1696
+ });
1697
+ } else {
1698
+ plan.changes.push({
1699
+ file,
1700
+ kind: "create",
1701
+ summary: `toolbar with ${plugins.join(", ")}`,
1702
+ content: devbeltModule(plugins, {
1703
+ production,
1704
+ useClient: project.framework.kind === "next"
1705
+ })
1706
+ });
1707
+ }
1708
+ let path = relative(dirname3(host), file).replace(/\.[jt]sx$/, "").split("\\").join("/");
1709
+ if (!path.startsWith(".")) path = `./${path}`;
1710
+ return { tag: "DevBeltToolbar", importLine: `import { DevBeltToolbar } from "${path}";` };
1711
+ }
1712
+ function planInit(project, plugins = []) {
1713
+ const { framework } = project;
1714
+ const ts = project.typescript;
1715
+ const src = project.usesSrc ? "src" : "";
1716
+ const plan = { setup: "", changes: [], manual: [] };
1717
+ const toolbar = plugins.length > 0 ? "<DevBeltToolbar />" : "<DevBelt />";
1718
+ if (framework.kind === "next") {
1719
+ const injects = framework.version === void 0 || atLeast(framework.version, "16.3");
1720
+ plan.setup = `Next.js${framework.version ? ` ${framework.version}` : ""} \xB7 ${framework.router === "app" ? "App" : "Pages"} Router`;
1721
+ const production = 'process.env.NODE_ENV === "production"';
1722
+ if (injects) {
1723
+ const config = findFile(project.cwd, ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"]);
1724
+ if (config) {
1725
+ editFile(
1726
+ project,
1727
+ plan,
1728
+ config,
1729
+ "wrap the config with withDevBelt",
1730
+ wrapNextConfig,
1731
+ 'Wrap the exported config: `withDevBelt(config)` from "react-devbelt/next".'
1732
+ );
1733
+ } else {
1734
+ const file = ts ? "next.config.ts" : "next.config.mjs";
1735
+ plan.changes.push({
1736
+ file,
1737
+ kind: "create",
1738
+ summary: "new config with withDevBelt",
1739
+ content: `import { withDevBelt } from "react-devbelt/next";
1740
+
1741
+ export default withDevBelt({});
1742
+ `
1743
+ });
1744
+ }
1745
+ } else if (framework.version && atLeast(framework.version, "15.3")) {
1746
+ const existing = findFile(project.cwd, candidates(src, "instrumentation-client", ["ts", "js"]));
1747
+ if (existing) {
1748
+ editFile(project, plan, existing, "start capturing before hydration", addInstallImport, "");
1749
+ } else {
1750
+ plan.changes.push({
1751
+ file: join3(src, `instrumentation-client.${ts ? "ts" : "js"}`),
1752
+ kind: "create",
1753
+ summary: "start capturing before hydration",
1754
+ content: 'import "react-devbelt/install";\n'
1755
+ });
1756
+ }
1757
+ } else {
1758
+ plan.manual.push({
1759
+ file: void 0,
1760
+ instruction: 'Next.js before 15.3 has no instrumentation-client. Add `import "react-devbelt/install";` to the top of a client component that loads on every page.'
1761
+ });
1762
+ }
1763
+ if (framework.router === "app") {
1764
+ const layout = findFile(project.cwd, candidates(join3(src, "app"), "layout"));
1765
+ if (layout) {
1766
+ const mount = toolbarMount(project, plan, plugins, layout, join3(src, "app"), production);
1767
+ editFile(
1768
+ project,
1769
+ plan,
1770
+ layout,
1771
+ `render ${toolbar} inside <body>`,
1772
+ (source) => addDevBeltToLayout(source, mount),
1773
+ `Render \`${toolbar}\` once, inside <body> after {children}.`
1774
+ );
1775
+ } else {
1776
+ plan.manual.push({ file: void 0, instruction: `No root layout found. Render \`${toolbar}\` in it once you add one.` });
1777
+ }
1778
+ } else {
1779
+ const app = findFile(project.cwd, candidates(join3(src, "pages"), "_app"));
1780
+ const host = app ?? join3(src, "pages", `_app.${ts ? "tsx" : "jsx"}`);
1781
+ const mount = toolbarMount(project, plan, plugins, host, src, production);
1782
+ if (app) {
1783
+ editFile(
1784
+ project,
1785
+ plan,
1786
+ app,
1787
+ `render ${toolbar} next to the page`,
1788
+ (source) => addDevBeltBeside(source, "Component", mount),
1789
+ `Render \`${toolbar}\` next to \`<Component {...pageProps} />\`.`
1790
+ );
1791
+ } else {
1792
+ const element = `<${mount.tag} />`;
1793
+ const body = ` return (
1794
+ <>
1795
+ <Component {...pageProps} />
1796
+ ${element}
1797
+ </>
1798
+ );
1799
+ }
1800
+ `;
1801
+ plan.changes.push({
1802
+ file: host,
1803
+ kind: "create",
1804
+ summary: `custom App that renders ${toolbar}`,
1805
+ content: ts ? `import type { AppProps } from "next/app";
1806
+ ${mount.importLine}
1807
+
1808
+ export default function App({ Component, pageProps }: AppProps) {
1809
+ ${body}` : `${mount.importLine}
1810
+
1811
+ export default function App({ Component, pageProps }) {
1812
+ ${body}`
1813
+ });
1814
+ }
1815
+ }
1816
+ return plan;
1817
+ }
1818
+ plan.setup = { vite: "Vite + React", cra: "Create React App", other: "React" }[framework.bundler];
1819
+ const entry = findFile(project.cwd, [
1820
+ ...candidates("src", "main"),
1821
+ ...candidates("src", "index"),
1822
+ ...candidates("", "main"),
1823
+ ...candidates("", "index")
1824
+ ]);
1825
+ if (entry) {
1826
+ const production = framework.bundler === "vite" ? "import.meta.env.PROD" : 'process.env.NODE_ENV === "production"';
1827
+ const mount = toolbarMount(project, plan, plugins, entry, dirname3(entry), production);
1828
+ editFile(
1829
+ project,
1830
+ plan,
1831
+ entry,
1832
+ `install import first, ${toolbar} beside <App />`,
1833
+ (source) => addDevBeltToEntry(source, mount),
1834
+ `Make \`import "react-devbelt/install";\` the first import, and render \`${toolbar}\` next to <App />.`
1835
+ );
1836
+ } else {
1837
+ plan.manual.push({
1838
+ file: void 0,
1839
+ instruction: `Couldn't find the entry file. In it, make \`import "react-devbelt/install";\` the first import and render \`${toolbar}\` next to <App />.`
1840
+ });
1841
+ }
1842
+ return plan;
1843
+ }
1844
+
1845
+ // src/cli/run.ts
1846
+ import { spawn } from "child_process";
1847
+ async function runCommand(cwd, bin, args, labels) {
1848
+ const spin = spinner();
1849
+ spin.start(labels.running);
1850
+ const output = [];
1851
+ const code = await new Promise((done) => {
1852
+ const child = spawn(bin, args, { cwd, shell: process.platform === "win32" });
1853
+ child.stdout.on("data", (chunk) => output.push(chunk.toString()));
1854
+ child.stderr.on("data", (chunk) => output.push(chunk.toString()));
1855
+ child.on("error", (error) => {
1856
+ output.push(error.message);
1857
+ done(1);
1858
+ });
1859
+ child.on("close", (exitCode) => done(exitCode ?? 1));
1860
+ });
1861
+ if (code === 0) {
1862
+ spin.stop(labels.done);
1863
+ return true;
1864
+ }
1865
+ spin.error(`${bin} ${args.join(" ")} failed`);
1866
+ log.error(output.join("").trim().split("\n").slice(-15).join("\n"));
1867
+ return false;
1868
+ }
1869
+
1870
+ // src/cli/upgrade.ts
1871
+ var UPGRADABLE = ["react-devbelt", "devbelt-plugin-tanstack-query"];
1872
+ var CHANGELOG_URL = "https://github.com/ArtifactyNight/react-devbelt/blob/main/packages/react-devbelt/CHANGELOG.md";
1873
+ function installedPackages(project) {
1874
+ return UPGRADABLE.flatMap((name) => {
1875
+ const dev = project.pkg.devDependencies?.[name] !== void 0;
1876
+ if (!dev && project.pkg.dependencies?.[name] === void 0) return [];
1877
+ return [{ name, current: resolveVersion(project.cwd, project.pkg, name), dev }];
1878
+ });
1879
+ }
1880
+ function planUpgrade(project, releases) {
1881
+ const plan = { upgrades: [], current: [], warnings: [] };
1882
+ for (const { name, current, dev } of installedPackages(project)) {
1883
+ const release = releases[name];
1884
+ if (!release) continue;
1885
+ if (current && atLeast(current, release.version)) {
1886
+ plan.current.push({ name, version: current });
1887
+ continue;
1888
+ }
1889
+ plan.upgrades.push({ name, current, latest: release.version, dev, breaking: isBreaking(current, release.version) });
1890
+ }
1891
+ const after = new Map(plan.upgrades.map((upgrade2) => [upgrade2.name, upgrade2.latest]));
1892
+ for (const upgrade2 of plan.upgrades) {
1893
+ for (const [peer, range] of Object.entries(releases[upgrade2.name]?.peerDependencies ?? {})) {
1894
+ const installed = after.get(peer) ?? resolveVersion(project.cwd, project.pkg, peer);
1895
+ const minimum = range.match(/\d+(\.\d+){0,2}/)?.[0];
1896
+ if (!installed || !minimum || atLeast(installed, minimum)) continue;
1897
+ plan.warnings.push(`${upgrade2.name} ${upgrade2.latest} needs ${peer} ${minimum} or newer; this project has ${installed}.`);
1898
+ }
1899
+ }
1900
+ return plan;
1901
+ }
1902
+ function isBreaking(current, latest) {
1903
+ if (!current) return true;
1904
+ const [aMajor = 0, aMinor = 0] = current.split(".").map((part) => Number.parseInt(part, 10) || 0);
1905
+ const [bMajor = 0, bMinor = 0] = latest.split(".").map((part) => Number.parseInt(part, 10) || 0);
1906
+ if (bMajor !== aMajor) return true;
1907
+ return bMajor === 0 && bMinor !== aMinor;
1908
+ }
1909
+ function upgradeCommands(manager, upgrades) {
1910
+ const commands = [];
1911
+ for (const dev of [true, false]) {
1912
+ const specs = upgrades.filter((upgrade2) => upgrade2.dev === dev).map((upgrade2) => `${upgrade2.name}@${upgrade2.latest}`);
1913
+ if (specs.length === 0) continue;
1914
+ const verb = manager === "npm" ? "install" : "add";
1915
+ const flag = dev ? [manager === "bun" ? "-d" : "-D"] : [];
1916
+ commands.push([manager, [verb, ...flag, ...specs]]);
1917
+ }
1918
+ return commands;
1919
+ }
1920
+ function registryUrl(env = process.env) {
1921
+ return (env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
1922
+ }
1923
+ async function fetchReleases(names, registry = registryUrl(), fetcher = fetch) {
1924
+ const entries = await Promise.all(
1925
+ names.map(async (name) => {
1926
+ const response = await fetcher(`${registry}/${name}/latest`, { headers: { accept: "application/json" } });
1927
+ if (!response.ok) throw new Error(`Couldn't read ${name} from ${registry} (HTTP ${response.status}).`);
1928
+ const release = await response.json();
1929
+ return [name, { version: release.version, peerDependencies: release.peerDependencies }];
1930
+ })
1931
+ );
1932
+ return Object.fromEntries(entries);
1933
+ }
1934
+
1935
+ // src/cli/index.ts
1936
+ var HELP = `
1937
+ ${import_picocolors.default.bold("react-devbelt")} ${import_picocolors.default.dim("\xB7 dev toolbar for React and Next.js")}
1938
+
1939
+ Usage
1940
+ npx react-devbelt init [options] install and wire up the toolbar
1941
+ npx react-devbelt upgrade [options] update react-devbelt and its plugin packages
1942
+
1943
+ Options
1944
+ -y, --yes accept the plan without asking (init: default tools only,
1945
+ unless --plugins says otherwise)
1946
+ --plugins <list> init: opt-in tools to add, comma-separated:
1947
+ ${OPT_IN_PLUGINS.map((plugin) => plugin.id).join(", ")} (or "none")
1948
+ --skip-install init: don't install the package, only edit files
1949
+ --cwd <dir> project folder (default: current folder)
1950
+ -h, --help show this help
1951
+ `;
1952
+ async function main(argv) {
1953
+ const { values, positionals } = parseArgs({
1954
+ args: argv,
1955
+ allowPositionals: true,
1956
+ options: {
1957
+ yes: { type: "boolean", short: "y", default: false },
1958
+ "skip-install": { type: "boolean", default: false },
1959
+ cwd: { type: "string" },
1960
+ plugins: { type: "string" },
1961
+ help: { type: "boolean", short: "h", default: false }
1962
+ }
1963
+ });
1964
+ const command = positionals[0];
1965
+ if (values.help || command === void 0 || command === "help") {
1966
+ console.log(HELP);
1967
+ return command === void 0 && !values.help ? 1 : 0;
1968
+ }
1969
+ if (command !== "init" && command !== "upgrade") {
1970
+ console.error(`Unknown command "${command}".
1971
+ ${HELP}`);
1972
+ return 1;
1973
+ }
1974
+ const cwd = resolve(values.cwd ?? process.cwd());
1975
+ const interactive = !values.yes && process.stdin.isTTY === true;
1976
+ if (command === "upgrade") {
1977
+ if (values.plugins !== void 0 || values["skip-install"]) {
1978
+ console.error("--plugins and --skip-install only apply to init.");
1979
+ return 1;
1980
+ }
1981
+ return upgrade(cwd, { interactive });
1982
+ }
1983
+ let plugins;
1984
+ if (values.plugins !== void 0) {
1985
+ const ids = values.plugins.split(",").map((id) => id.trim().toLowerCase()).filter((id) => id && id !== "none");
1986
+ const unknown = ids.filter((id) => !isOptInPlugin(id));
1987
+ if (unknown.length > 0) {
1988
+ console.error(
1989
+ `Unknown plugin ${unknown.map((id) => `"${id}"`).join(", ")}. Choose from: ${OPT_IN_PLUGINS.map((plugin) => plugin.id).join(", ")}.`
1990
+ );
1991
+ return 1;
1992
+ }
1993
+ plugins = [...new Set(ids)];
1994
+ }
1995
+ return init(cwd, { interactive, install: !values["skip-install"], plugins });
1996
+ }
1997
+ async function init(cwd, options) {
1998
+ intro(import_picocolors.default.inverse(" react-devbelt init "));
1999
+ const project = detectProject(cwd);
2000
+ if (!project) {
2001
+ cancel(`No package.json in ${cwd}. Run this from your app's folder.`);
2002
+ return 1;
2003
+ }
2004
+ if (project.reactVersion && !atLeast(project.reactVersion, "19")) {
2005
+ cancel(
2006
+ `This project uses React ${project.reactVersion}. react-devbelt needs React 19 or newer; upgrade React first.`
2007
+ );
2008
+ return 1;
2009
+ }
2010
+ if (!project.reactVersion) {
2011
+ log.warn("Couldn't find React in package.json. react-devbelt needs React 19 or newer.");
2012
+ }
2013
+ let plugins = options.plugins ?? [];
2014
+ if (options.plugins === void 0 && options.interactive) {
2015
+ const picked = await multiselect({
2016
+ message: `Add opt-in tools? ${import_picocolors.default.dim("(space to toggle, enter to continue)")}`,
2017
+ required: false,
2018
+ options: OPT_IN_PLUGINS.map((plugin) => ({ value: plugin.id, label: plugin.label, hint: plugin.hint }))
2019
+ });
2020
+ if (isCancel(picked)) {
2021
+ cancel("Nothing changed.");
2022
+ return 0;
2023
+ }
2024
+ plugins = picked;
2025
+ }
2026
+ const plan = planInit(project, plugins);
2027
+ note(describe(project, plan, options.install), "Detected");
2028
+ if (plan.changes.every((change) => change.content === void 0) && plan.manual.length === 0 && project.alreadyInstalled) {
2029
+ outro("react-devbelt is already set up here. Nothing to do.");
2030
+ return 0;
2031
+ }
2032
+ if (options.interactive) {
2033
+ const go = await confirm({ message: "Apply these changes?", initialValue: true });
2034
+ if (isCancel(go) || !go) {
2035
+ cancel("Nothing changed.");
2036
+ return 0;
2037
+ }
2038
+ }
2039
+ if (options.install && !project.alreadyInstalled) {
2040
+ const ok = await install(project);
2041
+ if (!ok) return 1;
2042
+ }
2043
+ for (const change of plan.changes) {
2044
+ if (change.content === void 0) {
2045
+ log.info(`${import_picocolors.default.dim(change.file)} already set up`);
2046
+ continue;
2047
+ }
2048
+ const target = join4(cwd, change.file);
2049
+ mkdirSync(dirname4(target), { recursive: true });
2050
+ writeFileSync(target, change.content);
2051
+ log.success(`${change.kind === "create" ? "Created" : "Updated"} ${import_picocolors.default.cyan(change.file)} ${import_picocolors.default.dim(`\xB7 ${change.summary}`)}`);
2052
+ }
2053
+ if (plan.manual.length > 0) {
2054
+ note(
2055
+ plan.manual.map((step) => `${step.file ? `${import_picocolors.default.cyan(step.file)}
2056
+ ` : ""}${step.instruction}`).join("\n\n"),
2057
+ import_picocolors.default.yellow("Do this by hand")
2058
+ );
2059
+ }
2060
+ const hints = [];
2061
+ if (hasDependency(project, "@tanstack/react-query")) {
2062
+ hints.push(
2063
+ "This app uses TanStack Query. Its tool needs your QueryClient, so add it by hand: https://github.com/ArtifactyNight/react-devbelt/blob/main/packages/devbelt-plugin-tanstack-query"
2064
+ );
2065
+ }
2066
+ if (plugins.length === 0) {
2067
+ hints.push("Opt-in tools later: https://github.com/ArtifactyNight/react-devbelt#-choosing-and-configuring-plugins");
2068
+ }
2069
+ outro(
2070
+ `Start your dev server; the toolbar shows at the bottom of the page.${hints.map((hint) => `
2071
+ ${import_picocolors.default.dim(hint)}`).join("")}`
2072
+ );
2073
+ return 0;
2074
+ }
2075
+ function hasDependency(project, name) {
2076
+ return Boolean(project.pkg.dependencies?.[name] ?? project.pkg.devDependencies?.[name]);
2077
+ }
2078
+ function describe(project, plan, installing) {
2079
+ const lines = [
2080
+ `${import_picocolors.default.dim("Framework")} ${plan.setup}`,
2081
+ `${import_picocolors.default.dim("React")} ${project.reactVersion ?? "unknown"}`,
2082
+ `${import_picocolors.default.dim("Package manager")} ${project.packageManager}`,
2083
+ ""
2084
+ ];
2085
+ if (installing && !project.alreadyInstalled) {
2086
+ const [bin, args] = installCommand(project.packageManager);
2087
+ lines.push(`${import_picocolors.default.green("+")} ${bin} ${args.join(" ")}`);
2088
+ }
2089
+ for (const change of plan.changes) {
2090
+ const mark = change.content === void 0 ? import_picocolors.default.dim("\u2713") : change.kind === "create" ? import_picocolors.default.green("+") : import_picocolors.default.yellow("~");
2091
+ lines.push(`${mark} ${change.file} ${import_picocolors.default.dim(`\xB7 ${change.content === void 0 ? "already set up" : change.summary}`)}`);
2092
+ }
2093
+ for (const step of plan.manual) {
2094
+ lines.push(`${import_picocolors.default.red("!")} ${step.file ?? "manual step"} ${import_picocolors.default.dim("\xB7 couldn't edit safely, see below")}`);
2095
+ }
2096
+ return lines.join("\n");
2097
+ }
2098
+ async function install(project) {
2099
+ const [bin, args] = installCommand(project.packageManager);
2100
+ const ok = await runCommand(project.cwd, bin, args, { running: `Installing with ${bin}`, done: "Installed react-devbelt" });
2101
+ if (!ok) cancel("No files were changed.");
2102
+ return ok;
2103
+ }
2104
+ async function upgrade(cwd, options) {
2105
+ intro(import_picocolors.default.inverse(" react-devbelt upgrade "));
2106
+ const project = detectProject(cwd);
2107
+ if (!project) {
2108
+ cancel(`No package.json in ${cwd}. Run this from your app's folder.`);
2109
+ return 1;
2110
+ }
2111
+ const installed = installedPackages(project);
2112
+ if (!installed.some((entry) => entry.name === "react-devbelt")) {
2113
+ cancel("react-devbelt isn't in package.json. Set it up with: npx react-devbelt init");
2114
+ return 1;
2115
+ }
2116
+ const spin = spinner();
2117
+ spin.start("Checking for new versions");
2118
+ let releases;
2119
+ try {
2120
+ releases = await fetchReleases(installed.map((entry) => entry.name));
2121
+ } catch (error) {
2122
+ spin.error("Couldn't check for new versions");
2123
+ cancel(error instanceof Error ? error.message : String(error));
2124
+ return 1;
2125
+ }
2126
+ spin.stop("Checked for new versions");
2127
+ const plan = planUpgrade(project, releases);
2128
+ if (plan.upgrades.length === 0) {
2129
+ outro(`Already on the latest: ${plan.current.map(({ name, version }) => `${name} ${version}`).join(", ")}.`);
2130
+ return 0;
2131
+ }
2132
+ const commands = upgradeCommands(project.packageManager, plan.upgrades);
2133
+ const lines = [
2134
+ ...plan.upgrades.map(
2135
+ (upgrade2) => `${import_picocolors.default.yellow("~")} ${upgrade2.name} ${import_picocolors.default.dim(upgrade2.current ?? "?")} \u2192 ${import_picocolors.default.green(upgrade2.latest)}${upgrade2.breaking ? import_picocolors.default.yellow(" may break") : ""}`
2136
+ ),
2137
+ ...plan.current.map(({ name, version }) => `${import_picocolors.default.dim("\u2713")} ${name} ${import_picocolors.default.dim(`${version} \xB7 latest`)}`),
2138
+ "",
2139
+ ...commands.map(([bin, args]) => import_picocolors.default.dim(`${bin} ${args.join(" ")}`))
2140
+ ];
2141
+ note(lines.join("\n"), "Updates");
2142
+ for (const warning of plan.warnings) log.warn(warning);
2143
+ if (plan.upgrades.some((upgrade2) => upgrade2.breaking)) {
2144
+ log.info(`Changelog: ${CHANGELOG_URL}`);
2145
+ }
2146
+ if (options.interactive) {
2147
+ const go = await confirm({ message: "Upgrade now?", initialValue: true });
2148
+ if (isCancel(go) || !go) {
2149
+ cancel("Nothing changed.");
2150
+ return 0;
2151
+ }
2152
+ }
2153
+ for (const [bin, args] of commands) {
2154
+ const ok = await runCommand(project.cwd, bin, args, {
2155
+ running: `Upgrading with ${bin}`,
2156
+ done: `Upgraded ${args.filter((arg) => arg.includes("@")).join(", ")}`
2157
+ });
2158
+ if (!ok) {
2159
+ cancel("The upgrade didn't finish. Your package.json and lockfile may be partly updated.");
2160
+ return 1;
2161
+ }
2162
+ }
2163
+ outro("Restart your dev server to load the new version.");
2164
+ return 0;
2165
+ }
2166
+ main(process.argv.slice(2)).then(
2167
+ (code) => {
2168
+ process.exitCode = code;
2169
+ },
2170
+ (error) => {
2171
+ cancel(error instanceof Error ? error.message : String(error));
2172
+ process.exitCode = 1;
2173
+ }
2174
+ );