tokocode 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ import { rmSync } from 'node:fs';
2
+ /**
3
+ * Paths to delete if the process is interrupted (Ctrl+C) mid-way, e.g. a half-extracted
4
+ * staging folder. The resumable download itself is kept on purpose.
5
+ */
6
+ const paths = new Set();
7
+ export function removeOnInterrupt(target) {
8
+ paths.add(target);
9
+ return () => paths.delete(target);
10
+ }
11
+ export function runInterruptCleanup() {
12
+ for (const target of paths) {
13
+ try {
14
+ rmSync(target, { recursive: true, force: true });
15
+ }
16
+ catch {
17
+ // Best effort on the way out.
18
+ }
19
+ }
20
+ paths.clear();
21
+ }
@@ -0,0 +1,77 @@
1
+ import { EXIT } from '../config/constants.js';
2
+ /**
3
+ * An error the customer can act on: a stable code, a plain-language message and a hint.
4
+ * Server errors keep the server's code and wording (they are written for customers).
5
+ */
6
+ export class CliError extends Error {
7
+ code;
8
+ hint;
9
+ exitCode;
10
+ details;
11
+ constructor(code, message, hint = '', exitCode = EXIT.error, details = {}) {
12
+ super(message);
13
+ this.code = code;
14
+ this.hint = hint;
15
+ this.exitCode = exitCode;
16
+ this.details = details;
17
+ this.name = 'CliError';
18
+ }
19
+ get status() {
20
+ return this.details.status;
21
+ }
22
+ get retryAfter() {
23
+ return this.details.retryAfter;
24
+ }
25
+ }
26
+ /** Ctrl+C or "no" at a confirmation. */
27
+ export class CancelledError extends CliError {
28
+ constructor(message = 'Instalasi dibatalkan.') {
29
+ super('cancelled', message, '', EXIT.cancelled);
30
+ this.name = 'CancelledError';
31
+ }
32
+ }
33
+ const NETWORK_CODES = {
34
+ ENOTFOUND: ['Server TokoCode tidak ditemukan.', 'Periksa koneksi internet Anda atau DNS, lalu coba lagi.'],
35
+ EAI_AGAIN: ['Server TokoCode tidak dapat dihubungi (DNS).', 'Periksa koneksi internet Anda, lalu coba lagi.'],
36
+ ECONNREFUSED: ['Koneksi ke server TokoCode ditolak.', 'Server mungkin sedang pemeliharaan. Coba lagi beberapa saat lagi.'],
37
+ ECONNRESET: ['Koneksi ke server TokoCode terputus.', 'Periksa koneksi internet Anda, lalu jalankan ulang perintah ini.'],
38
+ ETIMEDOUT: ['Server TokoCode tidak merespons (timeout).', 'Periksa koneksi internet Anda, lalu coba lagi.'],
39
+ EPIPE: ['Koneksi ke server TokoCode terputus.', 'Jalankan ulang perintah ini.'],
40
+ ENETUNREACH: ['Jaringan tidak terjangkau.', 'Pastikan komputer terhubung ke internet.'],
41
+ EHOSTUNREACH: ['Server TokoCode tidak terjangkau.', 'Pastikan komputer terhubung ke internet.'],
42
+ CERT_HAS_EXPIRED: ['Sertifikat HTTPS server tidak valid.', 'Pastikan tanggal dan jam komputer benar.'],
43
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: ['Sertifikat HTTPS server tidak dapat diverifikasi.', 'Jaringan Anda mungkin memakai proxy/antivirus yang memeriksa HTTPS. Coba jaringan lain.'],
44
+ SELF_SIGNED_CERT_IN_CHAIN: ['Sertifikat HTTPS server tidak dapat diverifikasi.', 'Jaringan Anda mungkin memakai proxy/antivirus yang memeriksa HTTPS. Coba jaringan lain.'],
45
+ };
46
+ const FILESYSTEM_CODES = {
47
+ ENOSPC: ['Ruang penyimpanan tidak cukup.', 'Kosongkan ruang disk atau pilih lokasi instalasi di drive lain.'],
48
+ EACCES: ['Izin akses ditolak.', 'Pilih folder lain yang dapat Anda tulis (misalnya folder Documents), atau jalankan terminal dengan hak yang sesuai.'],
49
+ EPERM: ['Operasi tidak diizinkan oleh sistem.', 'Tutup aplikasi yang sedang membuka folder tujuan (editor, antivirus), lalu coba lagi.'],
50
+ EROFS: ['Lokasi instalasi hanya-baca.', 'Pilih folder lain.'],
51
+ EBUSY: ['File sedang dipakai aplikasi lain.', 'Tutup aplikasi yang membuka folder tujuan, lalu coba lagi.'],
52
+ ENAMETOOLONG: ['Nama atau path file terlalu panjang.', 'Pilih lokasi instalasi yang lebih pendek, misalnya D:\\Projects.'],
53
+ EMFILE: ['Terlalu banyak file terbuka.', 'Tutup beberapa aplikasi lalu coba lagi.'],
54
+ };
55
+ export function isNetworkError(error) {
56
+ const code = error?.code;
57
+ return typeof code === 'string' && (code in NETWORK_CODES || code.startsWith('ERR_SOCKET') || code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'UND_ERR_SOCKET');
58
+ }
59
+ /**
60
+ * Converts any thrown value into a CliError with a message for the customer.
61
+ */
62
+ export function toCliError(error, fallback = 'Terjadi kesalahan yang tidak terduga.') {
63
+ if (error instanceof CliError) {
64
+ return error;
65
+ }
66
+ const code = error?.code ?? '';
67
+ const network = NETWORK_CODES[code];
68
+ if (network) {
69
+ return new CliError('network_error', network[0], network[1], EXIT.error, { cause: error });
70
+ }
71
+ const filesystem = FILESYSTEM_CODES[code];
72
+ if (filesystem) {
73
+ const target = error.path;
74
+ return new CliError(code.toLowerCase(), filesystem[0] + (target ? ` (${target})` : ''), filesystem[1], EXIT.error, { cause: error });
75
+ }
76
+ return new CliError('unexpected', error instanceof Error && error.message ? `${fallback} ${error.message}` : fallback, 'Jalankan ulang dengan --debug untuk detail, lalu hubungi dukungan TokoCode bila berulang.', EXIT.error, { cause: error });
77
+ }
@@ -0,0 +1,138 @@
1
+ import { constants as fsConstants } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { randomBytes } from 'node:crypto';
6
+ const IGNORED_ENTRIES = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini']);
7
+ /**
8
+ * What is at a path: nothing, an empty folder (OS junk files ignored), a folder with files, or a file.
9
+ */
10
+ export async function directoryState(target) {
11
+ let stat;
12
+ try {
13
+ stat = await fs.stat(target);
14
+ }
15
+ catch (error) {
16
+ if (error.code === 'ENOENT') {
17
+ return 'missing';
18
+ }
19
+ throw error;
20
+ }
21
+ if (!stat.isDirectory()) {
22
+ return 'file';
23
+ }
24
+ const entries = (await fs.readdir(target)).filter((entry) => !IGNORED_ENTRIES.has(entry));
25
+ return entries.length === 0 ? 'empty' : 'not-empty';
26
+ }
27
+ /**
28
+ * True when `child` is `parent` or inside it (case-insensitive on Windows and macOS).
29
+ */
30
+ export function isInside(parent, child) {
31
+ const caseInsensitive = process.platform === 'win32' || process.platform === 'darwin';
32
+ const a = path.resolve(parent);
33
+ const b = path.resolve(child);
34
+ const relative = path.relative(caseInsensitive ? a.toLowerCase() : a, caseInsensitive ? b.toLowerCase() : b);
35
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
36
+ }
37
+ /** Expands a leading ~ and resolves against the current directory. */
38
+ export function resolveUserPath(input, base = process.cwd()) {
39
+ const trimmed = input.trim().replace(/^["']|["']$/g, '');
40
+ const expanded = trimmed === '~' || trimmed.startsWith('~/') || trimmed.startsWith('~\\') ? path.join(os.homedir(), trimmed.slice(1)) : trimmed;
41
+ return path.resolve(base, expanded);
42
+ }
43
+ /**
44
+ * Checks that files can be created in `directory` (creating it if needed) by writing a probe file.
45
+ */
46
+ export async function ensureWritableDirectory(directory) {
47
+ await fs.mkdir(directory, { recursive: true });
48
+ const probe = path.join(directory, `.tokocode-write-test-${randomBytes(4).toString('hex')}`);
49
+ await fs.writeFile(probe, '');
50
+ await fs.rm(probe, { force: true });
51
+ }
52
+ /**
53
+ * Free bytes on the volume of `directory` (or the nearest existing parent), null when unknown.
54
+ */
55
+ export async function freeSpace(directory) {
56
+ let current = path.resolve(directory);
57
+ for (;;) {
58
+ try {
59
+ await fs.access(current, fsConstants.F_OK);
60
+ break;
61
+ }
62
+ catch {
63
+ const parent = path.dirname(current);
64
+ if (parent === current) {
65
+ return null;
66
+ }
67
+ current = parent;
68
+ }
69
+ }
70
+ if (typeof fs.statfs !== 'function') {
71
+ return null;
72
+ }
73
+ try {
74
+ const stats = await fs.statfs(current);
75
+ return Number(stats.bavail) * Number(stats.bsize);
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ export async function fileSize(file) {
82
+ try {
83
+ return (await fs.stat(file)).size;
84
+ }
85
+ catch (error) {
86
+ if (error.code === 'ENOENT') {
87
+ return 0;
88
+ }
89
+ throw error;
90
+ }
91
+ }
92
+ /** Deletes a file or folder, ignoring "not found" and other errors (best-effort cleanup). */
93
+ export async function removeQuietly(target) {
94
+ try {
95
+ await fs.rm(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
96
+ }
97
+ catch {
98
+ // Cleanup must never hide the real outcome.
99
+ }
100
+ }
101
+ /**
102
+ * Moves a finished staging folder into place. Rename is atomic on the same volume; Windows
103
+ * antivirus may briefly lock new files, so EPERM/EBUSY are retried before copying instead.
104
+ */
105
+ export async function moveDirectory(from, to) {
106
+ for (let attempt = 0; attempt < 6; attempt++) {
107
+ try {
108
+ await fs.rename(from, to);
109
+ return;
110
+ }
111
+ catch (error) {
112
+ const code = error.code;
113
+ if (code === 'EXDEV') {
114
+ break;
115
+ }
116
+ if ((code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') && attempt < 5) {
117
+ await new Promise((resolve) => setTimeout(resolve, 250 * (attempt + 1)));
118
+ continue;
119
+ }
120
+ throw error;
121
+ }
122
+ }
123
+ await fs.cp(from, to, { recursive: true, errorOnExist: true, force: false });
124
+ await removeQuietly(from);
125
+ }
126
+ export function humanBytes(bytes) {
127
+ if (!Number.isFinite(bytes) || bytes < 0) {
128
+ return '-';
129
+ }
130
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
131
+ let value = bytes;
132
+ let unit = 0;
133
+ while (value >= 1024 && unit < units.length - 1) {
134
+ value /= 1024;
135
+ unit++;
136
+ }
137
+ return `${value.toFixed(unit === 0 ? 0 : value < 10 ? 2 : 1)} ${units[unit]}`;
138
+ }
@@ -0,0 +1,72 @@
1
+ import http, {} from 'node:http';
2
+ import https from 'node:https';
3
+ import { debug } from './logger.js';
4
+ /**
5
+ * Minimal HTTP client on node:http/https: streaming responses, socket idle timeouts and
6
+ * keep-alive, with no dependency on the global fetch (experimental on Node 18).
7
+ */
8
+ const agents = {
9
+ 'http:': new http.Agent({ keepAlive: true, maxSockets: 4 }),
10
+ 'https:': new https.Agent({ keepAlive: true, maxSockets: 4 }),
11
+ };
12
+ export function openRequest(options) {
13
+ return new Promise((resolve, reject) => {
14
+ const url = new URL(options.url);
15
+ const transport = url.protocol === 'http:' ? http : https;
16
+ const headers = { ...options.headers };
17
+ if (options.body !== undefined) {
18
+ headers['Content-Length'] = Buffer.byteLength(options.body);
19
+ }
20
+ debug(`${options.method} ${url.pathname}`, headers);
21
+ const request = transport.request(url, {
22
+ method: options.method,
23
+ headers,
24
+ agent: agents[url.protocol],
25
+ timeout: options.timeoutMs,
26
+ signal: options.signal,
27
+ }, resolve);
28
+ request.on('timeout', () => {
29
+ request.destroy(Object.assign(new Error('Koneksi tidak merespons.'), { code: 'ETIMEDOUT' }));
30
+ });
31
+ request.on('error', reject);
32
+ if (options.body !== undefined) {
33
+ request.write(options.body);
34
+ }
35
+ request.end();
36
+ });
37
+ }
38
+ /** Reads a (small) response body as text, refusing more than `limit` bytes. */
39
+ export function readBody(response, limit = 1024 * 1024) {
40
+ return new Promise((resolve, reject) => {
41
+ const chunks = [];
42
+ let size = 0;
43
+ response.on('data', (chunk) => {
44
+ size += chunk.length;
45
+ if (size > limit) {
46
+ response.destroy(new Error('Respons server terlalu besar.'));
47
+ return;
48
+ }
49
+ chunks.push(chunk);
50
+ });
51
+ response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
52
+ response.on('error', reject);
53
+ response.on('aborted', () => reject(Object.assign(new Error('Koneksi terputus.'), { code: 'ECONNRESET' })));
54
+ });
55
+ }
56
+ /** Seconds from a Retry-After header (seconds or HTTP date), undefined when absent. */
57
+ export function parseRetryAfter(value) {
58
+ const raw = Array.isArray(value) ? value[0] : value;
59
+ if (!raw) {
60
+ return undefined;
61
+ }
62
+ const seconds = Number.parseInt(raw, 10);
63
+ if (Number.isFinite(seconds) && String(seconds) === raw.trim()) {
64
+ return Math.max(0, seconds);
65
+ }
66
+ const date = Date.parse(raw);
67
+ return Number.isFinite(date) ? Math.max(0, Math.ceil((date - Date.now()) / 1000)) : undefined;
68
+ }
69
+ export function destroyAgents() {
70
+ agents['http:'].destroy();
71
+ agents['https:'].destroy();
72
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Debug logging (--debug or TOKOCODE_DEBUG=1) to stderr. Every line passes through redact(),
3
+ * so installation tokens, session secrets and Authorization headers are never printed.
4
+ */
5
+ let enabled = process.env.TOKOCODE_DEBUG === '1';
6
+ export function setDebug(value) {
7
+ enabled = value || process.env.TOKOCODE_DEBUG === '1';
8
+ }
9
+ export function isDebug() {
10
+ return enabled;
11
+ }
12
+ const PATTERNS = [
13
+ // Installation tokens: TK-XXXX-… in any spacing/case.
14
+ [/\bTK[-\s]?(?:[0-9A-Za-z]{4}[-\s]?){5}[0-9A-Za-z]{4}\b/gi, 'TK-****'],
15
+ [/\b[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{24}\b/g, '****'],
16
+ // Download session secrets and bearer headers.
17
+ [/tcs_[A-Za-z0-9_-]{10,}/g, 'tcs_****'],
18
+ [/(authorization|x-tokocode-session)(["']?\s*[:=]\s*["']?)(bearer\s+)?[^\s"',}]+/gi, '$1$2$3****'],
19
+ [/("(?:token|secret|request_id)"\s*:\s*")[^"]*(")/gi, '$1****$2'],
20
+ ];
21
+ export function redact(text) {
22
+ let out = text;
23
+ for (const [pattern, replacement] of PATTERNS) {
24
+ out = out.replace(pattern, replacement);
25
+ }
26
+ return out;
27
+ }
28
+ export function debug(message, data) {
29
+ if (!enabled) {
30
+ return;
31
+ }
32
+ let line = `[debug ${new Date().toISOString()}] ${message}`;
33
+ if (data !== undefined) {
34
+ let serialized;
35
+ try {
36
+ serialized = typeof data === 'string' ? data : JSON.stringify(data);
37
+ }
38
+ catch {
39
+ serialized = String(data);
40
+ }
41
+ line += ' ' + serialized;
42
+ }
43
+ process.stderr.write(redact(line) + '\n');
44
+ }
@@ -0,0 +1,89 @@
1
+ import chalk from 'chalk';
2
+ import { humanBytes } from './filesystem.js';
3
+ /**
4
+ * Download/extract progress bar. On a TTY it redraws one line; when output is piped it prints
5
+ * a line every 10% so logs stay readable.
6
+ */
7
+ export class ProgressBar {
8
+ label;
9
+ total;
10
+ unit;
11
+ started = Date.now();
12
+ lastDraw = 0;
13
+ lastPercentLogged = -10;
14
+ samples = [];
15
+ tty = Boolean(process.stdout.isTTY);
16
+ constructor(label, total, unit = 'bytes') {
17
+ this.label = label;
18
+ this.total = total;
19
+ this.unit = unit;
20
+ }
21
+ update(current, force = false) {
22
+ const now = Date.now();
23
+ this.samples.push([now, current]);
24
+ while (this.samples.length > 2 && now - this.samples[0][0] > 5000) {
25
+ this.samples.shift();
26
+ }
27
+ if (!force && now - this.lastDraw < 100) {
28
+ return;
29
+ }
30
+ this.lastDraw = now;
31
+ const percent = this.total > 0 ? Math.min(100, Math.floor((current / this.total) * 100)) : 0;
32
+ if (!this.tty) {
33
+ if (percent >= this.lastPercentLogged + 10 || force) {
34
+ this.lastPercentLogged = percent - (percent % 10);
35
+ process.stdout.write(` ${this.label} ${percent}% (${this.amount(current)})\n`);
36
+ }
37
+ return;
38
+ }
39
+ const columns = process.stdout.columns ?? 80;
40
+ const width = Math.max(10, Math.min(30, columns - 60));
41
+ const filled = Math.round((percent / 100) * width);
42
+ const bar = chalk.cyan('█'.repeat(filled)) + chalk.dim('░'.repeat(width - filled));
43
+ const rate = this.rate();
44
+ const extra = this.unit === 'bytes' && rate > 0
45
+ ? ` ${humanBytes(rate)}/s` + (this.total > current ? ` · sisa ${formatDuration((this.total - current) / rate)}` : '')
46
+ : '';
47
+ const line = ` ${bar} ${String(percent).padStart(3)}% ${chalk.dim(this.amount(current) + extra)}`;
48
+ process.stdout.write('\r\u001b[2K' + line);
49
+ }
50
+ done(current = this.total) {
51
+ this.update(current, true);
52
+ if (this.tty) {
53
+ process.stdout.write('\r\u001b[2K');
54
+ }
55
+ }
56
+ /** Clears the bar line so a message can be printed (e.g. a retry notice). */
57
+ clear() {
58
+ if (this.tty) {
59
+ process.stdout.write('\r\u001b[2K');
60
+ }
61
+ }
62
+ elapsedSeconds() {
63
+ return (Date.now() - this.started) / 1000;
64
+ }
65
+ amount(current) {
66
+ return this.unit === 'bytes' ? `${humanBytes(current)} / ${humanBytes(this.total)}` : `${current} / ${this.total} file`;
67
+ }
68
+ rate() {
69
+ if (this.samples.length < 2) {
70
+ return 0;
71
+ }
72
+ const [t0, b0] = this.samples[0];
73
+ const [t1, b1] = this.samples[this.samples.length - 1];
74
+ return t1 > t0 ? ((b1 - b0) / (t1 - t0)) * 1000 : 0;
75
+ }
76
+ }
77
+ export function formatDuration(seconds) {
78
+ if (!Number.isFinite(seconds) || seconds < 0) {
79
+ return '-';
80
+ }
81
+ if (seconds < 60) {
82
+ return `${Math.ceil(seconds)} dtk`;
83
+ }
84
+ const minutes = Math.floor(seconds / 60);
85
+ if (minutes < 60) {
86
+ return `${minutes} mnt ${Math.ceil(seconds % 60)} dtk`;
87
+ }
88
+ return `${Math.floor(minutes / 60)} jam ${minutes % 60} mnt`;
89
+ }
@@ -0,0 +1,149 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import chalk from 'chalk';
3
+ import { CancelledError, CliError } from './errors.js';
4
+ import { EXIT } from '../config/constants.js';
5
+ /**
6
+ * Terminal output and prompts. Plain ASCII fallbacks are used where the console cannot show
7
+ * box-drawing characters; colours follow chalk's detection (NO_COLOR / FORCE_COLOR respected).
8
+ */
9
+ const unicode = process.platform !== 'win32' || Boolean(process.env.WT_SESSION) || process.env.TERM_PROGRAM === 'vscode' || process.env.TERM === 'xterm-256color';
10
+ export const symbols = {
11
+ ok: unicode ? '✓' : '√',
12
+ fail: unicode ? '✖' : '×',
13
+ warn: unicode ? '⚠' : '!',
14
+ info: unicode ? 'ℹ' : 'i',
15
+ arrow: unicode ? '›' : '>',
16
+ bullet: unicode ? '•' : '-',
17
+ };
18
+ export const out = {
19
+ line(text = '') {
20
+ process.stdout.write(text + '\n');
21
+ },
22
+ ok(text) {
23
+ out.line(chalk.green(symbols.ok) + ' ' + text);
24
+ },
25
+ warn(text) {
26
+ out.line(chalk.yellow(symbols.warn) + ' ' + text);
27
+ },
28
+ info(text) {
29
+ out.line(chalk.cyan(symbols.info) + ' ' + text);
30
+ },
31
+ fail(text) {
32
+ process.stderr.write(chalk.red(symbols.fail) + ' ' + chalk.bold(text) + '\n');
33
+ },
34
+ muted(text) {
35
+ out.line(chalk.dim(text));
36
+ },
37
+ };
38
+ /** Draws a centred box around lines (the welcome and success banners). */
39
+ export function box(lines, color = chalk.cyan) {
40
+ const width = Math.max(42, ...lines.map((line) => visibleLength(line) + 6));
41
+ const [tl, tr, bl, br, h, v] = unicode ? ['╔', '╗', '╚', '╝', '═', '║'] : ['+', '+', '+', '+', '-', '|'];
42
+ const pad = (text) => {
43
+ const free = width - visibleLength(text);
44
+ const left = Math.floor(free / 2);
45
+ return color(v) + ' '.repeat(left) + text + ' '.repeat(free - left) + color(v);
46
+ };
47
+ const rows = [color(tl + h.repeat(width) + tr), pad(''), ...lines.map(pad), pad(''), color(bl + h.repeat(width) + br)];
48
+ return rows.join('\n');
49
+ }
50
+ export function banner() {
51
+ out.line();
52
+ out.line(box([chalk.bold.white('TOKOCODE CLI'), chalk.cyan('SOURCE CODE INSTALLER')]));
53
+ out.line();
54
+ }
55
+ /** Two-column details ("Produk : …"). */
56
+ export function details(rows) {
57
+ const width = Math.max(...rows.map(([label]) => label.length));
58
+ for (const [label, value] of rows) {
59
+ out.line(`${chalk.dim(label.padEnd(width))} : ${value}`);
60
+ }
61
+ }
62
+ export function step(index, total, label) {
63
+ return `${chalk.dim(`[${index}/${total}]`)} ${label}`;
64
+ }
65
+ function visibleLength(text) {
66
+ // eslint-disable-next-line no-control-regex
67
+ return text.replace(/\u001b\[[0-9;]*m/g, '').length;
68
+ }
69
+ export function isInteractive() {
70
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY) && process.env.CI !== 'true';
71
+ }
72
+ let rl = null;
73
+ function readline() {
74
+ if (!rl) {
75
+ rl = createInterface({ input: process.stdin, output: process.stdout, terminal: Boolean(process.stdin.isTTY) });
76
+ rl.on('SIGINT', () => {
77
+ closePrompts();
78
+ process.emit('SIGINT');
79
+ });
80
+ }
81
+ return rl;
82
+ }
83
+ export function closePrompts() {
84
+ rl?.close();
85
+ rl = null;
86
+ }
87
+ function requireInteractive(question) {
88
+ if (!isInteractive()) {
89
+ throw new CliError('needs_input', `Butuh jawaban interaktif: ${question}`, 'Jalankan di terminal biasa, atau berikan opsi --token, --dir, --name, dan --yes.', EXIT.usage);
90
+ }
91
+ }
92
+ /** Asks a question; an empty answer returns `fallback`. */
93
+ export async function ask(question, fallback = '') {
94
+ requireInteractive(question);
95
+ const suffix = fallback !== '' ? chalk.dim(` (${fallback})`) : '';
96
+ try {
97
+ const answer = await readline().question(`${chalk.cyan('?')} ${chalk.bold(question)}${suffix}\n${chalk.cyan(symbols.arrow)} `);
98
+ return answer.trim() === '' ? fallback : answer.trim();
99
+ }
100
+ catch (error) {
101
+ if (error.name === 'AbortError') {
102
+ throw new CancelledError();
103
+ }
104
+ throw error;
105
+ }
106
+ }
107
+ /** Yes/no question; Enter picks the default. */
108
+ export async function confirm(question, defaultYes = true) {
109
+ requireInteractive(question);
110
+ const hint = defaultYes ? 'Y/n' : 'y/N';
111
+ for (;;) {
112
+ const answer = (await readline().question(`${chalk.cyan('?')} ${chalk.bold(question)} ${chalk.dim(`(${hint})`)} `)).trim().toLowerCase();
113
+ if (answer === '') {
114
+ return defaultYes;
115
+ }
116
+ if (['y', 'ya', 'yes'].includes(answer)) {
117
+ return true;
118
+ }
119
+ if (['n', 'no', 't', 'tidak'].includes(answer)) {
120
+ return false;
121
+ }
122
+ out.muted('Jawab y (ya) atau n (tidak).');
123
+ }
124
+ }
125
+ /** Numbered menu; returns the chosen value. */
126
+ export async function choose(question, options) {
127
+ requireInteractive(question);
128
+ out.line(`${chalk.cyan('?')} ${chalk.bold(question)}`);
129
+ options.forEach((option, index) => out.line(` ${chalk.cyan(String(index + 1))}. ${option.label}`));
130
+ for (;;) {
131
+ const answer = (await readline().question(`${chalk.cyan(symbols.arrow)} Pilih 1-${options.length}: `)).trim();
132
+ const picked = options[Number.parseInt(answer, 10) - 1];
133
+ if (picked) {
134
+ return picked.value;
135
+ }
136
+ out.muted(`Ketik angka 1 sampai ${options.length}.`);
137
+ }
138
+ }
139
+ /** Prints a CliError the way customers see it: message, then what to do. */
140
+ export function printError(error) {
141
+ out.line();
142
+ out.fail(error.message);
143
+ if (error.hint) {
144
+ process.stderr.write(chalk.yellow(' ' + error.hint.split('\n').join('\n ')) + '\n');
145
+ }
146
+ if (error.code !== 'cancelled' && error.code !== 'unexpected') {
147
+ process.stderr.write(chalk.dim(` Kode: ${error.code}`) + '\n');
148
+ }
149
+ }