tokocode 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 — 2026-11-16
4
+
5
+ - Pembaruan otomatis: setiap kali dijalankan lewat `npx`, CLI memeriksa versi terbaru di npm (paling sering tiap 30 menit, maksimal 2,5 detik) dan langsung beralih ke versi itu dengan perintah yang sama. Cache npm yang basi tidak lagi membuat versi lama terpakai. Matikan dengan `--no-update` atau `TOKOCODE_NO_UPDATE=1`; terpasang global (`npm i -g`) hanya diberi petunjuk.
6
+ - `npx tokocode update`: periksa dan unduh versi terbaru sekarang.
7
+ - Tampilan baru: logo Tokocode.id (tas dengan `</>`, warna merek) di tengah layar, sambutan dan menu yang rapi; perintah lain diawali satu baris merek.
8
+
9
+ ## 1.1.0 — 2026-11-17
10
+
11
+ - `search` / `info`: katalog TokoCode dari terminal (harga, label gratis, jenis, `--json`).
12
+ - `add <nama...>`: produk gratis terpasang tanpa akun (unduh, SHA-256, ekstraksi aman ke `./<nama>`); produk berbayar dipasang dari akun setelah `login`, tanpa menyalin token.
13
+ - `npx tokocode` tanpa perintah membuka menu: pasang komponen gratis, cari di katalog, pasang produk yang sudah dibeli, pasang dengan installation token, atau lihat semua perintah. Dengan `--token`, `TOKOCODE_TOKEN`, `--yes`, unduhan tertunda, atau tanpa terminal (skrip/CI), alur installation token tetap berjalan langsung.
14
+ - Perbaikan Windows: pertanyaan yang muncul setelah spinner (misalnya lokasi folder setelah verifikasi token) tidak lagi menunggu tanpa bisa diketik.
15
+ - `login` (device login: kode di terminal, satu klik "Izinkan" di browser), `whoami`, `library`, `logout`. Kunci akses disimpan dengan izin 0600 dan disamarkan di log.
16
+
3
17
  ## 1.0.0 — 2026-11-07
4
18
 
5
19
  Rilis pertama.
package/README.md CHANGED
@@ -34,6 +34,27 @@ Status : Siap diinstal
34
34
  INSTALASI BERHASIL!
35
35
  ```
36
36
 
37
+ ## Perintah utama (versi 1.1)
38
+
39
+ | Perintah | Fungsi |
40
+ |---|---|
41
+ | `npx tokocode search [kata] [--gratis] [--jenis komponen|template|jasa]` | Cari produk di katalog, lengkap dengan harga dan label gratis |
42
+ | `npx tokocode info <nama>` | Detail produk: harga, versi, ukuran paket, cara memasang |
43
+ | `npx tokocode add <nama...>` | Pasang produk **gratis** tanpa akun, atau produk yang sudah Anda beli (setelah `login`) ke `./<nama>` |
44
+ | `npx tokocode login` | Hubungkan CLI ke akun: buka tautan, klik **Izinkan**, selesai (tanpa mengetik password) |
45
+ | `npx tokocode library` | Produk di akun Anda yang siap dipasang |
46
+ | `npx tokocode whoami` · `logout` | Akun yang terhubung · putuskan CLI dari akun |
47
+ | `npx tokocode` / `--token TK-…` | Pasang dengan installation token (cara di bawah, tetap didukung) |
48
+ | `npx tokocode doctor` | Periksa Node.js, koneksi, dan izin folder |
49
+
50
+ ```bash
51
+ npx tokocode add liquid-toggle # komponen gratis, langsung terpasang
52
+ npx tokocode login # sekali saja, untuk produk berbayar
53
+ npx tokocode add template-kopi-senja # produk yang sudah dibeli, tanpa menyalin token
54
+ ```
55
+
56
+ Login disimpan di `%APPDATA%\tokocode\auth.json` (Windows) atau `~/.config/tokocode/auth.json` (izin 0600); server hanya menyimpan hash-nya, berlaku 90 hari, dan bisa diputus kapan saja di **Akun > Instalasi CLI**. Opsi `--json` pada `search`, `info`, `whoami`, dan `library` memberi keluaran untuk skrip.
57
+
37
58
  ## 1. Persyaratan
38
59
 
39
60
  | Kebutuhan | Keterangan |
@@ -0,0 +1,147 @@
1
+ import { spawn } from 'node:child_process';
2
+ import os from 'node:os';
3
+ import chalk from 'chalk';
4
+ import ora from 'ora';
5
+ import { DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
6
+ import { ApiClient } from '../services/api.service.js';
7
+ import { forgetLogin, loadLogin, saveLogin } from '../services/auth.service.js';
8
+ import { CliError, toCliError } from '../utils/errors.js';
9
+ import { debug } from '../utils/logger.js';
10
+ import { box, brandLine, details, out } from '../utils/terminal.js';
11
+ import { normalizeApiUrl } from '../utils/validation.js';
12
+ import { printTable } from './catalog.js';
13
+ import { withSpinner } from './install.js';
14
+ function client(api) {
15
+ return new ApiClient(normalizeApiUrl(api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
16
+ }
17
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
18
+ /** Opens the approval page in the default browser; failure is fine (the link is printed). */
19
+ function openBrowser(url) {
20
+ try {
21
+ const child = process.platform === 'win32'
22
+ ? spawn('cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true })
23
+ : spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [url], { detached: true, stdio: 'ignore' });
24
+ child.on('error', (error) => debug('browser not opened', error.message));
25
+ child.unref();
26
+ }
27
+ catch (error) {
28
+ debug('browser not opened', error.message);
29
+ }
30
+ }
31
+ /**
32
+ * `npx tokocode login`: shows a code, opens the browser, and waits for one click on "Izinkan".
33
+ */
34
+ export async function runLogin(options) {
35
+ brandLine();
36
+ const api = client(options.api);
37
+ const start = await withSpinner('Menyiapkan login…', () => api.deviceStart({ ...ApiClient.clientInfo(), host: os.hostname().slice(0, 60) }), { silentSuccess: true });
38
+ out.line();
39
+ out.line(box([chalk.bold.white('MASUK KE TOKOCODE'), '', `Kode: ${chalk.bold.cyan(start.user_code)}`], chalk.cyan));
40
+ out.line();
41
+ out.line(`Buka tautan ini lalu klik ${chalk.bold('Izinkan')}:`);
42
+ out.line(chalk.cyan.underline(start.verification_url_complete));
43
+ out.line();
44
+ if (options.browser !== false && process.stdout.isTTY) {
45
+ openBrowser(start.verification_url_complete);
46
+ out.muted('Browser dibuka otomatis. Pastikan kodenya sama dengan di atas.');
47
+ }
48
+ const spinner = ora({ text: 'Menunggu persetujuan di browser…', stream: process.stdout, discardStdin: false }).start();
49
+ const deadline = Date.now() + start.expires_in * 1000;
50
+ let interval = Math.max(2, start.interval) * 1000;
51
+ for (;;) {
52
+ await sleep(interval);
53
+ try {
54
+ const granted = await api.deviceToken(start.device_code);
55
+ await saveLogin(api.baseUrl, { token: granted.access_token, user: granted.user, expires_at: granted.expires_at, saved_at: new Date().toISOString() });
56
+ spinner.succeed(`Terhubung sebagai ${chalk.bold(granted.user.name)} ${chalk.dim(`(${granted.user.email})`)}`);
57
+ out.line();
58
+ out.line(`Lihat produk Anda: ${chalk.cyan(`npx ${PACKAGE_NAME} library`)}`);
59
+ out.line(`Pasang produk: ${chalk.cyan(`npx ${PACKAGE_NAME} add <nama>`)}`);
60
+ return;
61
+ }
62
+ catch (error) {
63
+ const cliError = toCliError(error);
64
+ if (cliError.code === 'authorization_pending' && Date.now() < deadline) {
65
+ continue;
66
+ }
67
+ if (cliError.code === 'rate_limited') {
68
+ interval = Math.min(interval * 2, 15000);
69
+ continue;
70
+ }
71
+ spinner.fail(cliError.code === 'authorization_pending' ? 'Waktu persetujuan habis' : cliError.message);
72
+ if (cliError.code === 'authorization_pending') {
73
+ throw new CliError('login_expired', 'Kode masuk sudah kedaluwarsa (10 menit).', `Jalankan ulang: npx ${PACKAGE_NAME} login`);
74
+ }
75
+ throw cliError;
76
+ }
77
+ }
78
+ }
79
+ export async function runLogout(options) {
80
+ const api = client(options.api);
81
+ const login = await loadLogin(api.baseUrl);
82
+ if (!login) {
83
+ out.info('CLI ini belum terhubung ke akun TokoCode.');
84
+ return;
85
+ }
86
+ try {
87
+ await api.logout(login.token);
88
+ }
89
+ catch (error) {
90
+ debug('logout not confirmed by the server', error.message);
91
+ }
92
+ await forgetLogin(api.baseUrl);
93
+ out.ok(`Keluar dari akun ${chalk.bold(login.user.name)}. Kunci akses di perangkat ini sudah dihapus.`);
94
+ }
95
+ async function requireLogin(api) {
96
+ const login = await loadLogin(api.baseUrl);
97
+ if (!login) {
98
+ throw new CliError('auth_required', 'Anda belum masuk ke TokoCode CLI.', `Jalankan: npx ${PACKAGE_NAME} login`);
99
+ }
100
+ return login.token;
101
+ }
102
+ async function forgetIfRejected(api, error) {
103
+ const cliError = toCliError(error);
104
+ if (cliError.code === 'auth_invalid') {
105
+ await forgetLogin(api.baseUrl);
106
+ }
107
+ throw cliError;
108
+ }
109
+ export async function runWhoami(options) {
110
+ const api = client(options.api);
111
+ const token = await requireLogin(api);
112
+ const me = await withSpinner('Memeriksa akun…', () => api.me(token), { silentSuccess: true }).catch((error) => forgetIfRejected(api, error));
113
+ if (options.json) {
114
+ out.line(JSON.stringify(me, null, 2));
115
+ return;
116
+ }
117
+ details([
118
+ ['Akun', `${chalk.bold(me.user.name)} ${chalk.dim(me.user.email)}`],
119
+ ['Produk', `${me.library} siap dipasang`],
120
+ ['Login berlaku', new Date(me.token.expires_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })],
121
+ ['Toko', api.baseUrl],
122
+ ]);
123
+ }
124
+ /**
125
+ * `npx tokocode library`: paid and free products of the signed-in customer.
126
+ */
127
+ export async function runLibrary(options) {
128
+ if (!options.json) {
129
+ brandLine();
130
+ }
131
+ const api = client(options.api);
132
+ const token = await requireLogin(api);
133
+ const { items } = await withSpinner('Mengambil produk di akun Anda…', () => api.library(token), { silentSuccess: true }).catch((error) => forgetIfRejected(api, error));
134
+ if (options.json) {
135
+ out.line(JSON.stringify(items, null, 2));
136
+ return;
137
+ }
138
+ if (items.length === 0) {
139
+ out.info('Belum ada produk di akun Anda.');
140
+ out.muted(` Lihat yang gratis: npx ${PACKAGE_NAME} search --gratis`);
141
+ return;
142
+ }
143
+ out.line();
144
+ printTable(items.map((item) => ({ ...item, extra: item.source === 'paid' && item.invoice_no ? item.invoice_no : undefined })));
145
+ out.line();
146
+ out.muted(`${items.length} produk. Pasang: npx ${PACKAGE_NAME} add <nama>`);
147
+ }
@@ -0,0 +1,201 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { createWriteStream } from 'node:fs';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { Transform } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import chalk from 'chalk';
8
+ import ora from 'ora';
9
+ import { CLI_VERSION, DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
10
+ import { ApiClient } from '../services/api.service.js';
11
+ import { loadLogin } from '../services/auth.service.js';
12
+ import { sameChecksum, sha256File } from '../services/checksum.service.js';
13
+ import { extractArchive } from '../services/extraction.service.js';
14
+ import { stateDir } from '../services/state.service.js';
15
+ import { removeOnInterrupt } from '../utils/cleanup.js';
16
+ import { CliError, toCliError } from '../utils/errors.js';
17
+ import { directoryState, fileSize, humanBytes, moveDirectory, removeQuietly } from '../utils/filesystem.js';
18
+ import { formatDuration, ProgressBar } from '../utils/progress.js';
19
+ import { box, brandLine, details, out } from '../utils/terminal.js';
20
+ import { compareVersions, normalizeApiUrl } from '../utils/validation.js';
21
+ import { chooseTarget, runLibraryInstall, withSpinner } from './install.js';
22
+ const KIND_LABEL = { komponen: 'Komponen UI', template: 'Template / source code', jasa: 'Layanan' };
23
+ /**
24
+ * `npx tokocode add <name...>`: free products install right away (no account); paid products install from the
25
+ * signed-in account (`npx tokocode login`), otherwise the CLI explains how to get them.
26
+ */
27
+ export async function runAdd(names, options) {
28
+ brandLine();
29
+ const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
30
+ await assertAvailable(api);
31
+ const many = names.length > 1;
32
+ for (const [index, raw] of names.entries()) {
33
+ const name = raw.trim().toLowerCase();
34
+ if (many) {
35
+ out.line();
36
+ out.line(chalk.bold(`[${index + 1}/${names.length}] ${name}`));
37
+ }
38
+ const { product } = await withSpinner(`Mencari ${chalk.bold(name)} di katalog…`, () => api.product(name), { silentSuccess: true });
39
+ const perItem = many ? { ...options, name: undefined } : options;
40
+ if (product.install === 'service') {
41
+ throw new CliError('product_unavailable', `${product.title} adalah layanan yang dikerjakan tim, bukan paket untuk dipasang.`, `Pesan di website: ${product.url}`);
42
+ }
43
+ if (product.free) {
44
+ await installFree(api, product, perItem);
45
+ continue;
46
+ }
47
+ const login = await loadLogin(api.baseUrl);
48
+ if (!login) {
49
+ throw new CliError('auth_required', `${product.title} berbayar (${product.price_label}).`, [
50
+ `1. Beli di website: ${product.url}`,
51
+ `2. Hubungkan CLI sekali saja: npx ${PACKAGE_NAME} login`,
52
+ `3. Jalankan lagi: npx ${PACKAGE_NAME} add ${product.name}`,
53
+ ].join('\n'));
54
+ }
55
+ try {
56
+ await runLibraryInstall(api, product.name, login.token, { ...perItem, dir: perItem.dir ?? process.cwd(), name: perItem.name ?? product.name });
57
+ }
58
+ catch (error) {
59
+ const cliError = toCliError(error);
60
+ if (cliError.code === 'not_owned') {
61
+ throw new CliError('not_owned', `${product.title} belum ada di akun ${login.user.name}.`, `Beli di ${product.url} (${product.price_label}), lalu jalankan perintah ini lagi.`);
62
+ }
63
+ if (cliError.code === 'auth_invalid') {
64
+ throw new CliError('auth_invalid', cliError.message, `Masuk lagi: npx ${PACKAGE_NAME} login`);
65
+ }
66
+ throw cliError;
67
+ }
68
+ }
69
+ }
70
+ async function assertAvailable(api) {
71
+ const meta = await withSpinner('Menghubungi server TokoCode…', () => api.meta(), { silentSuccess: true });
72
+ if (!meta.enabled) {
73
+ throw new CliError('cli_disabled', 'TokoCode CLI sedang dinonaktifkan.', meta.maintenance_message || 'Silakan coba lagi nanti.');
74
+ }
75
+ if (compareVersions(CLI_VERSION, meta.min_cli_version) < 0) {
76
+ throw new CliError('cli_outdated', `Versi TokoCode CLI Anda (${CLI_VERSION}) sudah tidak didukung.`, `Jalankan versi terbaru: npx ${PACKAGE_NAME}@latest`);
77
+ }
78
+ }
79
+ /**
80
+ * Free product: download (resumable) → SHA-256 check → extraction into a new folder. Nothing is executed.
81
+ */
82
+ async function installFree(api, product, options) {
83
+ const pkg = product.package;
84
+ if (!pkg) {
85
+ throw new CliError('package_unavailable', `Paket ${product.title} sedang disiapkan.`, `Coba lagi nanti, atau unduh dari ${product.url}`);
86
+ }
87
+ out.ok(`${chalk.bold(product.title)} ${chalk.green('· Gratis')}`);
88
+ details([
89
+ ['Jenis', [KIND_LABEL[product.kind] ?? product.kind, product.group].filter(Boolean).join(' · ')],
90
+ ['Versi', pkg.version || product.version],
91
+ ['Ukuran', humanBytes(pkg.size)],
92
+ ]);
93
+ out.line();
94
+ // One command, no questions: ./<name> in the current folder (asked again only when that folder has files).
95
+ const target = await chooseTarget({ suggested_folder: product.name, package: pkg }, { ...options, dir: options.dir ?? process.cwd(), name: options.name ?? product.name });
96
+ out.line();
97
+ await fs.mkdir(stateDir(), { recursive: true });
98
+ const part = path.join(stateDir(), `free-${product.name}-${pkg.sha256.slice(0, 16)}.zip.part`);
99
+ const started = Date.now();
100
+ await downloadFree(api, product.name, pkg, part);
101
+ const spinner = ora({ text: 'Memverifikasi integritas file (SHA-256)', stream: process.stdout, discardStdin: false }).start();
102
+ const checksum = await sha256File(part);
103
+ if (!sameChecksum(checksum, pkg.sha256)) {
104
+ spinner.fail('Checksum file tidak cocok');
105
+ await removeQuietly(part);
106
+ throw new CliError('checksum_mismatch', 'Checksum file tidak cocok dengan server.', `File rusak saat diunduh dan sudah dihapus. Jalankan ulang: npx ${PACKAGE_NAME} add ${product.name}`);
107
+ }
108
+ spinner.succeed(`Integritas file cocok ${chalk.dim('sha256 ' + checksum.slice(0, 12) + '…')}`);
109
+ const files = await extractInto(part, target);
110
+ await removeQuietly(part);
111
+ out.line();
112
+ out.line(box([chalk.bold.green('TERPASANG!'), chalk.dim(`${product.title} · Gratis`)], chalk.green));
113
+ out.line();
114
+ details([
115
+ ['Lokasi', chalk.cyan(target)],
116
+ ['Isi', `${files} file · ${humanBytes(pkg.size)} · ${formatDuration((Date.now() - started) / 1000)}`],
117
+ ]);
118
+ out.line();
119
+ out.line(chalk.bold('Langkah selanjutnya:'));
120
+ const relative = path.relative(process.cwd(), target) || '.';
121
+ out.line(`1. Buka ${chalk.cyan(path.join(relative, 'index.html'))} di browser untuk melihat contohnya.`);
122
+ out.line(`2. Baca ${chalk.cyan(path.join(relative, 'README.md'))}: cara menempel komponen ke halaman Anda.`);
123
+ if (await exists(path.join(target, 'i18n.js'))) {
124
+ out.line(`3. Bahasa Indonesia: tambahkan ${chalk.cyan('<html lang="id">')} atau ${chalk.cyan('#lang=id')}; lihat bagian "Bahasa" di README.`);
125
+ }
126
+ out.line();
127
+ out.muted('Tidak ada script dari paket yang dijalankan otomatis.');
128
+ }
129
+ async function downloadFree(api, name, pkg, part) {
130
+ let start = await fileSize(part).catch(() => 0);
131
+ if (start > pkg.size) {
132
+ await removeQuietly(part);
133
+ start = 0;
134
+ }
135
+ const bar = new ProgressBar('Mengunduh', pkg.size);
136
+ const forget = removeOnInterrupt(part);
137
+ try {
138
+ if (start < pkg.size) {
139
+ const response = await api.openFreePackage(name, start, pkg.sha256);
140
+ if (response.statusCode === 200) {
141
+ start = 0; // the server sent the whole file (new build or no range support)
142
+ }
143
+ if (response.statusCode !== 416) {
144
+ let received = start;
145
+ const counter = new Transform({
146
+ transform(chunk, _encoding, callback) {
147
+ received += chunk.length;
148
+ bar.update(received);
149
+ callback(null, chunk);
150
+ },
151
+ });
152
+ await pipeline(response, counter, createWriteStream(part, { flags: start > 0 ? 'a' : 'w' }));
153
+ }
154
+ else {
155
+ response.resume();
156
+ }
157
+ }
158
+ bar.done(pkg.size);
159
+ forget();
160
+ out.ok(`Diunduh ${chalk.dim(`${humanBytes(pkg.size)} · ${formatDuration(bar.elapsedSeconds())}`)}`);
161
+ }
162
+ catch (error) {
163
+ bar.clear();
164
+ forget();
165
+ throw toCliError(error);
166
+ }
167
+ }
168
+ async function extractInto(zip, target) {
169
+ const parent = path.dirname(target);
170
+ await fs.mkdir(parent, { recursive: true });
171
+ const status = await directoryState(target);
172
+ if (status === 'not-empty' || status === 'file') {
173
+ throw new CliError('target_not_empty', `Folder ${target} sudah berisi file.`, 'Pilih nama folder lain dengan --name. File Anda tidak diubah.');
174
+ }
175
+ const staging = path.join(parent, `.tokocode-${path.basename(target)}-${randomBytes(4).toString('hex')}`);
176
+ const forget = removeOnInterrupt(staging);
177
+ const spinner = ora({ text: 'Mengekstrak file', stream: process.stdout, discardStdin: false }).start();
178
+ try {
179
+ const result = await extractArchive(zip, staging, {
180
+ onProgress: (written, total) => {
181
+ spinner.text = `Mengekstrak file ${chalk.dim(`${total > 0 ? Math.floor((written / total) * 100) : 100}%`)}`;
182
+ },
183
+ });
184
+ if (status === 'empty') {
185
+ await fs.rm(target, { recursive: true, force: true });
186
+ }
187
+ await moveDirectory(staging, target);
188
+ forget();
189
+ spinner.succeed(`Diekstrak ${chalk.dim(`${result.files} file`)}`);
190
+ return result.files;
191
+ }
192
+ catch (error) {
193
+ spinner.fail('Ekstraksi gagal');
194
+ await removeQuietly(staging);
195
+ forget();
196
+ throw toCliError(error);
197
+ }
198
+ }
199
+ async function exists(file) {
200
+ return fs.stat(file).then(() => true, () => false);
201
+ }
@@ -0,0 +1,97 @@
1
+ import chalk from 'chalk';
2
+ import { DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
3
+ import { ApiClient } from '../services/api.service.js';
4
+ import { CliError } from '../utils/errors.js';
5
+ import { humanBytes } from '../utils/filesystem.js';
6
+ import { details, out } from '../utils/terminal.js';
7
+ import { normalizeApiUrl } from '../utils/validation.js';
8
+ import { withSpinner } from './install.js';
9
+ const KINDS = ['komponen', 'template', 'jasa'];
10
+ const KIND_LABEL = { komponen: 'Komponen', template: 'Template', jasa: 'Layanan' };
11
+ function client(api) {
12
+ return new ApiClient(normalizeApiUrl(api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
13
+ }
14
+ /** Pads with the visible width (colours do not count). */
15
+ function cell(text, width) {
16
+ const plain = text.length > width ? text.slice(0, Math.max(1, width - 1)) + '…' : text;
17
+ return plain + ' '.repeat(Math.max(0, width - plain.length));
18
+ }
19
+ export function printTable(items) {
20
+ const columns = process.stdout.columns && process.stdout.columns > 60 ? process.stdout.columns : 100;
21
+ const nameWidth = Math.min(30, Math.max(8, ...items.map((item) => item.name.length)));
22
+ const priceWidth = 11;
23
+ const kindWidth = 18;
24
+ const titleWidth = Math.max(16, columns - nameWidth - priceWidth - kindWidth - 8);
25
+ out.line(chalk.dim(`${cell('NAMA', nameWidth)} ${cell('PRODUK', titleWidth)} ${cell('JENIS', kindWidth)} HARGA`));
26
+ for (const item of items) {
27
+ const kind = [KIND_LABEL[item.kind] ?? item.kind, item.group].filter(Boolean).join(' · ');
28
+ const price = item.free ? chalk.green(cell('Gratis', priceWidth)) : cell(item.price_label, priceWidth);
29
+ out.line(`${chalk.cyan(cell(item.name, nameWidth))} ${cell(item.title, titleWidth)} ${chalk.dim(cell(kind, kindWidth))} ${price}${item.extra ? ' ' + chalk.dim(item.extra) : ''}`);
30
+ }
31
+ }
32
+ /**
33
+ * `npx tokocode search [kata...] [--gratis] [--jenis komponen|template|jasa] [--json]`
34
+ */
35
+ export async function runSearch(words, options) {
36
+ const kind = options.jenis?.toLowerCase();
37
+ if (kind && !KINDS.includes(kind)) {
38
+ throw new CliError('invalid_option', `Jenis "${options.jenis}" tidak dikenal.`, `Pilih salah satu: ${KINDS.join(', ')}`, 2);
39
+ }
40
+ const query = words.join(' ').trim();
41
+ const api = client(options.api);
42
+ const { items } = await withSpinner('Mencari di katalog TokoCode…', () => api.catalog({ q: query, kind, free: options.gratis }), { silentSuccess: true });
43
+ if (options.json) {
44
+ out.line(JSON.stringify(items, null, 2));
45
+ return;
46
+ }
47
+ if (items.length === 0) {
48
+ out.warn(`Tidak ada produk yang cocok${query ? ` dengan "${query}"` : ''}.`);
49
+ out.muted(` Coba kata lain, atau lihat semuanya: npx ${PACKAGE_NAME} search`);
50
+ return;
51
+ }
52
+ out.line();
53
+ printTable(items);
54
+ out.line();
55
+ const free = items.filter((item) => item.free).length;
56
+ out.muted(`${items.length} produk${free > 0 ? ` · ${free} gratis` : ''}. Detail: npx ${PACKAGE_NAME} info <nama> · Pasang: npx ${PACKAGE_NAME} add <nama>`);
57
+ }
58
+ /**
59
+ * `npx tokocode info <nama>`
60
+ */
61
+ export async function runInfo(name, options) {
62
+ const api = client(options.api);
63
+ const { product } = await withSpinner(`Mengambil detail ${chalk.bold(name)}…`, () => api.product(name.trim().toLowerCase()), { silentSuccess: true });
64
+ if (options.json) {
65
+ out.line(JSON.stringify(product, null, 2));
66
+ return;
67
+ }
68
+ out.line();
69
+ out.line(chalk.bold(product.title) + (product.free ? chalk.green(' Gratis') : ''));
70
+ if (product.summary) {
71
+ out.line(chalk.dim(product.summary));
72
+ }
73
+ out.line();
74
+ const rows = [
75
+ ['Nama CLI', chalk.cyan(product.name)],
76
+ ['Jenis', [KIND_LABEL[product.kind] ?? product.kind, product.group ?? product.category].filter(Boolean).join(' · ')],
77
+ ['Harga', product.free ? chalk.green('Gratis') : product.price_label],
78
+ ];
79
+ if (product.version) {
80
+ rows.push(['Versi', product.version]);
81
+ }
82
+ if (product.package) {
83
+ rows.push(['Paket', `${product.package.file_name} · ${humanBytes(product.package.size)}`]);
84
+ }
85
+ rows.push(['Halaman', product.url]);
86
+ details(rows);
87
+ out.line();
88
+ if (product.install === 'free') {
89
+ out.line(`Pasang sekarang: ${chalk.cyan(`npx ${PACKAGE_NAME} add ${product.name}`)}`);
90
+ }
91
+ else if (product.install === 'purchase') {
92
+ out.line(`Setelah membeli: ${chalk.cyan(`npx ${PACKAGE_NAME} login`)} lalu ${chalk.cyan(`npx ${PACKAGE_NAME} add ${product.name}`)}`);
93
+ }
94
+ else {
95
+ out.line(`Layanan dikerjakan tim TokoCode. Pesan di: ${product.url}`);
96
+ }
97
+ }
@@ -5,7 +5,7 @@ import { ApiClient } from '../services/api.service.js';
5
5
  import { pendingStates, stateDir } from '../services/state.service.js';
6
6
  import { toCliError } from '../utils/errors.js';
7
7
  import { ensureWritableDirectory, freeSpace, humanBytes } from '../utils/filesystem.js';
8
- import { out, symbols } from '../utils/terminal.js';
8
+ import { brandLine, out, symbols } from '../utils/terminal.js';
9
9
  import { compareVersions, normalizeApiUrl } from '../utils/validation.js';
10
10
  /**
11
11
  * `tokocode doctor`: checks everything an installation needs and explains what to fix.
@@ -13,6 +13,7 @@ import { compareVersions, normalizeApiUrl } from '../utils/validation.js';
13
13
  * @returns true when no blocking problem was found
14
14
  */
15
15
  export async function runDoctor(apiOption) {
16
+ brandLine();
16
17
  let ok = true;
17
18
  const pass = (label, detail = '') => out.line(`${chalk.green(symbols.ok)} ${label}${detail ? chalk.dim(' · ' + detail) : ''}`);
18
19
  const fail = (label, hint) => {
@@ -4,12 +4,28 @@ import { PACKAGE_NAME } from '../config/constants.js';
4
4
  export function helpFooter() {
5
5
  const cmd = `npx ${PACKAGE_NAME}`;
6
6
  return `
7
- ${chalk.bold('Contoh:')}
8
- ${chalk.cyan(cmd)} Mode interaktif (disarankan)
7
+ ${chalk.bold('Katalog & produk gratis (tanpa akun):')}
8
+ ${chalk.cyan(`${cmd} search tombol --gratis`)} Cari produk (--jenis komponen|template|jasa)
9
+ ${chalk.cyan(`${cmd} info otp-verify`)} Detail, harga, dan cara memasang
10
+ ${chalk.cyan(`${cmd} add liquid-toggle`)} Pasang produk gratis ke ./liquid-toggle
11
+
12
+ ${chalk.bold('Produk yang sudah dibeli (sekali login):')}
13
+ ${chalk.cyan(`${cmd} login`)} Setujui dengan satu klik di browser
14
+ ${chalk.cyan(`${cmd} library`)} Produk di akun Anda
15
+ ${chalk.cyan(`${cmd} add template-kopi-senja`)} Pasang tanpa menyalin token
16
+ ${chalk.cyan(`${cmd} whoami`)} · ${chalk.cyan(`${cmd} logout`)}
17
+
18
+ ${chalk.bold('Dengan installation token:')}
19
+ ${chalk.cyan(cmd)} Menu: gratis, cari, akun, atau token
9
20
  ${chalk.cyan(`${cmd} --token TK-XXXX-… --name klinik`)} Langsung dengan token dan nama folder
10
21
  ${chalk.cyan(`${cmd} --dir D:\\Projects --name "toko saya"`)} Pilih lokasi lain (nama dengan spasi diberi tanda kutip)
11
22
  ${chalk.cyan(`${cmd} doctor`)} Periksa koneksi dan kesiapan komputer
12
23
 
24
+ ${chalk.bold('Pembaruan otomatis')}
25
+ Setiap kali dijalankan lewat npx, CLI memeriksa versi terbaru di npm (maks. tiap 30 menit)
26
+ dan langsung memakai versi itu. ${chalk.cyan(`${cmd} update`)} memeriksa sekarang juga.
27
+ Matikan dengan --no-update atau TOKOCODE_NO_UPDATE=1.
28
+
13
29
  ${chalk.bold('Installation token')}
14
30
  Buat di website TokoCode: Akun > Instalasi CLI > Buat token.
15
31
  Token sekali pakai, hanya ditampilkan sekali, dan bisa dibuat ulang bila hilang.
@@ -22,6 +38,7 @@ ${chalk.bold('Variabel lingkungan')}
22
38
  TOKOCODE_TOKEN Token (alternatif --token; tidak disimpan)
23
39
  TOKOCODE_API_URL Alamat toko bila berbeda dari bawaan
24
40
  TOKOCODE_DEBUG=1 Log diagnosis (token dan secret selalu disamarkan)
41
+ TOKOCODE_NO_UPDATE=1 Jangan memperbarui CLI otomatis
25
42
  NO_COLOR=1 Matikan warna
26
43
  `;
27
44
  }
@@ -0,0 +1,103 @@
1
+ import chalk from 'chalk';
2
+ import { DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
3
+ import { ApiClient } from '../services/api.service.js';
4
+ import { loadLogin } from '../services/auth.service.js';
5
+ import { pendingStates } from '../services/state.service.js';
6
+ import { ask, banner, centerLine, choose, divider, isInteractive, out } from '../utils/terminal.js';
7
+ import { normalizeApiUrl } from '../utils/validation.js';
8
+ import { runLibrary, runLogin } from './account.js';
9
+ import { runAdd } from './add.js';
10
+ import { printTable, runSearch } from './catalog.js';
11
+ import { runInstall, withSpinner } from './install.js';
12
+ /**
13
+ * `npx tokocode` without a command. In a terminal it opens a menu (free components, search, the customer's
14
+ * products, installation token, help); with --token, TOKOCODE_TOKEN, an unfinished download, or without a
15
+ * terminal (scripts, CI) it keeps the original installation-token flow.
16
+ */
17
+ export async function runHome(options) {
18
+ const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
19
+ const direct = Boolean(options.token || process.env.TOKOCODE_TOKEN || options.yes || !isInteractive());
20
+ if (direct || (options.resume !== false && (await pendingStates(api.baseUrl)).length > 0)) {
21
+ await runInstall(options);
22
+ return;
23
+ }
24
+ banner();
25
+ const login = await loadLogin(api.baseUrl);
26
+ centerLine(chalk.bold('Selamat datang!') + chalk.dim(' Pasang komponen dan source code langsung ke folder project Anda.'));
27
+ if (login) {
28
+ centerLine(chalk.green('● ') + chalk.dim(`Masuk sebagai ${login.user.name || login.user.email}`));
29
+ }
30
+ out.line();
31
+ divider();
32
+ const choice = await choose('Apa yang ingin Anda lakukan?', [
33
+ { value: 'free', label: `Pasang komponen gratis ${chalk.dim('(tanpa akun)')}` },
34
+ { value: 'search', label: `Cari di katalog ${chalk.dim('(komponen, template, source code)')}` },
35
+ { value: 'library', label: `Pasang produk yang sudah saya beli ${chalk.dim(login ? '(dari akun Anda)' : '(login sekali, tanpa token)')}` },
36
+ { value: 'token', label: `Pasang dengan installation token ${chalk.dim('(TK-XXXX-…)')}` },
37
+ { value: 'help', label: 'Lihat semua perintah' },
38
+ ]);
39
+ out.line();
40
+ const add = { dir: options.dir, name: options.name, api: options.api, debug: options.debug };
41
+ switch (choice) {
42
+ case 'free': {
43
+ const { items } = await withSpinner('Mengambil komponen gratis…', () => api.catalog({ free: true }), { silentSuccess: true });
44
+ if (items.length === 0) {
45
+ out.info('Belum ada produk gratis saat ini.');
46
+ out.muted(` Lihat semua produk: npx ${PACKAGE_NAME} search`);
47
+ return;
48
+ }
49
+ printTable(items);
50
+ out.line();
51
+ await offerAdd(add);
52
+ return;
53
+ }
54
+ case 'search': {
55
+ const words = await ask('Cari apa? (contoh: tombol, navbar, template klinik; Enter = semua)');
56
+ await runSearch(words ? [words] : [], { api: options.api });
57
+ out.line();
58
+ await offerAdd(add);
59
+ return;
60
+ }
61
+ case 'library':
62
+ if (!login) {
63
+ await runLogin({ api: options.api });
64
+ out.line();
65
+ }
66
+ await runLibrary({ api: options.api });
67
+ out.line();
68
+ await offerAdd(add);
69
+ return;
70
+ case 'token':
71
+ await runInstall(options, { banner: false });
72
+ return;
73
+ default:
74
+ showCommands();
75
+ }
76
+ }
77
+ /** Asks which product to install (Enter skips) and installs it with `add`. */
78
+ async function offerAdd(options) {
79
+ const name = (await ask('Nama produk yang ingin dipasang (Enter = selesai)')).trim().toLowerCase();
80
+ if (name === '') {
81
+ out.muted(`Kapan saja: npx ${PACKAGE_NAME} add <nama>`);
82
+ return;
83
+ }
84
+ await runAdd([name], options);
85
+ }
86
+ function showCommands() {
87
+ const cmd = `npx ${PACKAGE_NAME}`;
88
+ const rows = [
89
+ [`${cmd} search tombol --gratis`, 'Cari produk (--jenis komponen|template|jasa)'],
90
+ [`${cmd} info otp-verify`, 'Detail, harga, dan cara memasang'],
91
+ [`${cmd} add liquid-toggle`, 'Pasang produk (gratis langsung, berbayar dari akun)'],
92
+ [`${cmd} login`, 'Hubungkan akun dengan satu klik di browser'],
93
+ [`${cmd} library`, 'Produk di akun Anda'],
94
+ [`${cmd} --token TK-XXXX-…`, 'Pasang dengan installation token'],
95
+ [`${cmd} doctor`, 'Periksa koneksi dan kesiapan komputer'],
96
+ [`${cmd} update`, 'Perbarui CLI sekarang (otomatis setiap dijalankan)'],
97
+ [`${cmd} --help`, 'Semua opsi'],
98
+ ];
99
+ const width = Math.max(...rows.map(([command]) => command.length));
100
+ out.line(chalk.bold('Perintah TokoCode CLI'));
101
+ out.line();
102
+ rows.forEach(([command, label]) => out.line(` ${chalk.cyan(command.padEnd(width))} ${chalk.dim(label)}`));
103
+ }
@@ -16,18 +16,21 @@ import { CancelledError, CliError, toCliError } from '../utils/errors.js';
16
16
  import { directoryState, ensureWritableDirectory, freeSpace, humanBytes, moveDirectory, removeQuietly, resolveUserPath } from '../utils/filesystem.js';
17
17
  import { debug } from '../utils/logger.js';
18
18
  import { formatDuration, ProgressBar } from '../utils/progress.js';
19
- import { ask, banner, box, choose, confirm, details, isInteractive, out, step } from '../utils/terminal.js';
19
+ import { ask, banner, box, centerLine, choose, confirm, details, divider, isInteractive, out, step } from '../utils/terminal.js';
20
20
  import { compareVersions, folderNameProblem, normalizeApiUrl, suggestFolderName } from '../utils/validation.js';
21
21
  const STEPS = 5;
22
22
  /**
23
23
  * `tokocode` / `tokocode install`: token → verify → choose folder → redeem → download (resumable)
24
24
  * → SHA-256 check → safe extraction → report. Nothing from the package is ever executed.
25
25
  */
26
- export async function runInstall(options) {
26
+ export async function runInstall(options, view = {}) {
27
27
  const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
28
- banner();
29
- out.line(chalk.bold('Selamat datang di TokoCode!'));
30
- out.line();
28
+ if (view.banner !== false) {
29
+ banner();
30
+ centerLine(chalk.bold('Selamat datang!') + chalk.dim(' Pasang produk yang sudah Anda beli dengan installation token.'));
31
+ out.line();
32
+ divider();
33
+ }
31
34
  warnOldNode();
32
35
  await withSpinner('Menghubungi server TokoCode…', async () => {
33
36
  const meta = await api.meta();
@@ -78,6 +81,34 @@ export async function runInstall(options) {
78
81
  debug('state saved', { dir: stateDir() });
79
82
  await performInstall(api, state, options);
80
83
  }
84
+ /**
85
+ * `npx tokocode add <name>` for a product the signed-in customer bought: the server issues and redeems an
86
+ * installation token for it, then the usual resumable download, SHA-256 check and safe extraction run.
87
+ */
88
+ export async function runLibraryInstall(api, name, accessToken, options) {
89
+ const requestId = randomBytes(18).toString('base64url');
90
+ const redeemed = await withSpinner(`Menyiapkan ${chalk.bold(name)} dari akun Anda…`, () => api.libraryInstall(name, accessToken, ApiClient.clientInfo(requestId)), { silentSuccess: true });
91
+ out.ok('Pembelian ditemukan di akun Anda!');
92
+ out.line();
93
+ describePurchase(redeemed);
94
+ const target = await chooseTarget(redeemed, options);
95
+ out.line();
96
+ out.ok(step(1, STEPS, 'Memvalidasi akses'));
97
+ out.ok(step(2, STEPS, 'Menyiapkan sesi download'));
98
+ const state = {
99
+ schema: 1,
100
+ apiUrl: api.baseUrl,
101
+ session: redeemed.session,
102
+ product: redeemed.product,
103
+ package: redeemed.package,
104
+ invoice: redeemed.order.invoice_no,
105
+ target,
106
+ partPath: await choosePartPath(redeemed.session.id, target, redeemed.package.size),
107
+ createdAt: new Date().toISOString(),
108
+ };
109
+ await saveState(state);
110
+ await performInstall(api, state, options);
111
+ }
81
112
  /**
82
113
  * Offers to continue an unfinished installation (download interrupted, terminal closed…).
83
114
  *
@@ -132,7 +163,7 @@ async function performInstall(api, state, options) {
132
163
  let checksum = '';
133
164
  for (let attempt = 1;; attempt++) {
134
165
  await downloadStep(api, state);
135
- const spinner = ora({ text: step(4, STEPS, 'Memverifikasi integritas file (SHA-256)'), stream: process.stdout }).start();
166
+ const spinner = ora({ text: step(4, STEPS, 'Memverifikasi integritas file (SHA-256)'), stream: process.stdout, discardStdin: false }).start();
136
167
  checksum = await sha256File(state.partPath);
137
168
  if (sameChecksum(checksum, state.package.sha256)) {
138
169
  spinner.succeed(step(4, STEPS, `Memverifikasi integritas file ${chalk.dim('sha256 ' + checksum.slice(0, 12) + '…')}`));
@@ -203,7 +234,7 @@ async function extractStep(api, state) {
203
234
  }
204
235
  const staging = path.join(parent, `.tokocode-${path.basename(state.target)}-${randomBytes(4).toString('hex')}`);
205
236
  const forget = removeOnInterrupt(staging);
206
- const spinner = ora({ text: step(5, STEPS, 'Mengekstrak source code'), stream: process.stdout }).start();
237
+ const spinner = ora({ text: step(5, STEPS, 'Mengekstrak source code'), stream: process.stdout, discardStdin: false }).start();
207
238
  try {
208
239
  const result = await extractArchive(state.partPath, staging, {
209
240
  onProgress: (written, total) => {
@@ -334,7 +365,7 @@ function describePurchase(info) {
334
365
  * Asks for (or takes from options) the parent folder and project folder name, and makes sure
335
366
  * the destination is new or empty and writable. An existing folder with files is never touched.
336
367
  */
337
- async function chooseTarget(info, options) {
368
+ export async function chooseTarget(info, options) {
338
369
  const interactive = isInteractive() && !options.yes;
339
370
  const suggested = suggestFolderName(options.name ?? info.suggested_folder ?? 'tokocode-project');
340
371
  let base = options.dir ? resolveUserPath(options.dir) : process.cwd();
@@ -428,8 +459,8 @@ function warnOldNode() {
428
459
  out.warn(`Node.js ${process.versions.node} terdeteksi; disarankan versi ${MIN_NODE_VERSION} atau lebih baru (unduh di nodejs.org).`);
429
460
  }
430
461
  }
431
- async function withSpinner(text, action, options = {}) {
432
- const spinner = ora({ text, stream: process.stdout }).start();
462
+ export async function withSpinner(text, action, options = {}) {
463
+ const spinner = ora({ text, stream: process.stdout, discardStdin: false }).start();
433
464
  try {
434
465
  const result = await action();
435
466
  if (options.silentSuccess) {
@@ -0,0 +1,42 @@
1
+ import { spawn } from 'node:child_process';
2
+ import chalk from 'chalk';
3
+ import { CLI_VERSION, EXIT, PACKAGE_NAME } from '../config/constants.js';
4
+ import { latestVersion, planUpdate } from '../services/update.service.js';
5
+ import { CliError } from '../utils/errors.js';
6
+ import { brandLine, details, out } from '../utils/terminal.js';
7
+ import { compareVersions } from '../utils/validation.js';
8
+ import { withSpinner } from './install.js';
9
+ /**
10
+ * `npx tokocode update`: checks npm now (ignoring the 30-minute cache) and fetches the newest CLI, so the next
11
+ * `npx tokocode` starts with it. Normally not needed: every run updates itself automatically.
12
+ */
13
+ export async function runUpdate() {
14
+ brandLine();
15
+ const latest = await withSpinner('Memeriksa versi terbaru di npm…', () => latestVersion(true), { silentSuccess: true });
16
+ if (!latest) {
17
+ throw new CliError('network_error', 'Versi terbaru tidak dapat diperiksa.', 'Periksa koneksi internet, lalu coba lagi.');
18
+ }
19
+ out.line();
20
+ details([['Versi Anda', CLI_VERSION], ['Versi terbaru', latest]]);
21
+ out.line();
22
+ if (compareVersions(latest, CLI_VERSION) <= 0) {
23
+ out.ok('TokoCode CLI sudah versi terbaru.');
24
+ return EXIT.ok;
25
+ }
26
+ const plan = planUpdate(latest, ['--version'], { ...process.env, TOKOCODE_NO_UPDATE: '' });
27
+ if (plan.action !== 'relaunch') {
28
+ out.info(`Perbarui dengan: ${chalk.cyan(`npm install -g ${PACKAGE_NAME}@latest`)}`);
29
+ return EXIT.ok;
30
+ }
31
+ out.line(chalk.cyan(`↻ Mengunduh TokoCode CLI ${latest}…`));
32
+ const code = await new Promise((resolve) => {
33
+ const child = spawn(plan.command, plan.args, { stdio: ['ignore', 'ignore', 'inherit'], env: { ...process.env, TOKOCODE_NO_UPDATE: '1' } });
34
+ child.on('error', () => resolve(1));
35
+ child.on('exit', (exitCode) => resolve(exitCode ?? 1));
36
+ });
37
+ if (code !== 0) {
38
+ throw new CliError('update_failed', `TokoCode CLI ${latest} belum dapat diunduh.`, `Coba lagi beberapa menit lagi, atau jalankan: npx --prefer-online ${PACKAGE_NAME}@latest`);
39
+ }
40
+ out.ok(`TokoCode CLI ${latest} siap. Perintah npx ${PACKAGE_NAME} berikutnya memakai versi ini.`);
41
+ return EXIT.ok;
42
+ }
package/dist/index.js CHANGED
@@ -6,15 +6,26 @@ import { Command, Option } from 'commander';
6
6
  import { CLI_VERSION, EXIT, PACKAGE_NAME } from './config/constants.js';
7
7
  import { helpFooter } from './commands/help.js';
8
8
  import { runDoctor } from './commands/doctor.js';
9
+ import { runHome } from './commands/home.js';
9
10
  import { runInstall } from './commands/install.js';
11
+ import { runUpdate } from './commands/update.js';
10
12
  import { runVersion } from './commands/version.js';
13
+ import { autoUpdate } from './services/update.service.js';
14
+ import { runLibrary, runLogin, runLogout, runWhoami } from './commands/account.js';
15
+ import { runAdd } from './commands/add.js';
16
+ import { runInfo, runSearch } from './commands/catalog.js';
11
17
  import { runInterruptCleanup } from './utils/cleanup.js';
12
18
  import { CliError, toCliError } from './utils/errors.js';
13
19
  import { destroyAgents } from './utils/http.js';
14
20
  import { debug, setDebug } from './utils/logger.js';
15
21
  import { closePrompts, out, printError } from './utils/terminal.js';
16
22
  let interrupted = false;
23
+ // True while a newer CLI runs in our place (automatic update): it handles Ctrl+C itself.
24
+ let delegated = false;
17
25
  process.on('SIGINT', () => {
26
+ if (delegated) {
27
+ return;
28
+ }
18
29
  if (interrupted) {
19
30
  process.exit(EXIT.cancelled);
20
31
  }
@@ -26,6 +37,14 @@ process.on('SIGINT', () => {
26
37
  process.exit(EXIT.cancelled);
27
38
  });
28
39
  async function main(argv) {
40
+ // Automatic update: an older CLI started with npx hands over to the newest one (same arguments).
41
+ const handedOver = await autoUpdate(argv.slice(2), () => {
42
+ delegated = true;
43
+ });
44
+ if (handedOver !== null) {
45
+ return handedOver;
46
+ }
47
+ argv = argv.filter((arg, index) => index < 2 || arg !== '--no-update');
29
48
  const program = new Command();
30
49
  program
31
50
  .name(PACKAGE_NAME)
@@ -50,7 +69,11 @@ async function main(argv) {
50
69
  setDebug(Boolean(options.debug));
51
70
  await runInstall(options);
52
71
  };
53
- installOptions(program).action(install);
72
+ // Without a command: a menu in a terminal, the installation-token flow with --token/scripts.
73
+ installOptions(program).action(async (options) => {
74
+ setDebug(Boolean(options.debug));
75
+ await runHome(options);
76
+ });
54
77
  installOptions(program.command('install').description('Pasang produk dengan installation token (perintah bawaan)')).action(install);
55
78
  program
56
79
  .command('doctor')
@@ -62,6 +85,65 @@ async function main(argv) {
62
85
  exitCode = (await runDoctor(options.api)) ? EXIT.ok : EXIT.error;
63
86
  });
64
87
  program.command('version').description('Tampilkan versi CLI, Node.js, dan sistem').action(() => runVersion());
88
+ program
89
+ .command('update')
90
+ .alias('upgrade')
91
+ .description('Periksa dan unduh TokoCode CLI terbaru sekarang (biasanya otomatis)')
92
+ .action(async () => {
93
+ exitCode = await runUpdate();
94
+ });
95
+ // Catalogue, free products and the customer's account (CLI 1.1).
96
+ const apiOption = () => new Option('--api <url>', 'Alamat toko').env('TOKOCODE_API_URL');
97
+ program
98
+ .command('add')
99
+ .alias('get')
100
+ .argument('<nama...>', 'Nama produk dari katalog (lihat npx tokocode search)')
101
+ .description('Pasang produk: yang gratis langsung, yang berbayar dari akun Anda (setelah login)')
102
+ .option('-d, --dir <path>', 'Folder induk (bawaan: direktori saat ini)')
103
+ .option('-n, --name <folder>', 'Nama folder (bawaan: nama produk)')
104
+ .option('-y, --yes', 'Jangan bertanya konfirmasi')
105
+ .addOption(apiOption())
106
+ .option('--debug', 'Tampilkan log diagnosis')
107
+ .action(async (names, options) => {
108
+ setDebug(Boolean(options.debug));
109
+ await runAdd(names, options);
110
+ });
111
+ program
112
+ .command('search')
113
+ .alias('cari')
114
+ .argument('[kata...]', 'Kata kunci (kosongkan untuk semua produk)')
115
+ .description('Cari komponen, template, dan source code di katalog')
116
+ .option('-g, --gratis', 'Hanya produk gratis')
117
+ .option('-j, --jenis <jenis>', 'komponen, template, atau jasa')
118
+ .option('--json', 'Keluaran JSON (untuk skrip)')
119
+ .addOption(apiOption())
120
+ .action(async (words, options) => runSearch(words, options));
121
+ program
122
+ .command('info')
123
+ .argument('<nama>', 'Nama produk')
124
+ .description('Detail produk: harga, versi, paket, dan cara memasang')
125
+ .option('--json', 'Keluaran JSON')
126
+ .addOption(apiOption())
127
+ .action(async (name, options) => runInfo(name, options));
128
+ program
129
+ .command('login')
130
+ .description('Hubungkan CLI ke akun TokoCode (setujui dengan satu klik di browser)')
131
+ .option('--no-browser', 'Jangan buka browser otomatis (salin tautannya sendiri)')
132
+ .addOption(apiOption())
133
+ .option('--debug', 'Tampilkan log diagnosis')
134
+ .action(async (options) => {
135
+ setDebug(Boolean(options.debug));
136
+ await runLogin(options);
137
+ });
138
+ program.command('logout').description('Putuskan CLI ini dari akun TokoCode').addOption(apiOption()).action(async (options) => runLogout(options));
139
+ program.command('whoami').description('Tampilkan akun yang terhubung').option('--json', 'Keluaran JSON').addOption(apiOption()).action(async (options) => runWhoami(options));
140
+ program
141
+ .command('library')
142
+ .alias('produk')
143
+ .description('Produk di akun Anda yang siap dipasang')
144
+ .option('--json', 'Keluaran JSON')
145
+ .addOption(apiOption())
146
+ .action(async (options) => runLibrary(options));
65
147
  program.addHelpText('after', helpFooter());
66
148
  try {
67
149
  await program.parseAsync(argv);
@@ -44,6 +44,62 @@ export class ApiClient {
44
44
  debug('failure report not delivered', error.message);
45
45
  }
46
46
  }
47
+ /* Catalogue and free products (no account). */
48
+ catalog(query = {}) {
49
+ const params = new URLSearchParams();
50
+ if (query.q) {
51
+ params.set('q', query.q);
52
+ }
53
+ if (query.kind) {
54
+ params.set('kind', query.kind);
55
+ }
56
+ if (query.free) {
57
+ params.set('free', '1');
58
+ }
59
+ const suffix = params.toString();
60
+ return this.withRetry(() => this.call('GET', `/catalog${suffix ? `?${suffix}` : ''}`));
61
+ }
62
+ product(name) {
63
+ return this.withRetry(() => this.call('GET', `/products/${encodeURIComponent(name)}`));
64
+ }
65
+ /** Opens the ZIP stream of a free product (200/206; 416 when the part file is complete). */
66
+ async openFreePackage(name, start, etag) {
67
+ const headers = this.headers({ Accept: 'application/zip, application/json' });
68
+ if (start > 0) {
69
+ headers.Range = `bytes=${start}-`;
70
+ headers['If-Range'] = `"${etag}"`;
71
+ }
72
+ const response = await openRequest({ method: 'GET', url: `${this.baseUrl}${API_PREFIX}/free/${encodeURIComponent(name)}/package`, headers, timeoutMs: TIMEOUTS.downloadIdleMs });
73
+ const status = response.statusCode ?? 0;
74
+ if (status === 200 || status === 206 || status === 416) {
75
+ return response;
76
+ }
77
+ throw await this.errorFrom(response);
78
+ }
79
+ /* `npx tokocode login` and the customer's library (access token in Authorization). */
80
+ deviceStart(client) {
81
+ return this.withRetry(() => this.call('POST', '/auth/device', { client }));
82
+ }
83
+ /** One poll; "authorization_pending" comes back as a CliError for the caller to wait on. */
84
+ deviceToken(deviceCode) {
85
+ return this.call('POST', '/auth/token', { device_code: deviceCode });
86
+ }
87
+ me(accessToken) {
88
+ return this.withRetry(() => this.call('GET', '/me', undefined, accessToken));
89
+ }
90
+ library(accessToken) {
91
+ return this.withRetry(() => this.call('GET', '/library', undefined, accessToken));
92
+ }
93
+ /**
94
+ * Prepares the install of an owned product: the server issues and redeems an installation token and
95
+ * answers like redeem (purchase details + download session).
96
+ */
97
+ libraryInstall(name, accessToken, client) {
98
+ return this.withRetry(() => this.call('POST', `/library/${encodeURIComponent(name)}/install`, { client }, accessToken), 2);
99
+ }
100
+ async logout(accessToken) {
101
+ await this.call('POST', '/auth/logout', {}, accessToken);
102
+ }
47
103
  downloadUrl(sessionId) {
48
104
  return `${this.baseUrl}${API_PREFIX}/downloads/${sessionId}`;
49
105
  }
@@ -0,0 +1,61 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { debug } from '../utils/logger.js';
5
+ /**
6
+ * Where `npx tokocode login` keeps its access token: one entry per store address, in a file only the current
7
+ * user can read (0600 in a 0700 folder). TOKOCODE_CONFIG_DIR overrides the location (tests, CI).
8
+ */
9
+ export function configDir() {
10
+ if (process.env.TOKOCODE_CONFIG_DIR) {
11
+ return process.env.TOKOCODE_CONFIG_DIR;
12
+ }
13
+ if (process.platform === 'win32') {
14
+ return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'tokocode');
15
+ }
16
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'tokocode');
17
+ }
18
+ export function authFile() {
19
+ return path.join(configDir(), 'auth.json');
20
+ }
21
+ async function readAll() {
22
+ try {
23
+ const parsed = JSON.parse(await fs.readFile(authFile(), 'utf8'));
24
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ }
30
+ async function writeAll(all) {
31
+ await fs.mkdir(configDir(), { recursive: true, mode: 0o700 });
32
+ const target = authFile();
33
+ const temporary = `${target}.${process.pid}.tmp`;
34
+ await fs.writeFile(temporary, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
35
+ await fs.rename(temporary, target);
36
+ await fs.chmod(target, 0o600).catch(() => undefined);
37
+ }
38
+ /** The saved login for this store, or null (missing, malformed or expired). */
39
+ export async function loadLogin(apiUrl) {
40
+ const login = (await readAll())[apiUrl];
41
+ if (!login || typeof login.token !== 'string' || !login.token.startsWith('tca_')) {
42
+ return null;
43
+ }
44
+ if (Date.parse(login.expires_at) <= Date.now()) {
45
+ debug('saved login expired', { apiUrl });
46
+ return null;
47
+ }
48
+ return login;
49
+ }
50
+ export async function saveLogin(apiUrl, login) {
51
+ const all = await readAll();
52
+ all[apiUrl] = login;
53
+ await writeAll(all);
54
+ }
55
+ export async function forgetLogin(apiUrl) {
56
+ const all = await readAll();
57
+ if (all[apiUrl]) {
58
+ delete all[apiUrl];
59
+ await writeAll(all);
60
+ }
61
+ }
@@ -0,0 +1,118 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import chalk from 'chalk';
5
+ import { CLI_VERSION, PACKAGE_NAME } from '../config/constants.js';
6
+ import { debug } from '../utils/logger.js';
7
+ import { compareVersions } from '../utils/validation.js';
8
+ import { configDir } from './auth.service.js';
9
+ /**
10
+ * Automatic updates. Before a command runs, the CLI asks npm for the newest version (cached for
11
+ * CHECK_EVERY_MS, at most CHECK_TIMEOUT_MS on a slow network). Started through `npx`, an older CLI hands over
12
+ * to the newest one through npm itself (`npm exec --prefer-online`, so a stale npm cache cannot pick the
13
+ * old version again) with the same arguments; installed globally, it only shows how to update.
14
+ * Off with TOKOCODE_NO_UPDATE=1, --no-update, or in CI.
15
+ */
16
+ export const CHECK_EVERY_MS = 30 * 60 * 1000;
17
+ const CHECK_TIMEOUT_MS = 2500;
18
+ const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
19
+ const VERSION = /^\d+\.\d+\.\d+$/;
20
+ function cacheFile() {
21
+ return path.join(configDir(), 'update-check.json');
22
+ }
23
+ async function readCache() {
24
+ try {
25
+ const data = JSON.parse(await fs.readFile(cacheFile(), 'utf8'));
26
+ return typeof data.checked_at === 'number' && typeof data.latest === 'string' && VERSION.test(data.latest) ? data : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ async function writeCache(latest) {
33
+ try {
34
+ await fs.mkdir(configDir(), { recursive: true, mode: 0o700 });
35
+ await fs.writeFile(cacheFile(), JSON.stringify({ checked_at: Date.now(), latest }) + '\n', { mode: 0o600 });
36
+ }
37
+ catch (error) {
38
+ debug('update cache not written', error.message);
39
+ }
40
+ }
41
+ /** Newest version on npm, or null when npm cannot be reached (the CLI then simply carries on). */
42
+ export async function latestVersion(force = false, fetcher = fetch) {
43
+ const cached = await readCache();
44
+ if (!force && cached && Date.now() - cached.checked_at < CHECK_EVERY_MS) {
45
+ return cached.latest;
46
+ }
47
+ try {
48
+ const response = await fetcher(REGISTRY_URL, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) });
49
+ if (!response.ok) {
50
+ throw new Error(`HTTP ${response.status}`);
51
+ }
52
+ const latest = String((await response.json()).version ?? '');
53
+ if (!VERSION.test(latest)) {
54
+ throw new Error(`unexpected version "${latest}"`);
55
+ }
56
+ await writeCache(latest);
57
+ return latest;
58
+ }
59
+ catch (error) {
60
+ debug('update check skipped', error.message);
61
+ return cached?.latest ?? null;
62
+ }
63
+ }
64
+ /**
65
+ * What to do with the newest version: nothing, show a hint (global install), or relaunch through npm (npx).
66
+ */
67
+ export function planUpdate(latest, args, env = process.env, current = CLI_VERSION) {
68
+ if (!latest || compareVersions(latest, current) <= 0 || updatesDisabled(args, env)) {
69
+ return { action: 'none' };
70
+ }
71
+ const npmCli = env.npm_execpath ?? '';
72
+ if (env.npm_command !== 'exec' || !/npm-cli\.js$/i.test(npmCli)) {
73
+ return { action: 'notify', latest };
74
+ }
75
+ return {
76
+ action: 'relaunch',
77
+ latest,
78
+ command: process.execPath,
79
+ args: [npmCli, 'exec', '--yes', '--prefer-online', `--package=${PACKAGE_NAME}@${latest}`, '--', PACKAGE_NAME, ...args],
80
+ };
81
+ }
82
+ export function updatesDisabled(args, env = process.env) {
83
+ return ['1', 'true', 'yes'].includes(String(env.TOKOCODE_NO_UPDATE ?? '').toLowerCase())
84
+ || env.CI === 'true'
85
+ || args.includes('--no-update')
86
+ || args[0] === 'update';
87
+ }
88
+ /**
89
+ * Runs the update check before a command. Returns the exit code of the newer CLI when it took over, or null
90
+ * to carry on with this one. Messages go to stderr so `--json` output stays clean.
91
+ */
92
+ export async function autoUpdate(args, onDelegate) {
93
+ if (updatesDisabled(args)) {
94
+ return null;
95
+ }
96
+ const plan = planUpdate(await latestVersion(), args);
97
+ if (plan.action === 'notify') {
98
+ process.stderr.write(chalk.yellow(`\n! TokoCode CLI ${plan.latest} tersedia (Anda memakai ${CLI_VERSION}). Perbarui: npm install -g ${PACKAGE_NAME}@latest\n`));
99
+ return null;
100
+ }
101
+ if (plan.action !== 'relaunch') {
102
+ return null;
103
+ }
104
+ process.stderr.write(chalk.cyan(`\n↻ Memperbarui TokoCode CLI ${CLI_VERSION} → ${plan.latest}…\n`));
105
+ onDelegate();
106
+ return await new Promise((resolve) => {
107
+ const child = spawn(plan.command, plan.args, {
108
+ stdio: 'inherit',
109
+ env: { ...process.env, TOKOCODE_NO_UPDATE: '1', TOKOCODE_UPDATED_FROM: CLI_VERSION },
110
+ });
111
+ child.on('error', (error) => {
112
+ debug('relaunch failed', error.message);
113
+ process.stderr.write(chalk.yellow('! Pembaruan otomatis gagal; melanjutkan dengan versi ini.\n'));
114
+ resolve(null);
115
+ });
116
+ child.on('exit', (code, signal) => resolve(signal ? 130 : code ?? 1));
117
+ });
118
+ }
@@ -15,6 +15,9 @@ const PATTERNS = [
15
15
  [/\b[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{24}\b/g, '****'],
16
16
  // Download session secrets and bearer headers.
17
17
  [/tcs_[A-Za-z0-9_-]{10,}/g, 'tcs_****'],
18
+ // `npx tokocode login`: access tokens and device codes.
19
+ [/tca_[A-Za-z0-9_-]{10,}/g, 'tca_****'],
20
+ [/tcd_[A-Za-z0-9_-]{10,}/g, 'tcd_****'],
18
21
  [/(authorization|x-tokocode-session)(["']?\s*[:=]\s*["']?)(bearer\s+)?[^\s"',}]+/gi, '$1$2$3****'],
19
22
  [/("(?:token|secret|request_id)"\s*:\s*")[^"]*(")/gi, '$1****$2'],
20
23
  ];
@@ -1,7 +1,7 @@
1
1
  import { createInterface } from 'node:readline/promises';
2
2
  import chalk from 'chalk';
3
3
  import { CancelledError, CliError } from './errors.js';
4
- import { EXIT } from '../config/constants.js';
4
+ import { CLI_VERSION, EXIT } from '../config/constants.js';
5
5
  /**
6
6
  * Terminal output and prompts. Plain ASCII fallbacks are used where the console cannot show
7
7
  * box-drawing characters; colours follow chalk's detection (NO_COLOR / FORCE_COLOR respected).
@@ -47,9 +47,59 @@ export function box(lines, color = chalk.cyan) {
47
47
  const rows = [color(tl + h.repeat(width) + tr), pad(''), ...lines.map(pad), pad(''), color(bl + h.repeat(width) + br)];
48
48
  return rows.join('\n');
49
49
  }
50
- export function banner() {
50
+ /** Brand colours of the website logo (docs/Design): the bag, and a lighter blue that reads on dark terminals. */
51
+ const BRAND = '#2F4DFF';
52
+ const BRAND_TEXT = '#7C92FF';
53
+ let brandShown = false;
54
+ function centred(text, width) {
55
+ return ' '.repeat(Math.max(0, Math.floor((width - visibleLength(text)) / 2))) + text;
56
+ }
57
+ function wordmark() {
58
+ return chalk.bold('Tokocode') + chalk.bold.hex(BRAND_TEXT)('.id');
59
+ }
60
+ /**
61
+ * The Tokocode.id logo as on the website (shopping bag with </>, then the wordmark), centred in the terminal.
62
+ * Drawn with block characters that every Windows console font has; without colours the bag is solid blocks.
63
+ */
64
+ export function banner(tagline = 'Komponen UI · Template · Source code') {
65
+ brandShown = true;
66
+ const width = Math.min(process.stdout.columns || 80, 120);
67
+ const blue = chalk.hex(BRAND);
68
+ const body = (inner) => (chalk.level > 0 ? chalk.bgHex(BRAND).hex('#FFFFFF').bold(inner) : inner.replace(/ /g, '█'));
69
+ const mark = [
70
+ blue(' ▄▀▀▀▀▀▄ '),
71
+ blue(' ▄▄▄▄█▄▄▄▄▄█▄▄▄▄ '),
72
+ body(' '),
73
+ body(' </> '),
74
+ body(' '),
75
+ blue(' ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ '),
76
+ ];
77
+ out.line();
78
+ mark.forEach((row) => out.line(centred(row, width)));
79
+ out.line();
80
+ out.line(centred(wordmark(), width));
81
+ out.line(centred(chalk.dim(`${tagline} · CLI ${CLI_VERSION}`), width));
82
+ out.line();
83
+ }
84
+ /** A line centred under the logo (welcome text, signed-in account). */
85
+ export function centerLine(text) {
86
+ out.line(centred(text, Math.min(process.stdout.columns || 80, 120)));
87
+ }
88
+ /** Thin divider between the logo block and what follows. */
89
+ export function divider() {
90
+ const width = Math.min(process.stdout.columns || 80, 120);
91
+ out.line(centred(chalk.dim((unicode ? '─' : '-').repeat(Math.min(56, width - 4))), width));
92
+ out.line();
93
+ }
94
+ /** One-line brand header for commands that do not open with the full logo (shown once per run). */
95
+ export function brandLine() {
96
+ if (brandShown || !process.stdout.isTTY) {
97
+ return;
98
+ }
99
+ brandShown = true;
100
+ const tag = chalk.level > 0 ? chalk.bgHex(BRAND).hex('#FFFFFF').bold(' </> ') : '[</>]';
51
101
  out.line();
52
- out.line(box([chalk.bold.white('TOKOCODE CLI'), chalk.cyan('SOURCE CODE INSTALLER')]));
102
+ out.line(`${tag} ${wordmark()} ${chalk.dim(`CLI ${CLI_VERSION}`)}`);
53
103
  out.line();
54
104
  }
55
105
  /** Two-column details ("Produk : …"). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokocode",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Pasang source code yang sudah Anda beli di TokoCode langsung dari terminal: npx tokocode",
5
5
  "keywords": [
6
6
  "tokocode",