@farisabid/foliokit 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.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +151 -2
  3. package/bin/foliokit.js +476 -0
  4. package/package.json +46 -4
  5. package/public/css/main.css +915 -0
  6. package/public/css/tokens.css +29 -0
  7. package/public/favicon.svg +17 -0
  8. package/public/index.html +747 -0
  9. package/public/js/core/pdf-engine.js +69 -0
  10. package/public/js/core/state.js +365 -0
  11. package/public/js/tools/dev-tools.js +1508 -0
  12. package/public/js/tools/edit-pdf.js +1618 -0
  13. package/public/js/tools/office-tools.js +221 -0
  14. package/public/js/tools/pdf-ops.js +949 -0
  15. package/public/js/tools/sign-pdf.js +198 -0
  16. package/public/manifest.json +26 -0
  17. package/public/sw.js +88 -0
  18. package/public/vendor/fonts/inter-1.woff2 +0 -0
  19. package/public/vendor/fonts/inter-2.woff2 +0 -0
  20. package/public/vendor/fonts/inter-3.woff2 +0 -0
  21. package/public/vendor/fonts/inter-4.woff2 +0 -0
  22. package/public/vendor/fonts/inter-5.woff2 +0 -0
  23. package/public/vendor/fonts/inter-6.woff2 +0 -0
  24. package/public/vendor/fonts/inter-7.woff2 +0 -0
  25. package/public/vendor/fonts/inter.css +316 -0
  26. package/public/vendor/fonts/jbmono-1.woff2 +0 -0
  27. package/public/vendor/fonts/jbmono-2.woff2 +0 -0
  28. package/public/vendor/fonts/jbmono-3.woff2 +0 -0
  29. package/public/vendor/fonts/jbmono-4.woff2 +0 -0
  30. package/public/vendor/fonts/jbmono-5.woff2 +0 -0
  31. package/public/vendor/fonts/jbmono-6.woff2 +0 -0
  32. package/public/vendor/fonts/jbmono.css +109 -0
  33. package/public/vendor/jszip.min.js +13 -0
  34. package/public/vendor/pdf-lib.min.js +16 -0
  35. package/public/vendor/pdf.min.js +22 -0
  36. package/public/vendor/pdf.worker.min.js +22 -0
  37. package/public/vendor/qrcode.min.js +1 -0
  38. package/server.js +125 -0
  39. package/start.bat +19 -0
  40. package/start.sh +12 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Foliokit Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="./public/favicon.svg" alt="Foliokit Logo" width="76" height="76" />
4
+
5
+ # Foliokit
6
+
7
+ **Local-first PDF, Document & Developer Toolkit — 30 tools, 100% client-side, zero upload.**
8
+
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-0F172A.svg?style=flat-square)](./LICENSE)
10
+ [![Zero Dependencies](https://img.shields.io/badge/Dependencies-0-10B981.svg?style=flat-square)](./package.json)
11
+ [![100% Client-Side](https://img.shields.io/badge/Privacy-Zero%20Upload-4F46E5.svg?style=flat-square)](#-privasi--arsitektur)
12
+ [![PWA Offline Ready](https://img.shields.io/badge/PWA-Offline%20Ready-F43F5E.svg?style=flat-square)](#-cara-pakai)
13
+
14
+ <p>
15
+ <a href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Ffarizabid%2Ffoliokit">
16
+ <img src="https://vercel.com/button" alt="Deploy with Vercel" />
17
+ </a>
18
+ </p>
19
+
20
+ </div>
21
+
22
+ ---
23
+
24
+ **Foliokit** menyatukan **30 alat harian** — mulai dari **PDF Studio (termasuk Edit PDF & Sensor/Redact)**, **Administrasi Kantor**, hingga **11 Developer Tools** — yang berjalan **100% di memori browser Anda**.
25
+
26
+ Cocok untuk dokumen sensitif (kontrak, slip gaji, KTP, Bearer token produksi, payload JSON, query SQL) karena **0 byte dikirim ke server** dan aplikasi tetap berfungsi meski internet dimatikan.
27
+
28
+ ---
29
+
30
+ ## ⚡ Cara Pakai
31
+
32
+ ### 1. Web App / PWA *(Tanpa Install — Laptop & HP)*
33
+ Buka URL deployment Vercel Anda, lalu klik **Install App / Add to Home Screen** di browser. Setelah dimuat sekali, Service Worker menyimpan aset secara lokal sehingga seluruh 30 fitur **tetap berjalan 100% offline**.
34
+
35
+ ### 2. Jalankan Lokal via CLI *(Node.js ≥ 16)*
36
+ ```bash
37
+ # Jalankan langsung tanpa install permanen
38
+ npx @farisabid/foliokit
39
+
40
+ # Atau via Bun
41
+ bunx @farisabid/foliokit
42
+
43
+ # Install global agar bisa dipanggil dari mana saja
44
+ npm install -g @farisabid/foliokit
45
+ foliokit
46
+ ```
47
+
48
+ **Perintah CLI yang tersedia:**
49
+ ```bash
50
+ foliokit start # jalankan server lokal (default http://localhost:4747)
51
+ foliokit start --port 8080 # gunakan port kustom
52
+ foliokit status # cek status server & PID
53
+ foliokit logs # lihat log server
54
+ foliokit restart # restart server
55
+ foliokit stop # hentikan server
56
+ ```
57
+
58
+ ### 3. Clone & Double-Click
59
+ ```bash
60
+ git clone https://github.com/farizabid/foliokit.git
61
+ cd foliokit
62
+ ```
63
+ - **Windows:** klik dua kali `start.bat`
64
+ - **macOS / Linux:** jalankan `./start.sh`
65
+
66
+ ---
67
+
68
+ ## 🧰 Daftar Lengkap 30 Fitur
69
+
70
+ ### 📄 PDF Operations (13 Tools)
71
+ | Tool | Fungsi Utama |
72
+ |---|---|
73
+ | **Edit PDF Studio** | Tambah teks (+ mode *Whiteout* penutup teks lama), highlight, coret bebas, bentuk, stempel, gambar, **Sensor / Redact permanen** (flatten anti copy-paste), undo/redo. |
74
+ | **Gabung PDF** | Satukan beberapa berkas PDF dengan *drag-and-drop* langsung di kartu preview. |
75
+ | **Pisah Halaman** | Ekstrak rentang halaman tertentu (`1-3, 5, 8-10`) atau pecah per lembar. |
76
+ | **Atur Halaman** | Susun ulang urutan via *drag-and-drop* thumbnail, putar, atau hapus lembar. |
77
+ | **Kompres Ukuran** | Perkecil ukuran PDF (Ringan / Sedang / Ekstrem) untuk lampiran email & portal. |
78
+ | **Tanda Tangan PDF** | Coret TTD atau unggah stempel PNG, tempel, geser (*drag*), *resize*, dan unduh PDF. |
79
+ | **PDF ke Gambar** | Ekstrak seluruh lembar PDF menjadi JPG/PNG tajam (96–300 DPI) dalam 1 ZIP. |
80
+ | **Gambar ke PDF** | Gabungkan foto nota, KTP, atau hasil scan menjadi 1 berkas PDF (A4 / Letter / Fit). |
81
+ | **Watermark** | Pasang cap air teks (*RAHASIA*, *DRAFT*) dengan kontrol transparansi & sudut. |
82
+ | **Nomor Halaman** | Tambah penomoran otomatis di header/footer setiap halaman. |
83
+ | **Putar Halaman** | Putar orientasi dokumen 90°, 180°, atau 270°. |
84
+ | **Proteksi Sandi** | Tambahkan proteksi metadata / pengelolaan dokumen lokal. |
85
+ | **Ekstrak Teks** | Salin seluruh teks dari lapisan dokumen PDF ke papan klip secara instan. |
86
+
87
+ ### 🏢 Office & Administration (6 Tools)
88
+ | Tool | Fungsi Utama |
89
+ |---|---|
90
+ | **Kwitansi Otomatis** | Buat kwitansi resmi siap cetak dengan konversi angka ke **Terbilang Bahasa Indonesia**. |
91
+ | **Studio Tanda Tangan** | Buat tanda tangan PNG transparan siap tempel di Word / Excel / Google Docs. |
92
+ | **QR Code Studio** | Buat kode QR resolusi tinggi untuk tautan, WhatsApp (`wa.me`), dan Wi-Fi. |
93
+ | **Kompresor Foto** | Perkecil ukuran foto dan konversi format PNG ⇄ JPG ⇄ WebP secara lokal. |
94
+ | **Pembanding Naskah** | Bandingkan dua draf dokumen (*Diff Checker*) dan sorot perubahan per baris. |
95
+ | **Utilitas Teks** | Hitung kata/karakter, ubah kapitalisasi huruf, dan rapikan spasi berlebih. |
96
+
97
+ ### 💻 Developer Tools (11 Tools)
98
+ | Tool | Fungsi Utama |
99
+ |---|---|
100
+ | **JWT & Bearer Inspector** | Auto-strip prefix `Bearer`, decode UTF-8 Header/Payload, status expiry WIB/UTC, & verifikasi signature lokal (`HS256`/`HS512`) via `crypto.subtle`. |
101
+ | **UUID & Secret Generator** | Generate massal (1–100) UUID v4, UUID v7, ULID, NanoID, serta API Secret kriptografis. |
102
+ | **JSON Studio & Converter** | Format, minify, sort keys, validasi error, & konversi ke TypeScript, Java DTO, Query String, atau CSV. |
103
+ | **Regex Tester & Debugger** | Live match highlight, flags, tabel capture groups, replace preview, & preset lokal (NIK, NPWP, No HP ID). |
104
+ | **Cron Parser & Generator** | Mendukung 5-field (Linux/K8s) & 6-field (Spring/Quartz) + 10 jadwal eksekusi berikutnya (WIB/UTC). |
105
+ | **Base64, URL & Auth** | Base64URL UTF-8, editor query param URL, Basic Auth header builder, & File → Data URI. |
106
+ | **Hash, HMAC & Checksum** | SHA-1/256/384/512 (teks & file), HMAC-SHA256/512 untuk webhook, & pembanding hash target. |
107
+ | **Unix Timestamp & Zone** | Live Epoch clock & konversi serentak ke WIB, WITA, WIT, UTC, serta *relative time*. |
108
+ | **cURL Converter & Masker** | Ubah perintah `curl` ke `fetch()` / `axios` + tombol **1-Klik Sensor Secret** (`<REDACTED>`). |
109
+ | **SQL Formatter & Binder** | Rapikan query SQL & *bind* prepared params (`?`, `$1`, `:name`) siap tempel ke DBeaver/pgAdmin. |
110
+ | **Color Picker & Contrast** | Konversi HEX/RGB/HSL, shade generator `50–950`, & cek kontras aksesibilitas WCAG 2.1 AA/AAA. |
111
+
112
+ ---
113
+
114
+ ## 🔒 Privasi & Arsitektur
115
+
116
+ ```text
117
+ Berkas / Token Anda ──▶ Browser RAM (pdf-lib, pdf.js, Web Crypto API) ──▶ Hasil Unduhan Lokal
118
+ ▲
119
+ 0 byte dikirim ke server
120
+ ```
121
+
122
+ - **Zero Dependencies & Zero Build:** `server.js` hanya memakai modul bawaan Node.js (`http`, `fs`, `path`, `os`).
123
+ - **100% Offline Bundle:** Seluruh pustaka (`pdf-lib`, `pdf.js`, `jszip`, `qrcode`) dan font (`Inter`, `JetBrains Mono`) dibundel lokal di `public/vendor/`.
124
+ - **Aman untuk Audit:** Buka tab **Network** di Browser DevTools saat memproses PDF atau token — tidak ada satu pun request data keluar.
125
+
126
+ ---
127
+
128
+ ## 📁 Struktur Proyek
129
+
130
+ ```text
131
+ foliokit/
132
+ ├── bin/foliokit.js # CLI manager (start/stop/restart/status/logs)
133
+ ├── public/
134
+ │ ├── index.html # App shell & PWA entry
135
+ │ ├── favicon.svg # Foliokit vector brand mark
136
+ │ ├── manifest.json # Web App Manifest
137
+ │ ├── sw.js # Offline Service Worker
138
+ │ ├── css/ # Design tokens & stylesheets
139
+ │ ├── js/core/ # State, navigation & shared PDF engine
140
+ │ ├── js/tools/ # Modular PDF, Office & Developer tools
141
+ │ └── vendor/ # Bundled offline libraries & fonts
142
+ ├── server.js # Native Node.js static server + security headers
143
+ ├── vercel.json # Zero-config Vercel static deployment config
144
+ ├── start.bat / start.sh # 1-click local launchers
145
+ └── package.json
146
+ ```
147
+
148
+ ---
149
+
150
+ ## 📄 Lisensi
151
+
152
+ Dirilis di bawah lisensi [MIT](./LICENSE).
@@ -0,0 +1,476 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Foliokit — Command Line Manager
6
+ * Menu interaktif untuk menjalankan, menyembunyikan, dan menghentikan server lokal.
7
+ *
8
+ * foliokit Menu interaktif (start otomatis bila belum jalan)
9
+ * foliokit start Jalankan di latar belakang
10
+ * foliokit stop Hentikan server
11
+ * foliokit restart Mulai ulang
12
+ * foliokit status Tampilkan status
13
+ * foliokit logs Tampilkan log terakhir
14
+ * foliokit --port 8080 Tentukan port lain
15
+ */
16
+
17
+ const { spawn, execSync } = require('child_process');
18
+ const readline = require('readline');
19
+ const fs = require('fs');
20
+ const os = require('os');
21
+ const path = require('path');
22
+ const net = require('net');
23
+
24
+ const ROOT = path.resolve(__dirname, '..');
25
+ const SERVER = path.join(ROOT, 'server.js');
26
+ const STATE_DIR = path.join(os.homedir(), '.foliokit');
27
+ const STATE_FILE = path.join(STATE_DIR, 'state.json');
28
+ const LOG_FILE = path.join(STATE_DIR, 'foliokit.log');
29
+ const VERSION = '1.0.0';
30
+
31
+ const C = {
32
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
33
+ red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m',
34
+ cyan: '\x1b[36m', gray: '\x1b[90m',
35
+ };
36
+
37
+ // ==================================================
38
+ // UTILITAS
39
+ // ==================================================
40
+ function ensureDir() { fs.mkdirSync(STATE_DIR, { recursive: true }); }
41
+ function readState() { try { return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')); } catch { return null; } }
42
+ function writeState(s) { ensureDir(); fs.writeFileSync(STATE_FILE, JSON.stringify(s, null, 2)); }
43
+ function clearState() { try { fs.unlinkSync(STATE_FILE); } catch {} }
44
+ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
45
+
46
+ function isAlive(pid) {
47
+ if (!pid) return false;
48
+ try { process.kill(pid, 0); return true; }
49
+ catch (e) { return e.code === 'EPERM'; }
50
+ }
51
+
52
+ function pidsOnPort(port) {
53
+ const pids = new Set();
54
+ try {
55
+ if (process.platform === 'win32') {
56
+ const out = execSync('netstat -ano -p tcp', { encoding: 'utf8' });
57
+ for (const line of out.split(/\r?\n/)) {
58
+ if (!/LISTENING/.test(line)) continue;
59
+ const m = line.match(/:(\d+)\s+\S+\s+LISTENING\s+(\d+)/);
60
+ if (m && Number(m[1]) === port) pids.add(m[2]);
61
+ }
62
+ } else {
63
+ const out = execSync(`lsof -ti tcp:${port} -sTCP:LISTEN`, { encoding: 'utf8' });
64
+ out.split(/\s+/).filter(Boolean).forEach(p => pids.add(p));
65
+ }
66
+ } catch {}
67
+ return [...pids];
68
+ }
69
+
70
+ function killPid(pid) {
71
+ try {
72
+ if (process.platform === 'win32') execSync(`taskkill /PID ${pid} /F /T`, { stdio: 'ignore' });
73
+ else process.kill(Number(pid), 'SIGKILL');
74
+ } catch {}
75
+ }
76
+
77
+ function waitForPort(port, timeout = 10000) {
78
+ return new Promise(resolve => {
79
+ const start = Date.now();
80
+ const attempt = () => {
81
+ const sock = net.connect({ port, host: '127.0.0.1' });
82
+ sock.once('connect', () => { sock.destroy(); resolve(true); });
83
+ sock.once('error', () => {
84
+ sock.destroy();
85
+ if (Date.now() - start > timeout) resolve(false);
86
+ else setTimeout(attempt, 200);
87
+ });
88
+ };
89
+ attempt();
90
+ });
91
+ }
92
+
93
+ function getLocalIp() {
94
+ const ifaces = os.networkInterfaces();
95
+ for (const name of Object.keys(ifaces)) {
96
+ for (const iface of ifaces[name] || []) {
97
+ if (iface.family === 'IPv4' && !iface.internal) return iface.address;
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+
103
+ function openBrowser(url) {
104
+ try {
105
+ if (process.platform === 'win32') execSync(`start "" "${url}"`, { stdio: 'ignore', shell: true });
106
+ else if (process.platform === 'darwin') execSync(`open "${url}"`, { stdio: 'ignore' });
107
+ else execSync(`xdg-open "${url}"`, { stdio: 'ignore' });
108
+ } catch {}
109
+ }
110
+
111
+ function uptime(startedAt) {
112
+ if (!startedAt) return '\u2014';
113
+ let s = Math.floor((Date.now() - startedAt) / 1000);
114
+ const h = Math.floor(s / 3600); s %= 3600;
115
+ const m = Math.floor(s / 60); s %= 60;
116
+ return (h ? h + 'j ' : '') + (m ? m + 'm ' : '') + s + 'd';
117
+ }
118
+
119
+ function portFromArgs() {
120
+ const args = process.argv;
121
+ const i = args.indexOf('--port');
122
+ if (i > -1 && args[i + 1]) return Number(args[i + 1]);
123
+ const j = args.indexOf('-p');
124
+ if (j > -1 && args[j + 1]) return Number(args[j + 1]);
125
+ if (process.env.PORT) return Number(process.env.PORT);
126
+ return 4747;
127
+ }
128
+
129
+ // ==================================================
130
+ // KONTROL SERVER
131
+ // ==================================================
132
+ function startServer(port) {
133
+ ensureDir();
134
+ const fd = fs.openSync(LOG_FILE, 'a');
135
+ const child = spawn(process.execPath, [SERVER], {
136
+ cwd: ROOT,
137
+ detached: true,
138
+ stdio: ['ignore', fd, fd],
139
+ env: { ...process.env, PORT: String(port) },
140
+ });
141
+ child.unref();
142
+ try { fs.closeSync(fd); } catch {}
143
+ writeState({ pid: child.pid, port, startedAt: Date.now() });
144
+ return child.pid;
145
+ }
146
+
147
+ async function stopServer() {
148
+ const st = readState();
149
+ const port = st?.port || portFromArgs();
150
+ const pids = new Set();
151
+ if (st?.pid && isAlive(st.pid)) pids.add(String(st.pid));
152
+ pidsOnPort(port).forEach(p => pids.add(p));
153
+ if (!pids.size) { clearState(); return false; }
154
+ [...pids].forEach(killPid);
155
+ await sleep(600);
156
+ clearState();
157
+ return true;
158
+ }
159
+
160
+ function currentStatus() {
161
+ const st = readState();
162
+ const port = st?.port || portFromArgs();
163
+ const onPort = pidsOnPort(port);
164
+ const trackedAlive = st?.pid ? isAlive(st.pid) : false;
165
+ const running = trackedAlive || onPort.length > 0;
166
+ const pid = trackedAlive ? st.pid : (onPort[0] ? Number(onPort[0]) : null);
167
+ return { running, pid, port, startedAt: st?.startedAt };
168
+ }
169
+
170
+ // ==================================================
171
+ // TAMPILAN
172
+ // ==================================================
173
+ const W = 58;
174
+ function rule(ch = '\u2500') { return C.gray + ' ' + ch.repeat(W) + C.reset; }
175
+
176
+ function banner() {
177
+ console.log('');
178
+ console.log(' ' + C.bold + C.cyan + '\u25C6 Foliokit' + C.reset + C.dim + ' \u00b7 Local-First Document & Dev Toolkit' + C.reset);
179
+ console.log(rule());
180
+ }
181
+
182
+ function statusLine() {
183
+ const s = currentStatus();
184
+ if (s.running) {
185
+ console.log(' ' + C.dim + 'Status ' + C.reset + C.green + '\u25cf Aktif' + C.reset + C.gray + ' (PID ' + s.pid + ')' + C.reset);
186
+ console.log(' ' + C.dim + 'Lokal ' + C.reset + C.cyan + 'http://localhost:' + s.port + C.reset);
187
+ const ip = getLocalIp();
188
+ if (ip) console.log(' ' + C.dim + 'Jaringan ' + C.reset + C.cyan + 'http://' + ip + ':' + s.port + C.reset);
189
+ console.log(' ' + C.dim + 'Uptime ' + C.reset + uptime(s.startedAt));
190
+ } else {
191
+ console.log(' ' + C.dim + 'Status ' + C.reset + C.red + '\u25cb Berhenti' + C.reset);
192
+ console.log(' ' + C.dim + 'Port ' + C.reset + s.port);
193
+ }
194
+ console.log(rule());
195
+ return s;
196
+ }
197
+
198
+ function printStatus() { banner(); statusLine(); console.log(''); }
199
+
200
+ function printLog() {
201
+ banner();
202
+ console.log(' ' + C.bold + 'Log terakhir' + C.reset + C.gray + ' ' + LOG_FILE + C.reset);
203
+ console.log('');
204
+ let lines = [];
205
+ try { lines = fs.readFileSync(LOG_FILE, 'utf8').split(/\r?\n/).filter(Boolean).slice(-18); } catch {}
206
+ if (lines.length) console.log(' ' + lines.join('\n '));
207
+ else console.log(' ' + C.gray + '(belum ada log)' + C.reset);
208
+ console.log('');
209
+ }
210
+
211
+ // ==================================================
212
+ // MENU INTERAKTIF
213
+ // ==================================================
214
+ function menu() {
215
+ const stdin = process.stdin;
216
+ readline.emitKeypressEvents(stdin);
217
+ if (stdin.isTTY) stdin.setRawMode(true);
218
+ stdin.resume();
219
+
220
+ let sel = 0;
221
+ let mode = 'menu'; // 'menu' | 'log'
222
+ let busy = false;
223
+ let notice = '';
224
+ let uptimeRow = -1;
225
+
226
+ const items = (running) => ([
227
+ { id: 'open', label: 'Buka di browser' },
228
+ { id: 'toggle', label: running ? 'Stop server' : 'Start server' },
229
+ { id: 'logs', label: 'Lihat log terakhir' },
230
+ { id: 'refresh', label: 'Segarkan info' },
231
+ { id: 'hide', label: 'Sembunyikan (biarkan tetap berjalan)' },
232
+ { id: 'quit', label: 'Keluar' },
233
+ ]);
234
+
235
+ // Tulis ulang setiap baris di tempat tanpa membersihkan seluruh layar
236
+ // (mencegah kedipan). \x1b[2K menghapus satu baris, \x1b[J menghapus sisa di bawah.
237
+ const eol = (s) => '\x1b[2K' + s;
238
+
239
+ const buildFrame = () => {
240
+ const s = currentStatus();
241
+ const list = items(s.running);
242
+ const ip = getLocalIp();
243
+ const lines = [];
244
+ lines.push('');
245
+ lines.push(' ' + C.bold + C.cyan + '\u25C6 Foliokit' + C.reset + C.dim + ' \u00b7 Local-First Document & Dev Toolkit' + C.reset);
246
+ lines.push(rule());
247
+ lines.push(' ' + C.dim + 'Status ' + C.reset + (s.running
248
+ ? C.green + '\u25cf Aktif' + C.reset + C.gray + ' (PID ' + s.pid + ')' + C.reset
249
+ : C.red + '\u25cb Berhenti' + C.reset));
250
+ lines.push(' ' + C.dim + 'Lokal ' + C.reset + (s.running ? C.cyan + 'http://localhost:' + s.port + C.reset : C.gray + '\u2014' + C.reset));
251
+ lines.push(' ' + C.dim + 'Jaringan ' + C.reset + (s.running && ip ? C.cyan + 'http://' + ip + ':' + s.port + C.reset : C.gray + '\u2014' + C.reset));
252
+ lines.push(' ' + C.dim + 'Uptime ' + C.reset + (s.running ? uptime(s.startedAt) : C.gray + '\u2014' + C.reset));
253
+ uptimeRow = 6;
254
+ lines.push(rule());
255
+ lines.push('');
256
+ list.forEach((it, i) => {
257
+ lines.push(i === sel
258
+ ? ' ' + C.cyan + '\u276f' + C.reset + ' ' + C.bold + it.label + C.reset
259
+ : ' ' + it.label);
260
+ });
261
+ lines.push('');
262
+ lines.push(notice ? ' ' + notice : '');
263
+ lines.push(' ' + C.gray + '\u2191/\u2193 pilih \u00b7 Enter jalankan \u00b7 Ctrl+C keluar' + C.reset);
264
+ return lines;
265
+ };
266
+
267
+ const drawFull = () => {
268
+ const lines = buildFrame();
269
+ process.stdout.write('\x1b[H' + lines.map(eol).join('\n') + '\x1b[J');
270
+ };
271
+
272
+ const drawLog = () => {
273
+ const lines = [];
274
+ lines.push('');
275
+ lines.push(' ' + C.bold + C.cyan + '\u25C6 Foliokit' + C.reset + C.dim + ' \u00b7 Local-First Document & Dev Toolkit' + C.reset);
276
+ lines.push(rule());
277
+ lines.push(' ' + C.bold + 'Log terakhir' + C.reset + C.gray + ' ' + LOG_FILE + C.reset);
278
+ lines.push('');
279
+ let logs = [];
280
+ try { logs = fs.readFileSync(LOG_FILE, 'utf8').split(/\r?\n/).filter(Boolean).slice(-16); } catch {}
281
+ if (logs.length) logs.forEach(l => lines.push(' ' + l));
282
+ else lines.push(' ' + C.gray + '(belum ada log)' + C.reset);
283
+ lines.push('');
284
+ lines.push(' ' + C.gray + 'Tekan tombol apa saja untuk kembali' + C.reset);
285
+ process.stdout.write('\x1b[H' + lines.map(eol).join('\n') + '\x1b[J');
286
+ };
287
+
288
+ process.stdout.write('\x1b[2J\x1b[H');
289
+ drawFull();
290
+
291
+ // Hanya perbarui baris Uptime tiap detik (tanpa redraw penuh)
292
+ const tick = setInterval(() => {
293
+ if (mode !== 'menu' || busy || uptimeRow < 0) return;
294
+ const s = currentStatus();
295
+ const text = ' ' + C.dim + 'Uptime ' + C.reset + (s.running ? uptime(s.startedAt) : C.gray + '\u2014' + C.reset);
296
+ process.stdout.write('\x1b[' + (uptimeRow + 1) + ';1H\x1b[2K' + text);
297
+ }, 1000);
298
+
299
+ const cleanup = () => {
300
+ clearInterval(tick);
301
+ if (stdin.isTTY) stdin.setRawMode(false);
302
+ stdin.pause();
303
+ };
304
+
305
+ const exitWith = (msg) => {
306
+ cleanup();
307
+ process.stdout.write('\x1b[2J\x1b[H');
308
+ banner();
309
+ if (msg) console.log(' ' + msg);
310
+ console.log('');
311
+ console.log(' ' + C.gray + 'Panggil lagi dengan perintah: ' + C.reset + C.cyan + 'foliokit' + C.reset);
312
+ console.log('');
313
+ process.exit(0);
314
+ };
315
+
316
+ const activate = async (id) => {
317
+ if (busy) return;
318
+ const s = currentStatus();
319
+ if (id === 'open') { openBrowser('http://localhost:' + s.port); return; }
320
+ if (id === 'refresh') { drawFull(); return; }
321
+ if (id === 'logs') { mode = 'log'; drawLog(); return; }
322
+ if (id === 'hide') return exitWith('Server disembunyikan & tetap berjalan di latar.');
323
+ if (id === 'quit') return exitWith('Keluar.');
324
+ if (id === 'toggle') {
325
+ busy = true;
326
+ notice = s.running ? 'Menghentikan server\u2026' : 'Menjalankan server\u2026';
327
+ drawFull();
328
+ try {
329
+ if (s.running) {
330
+ await stopServer();
331
+ notice = C.red + '\u25a0 Server dihentikan.' + C.reset;
332
+ } else {
333
+ const pid = startServer(s.port);
334
+ const ok = await waitForPort(s.port);
335
+ notice = ok
336
+ ? C.green + '\u25cf Server aktif' + C.reset + C.gray + ' (PID ' + pid + ')' + C.reset
337
+ : C.red + 'Gagal menjalankan server. Cek menu Log.' + C.reset;
338
+ }
339
+ } catch (err) {
340
+ notice = C.red + 'Gagal: ' + (err.message || err) + C.reset;
341
+ }
342
+ busy = false;
343
+ drawFull();
344
+ setTimeout(() => { notice = ''; if (mode === 'menu' && !busy) drawFull(); }, 1600);
345
+ }
346
+ };
347
+
348
+ stdin.on('keypress', (str, key) => {
349
+ if (!key) return;
350
+ if (key.ctrl && key.name === 'c') return exitWith('Keluar. Server tetap berjalan.');
351
+ if (key.name === 'escape') return exitWith('Keluar.');
352
+ if (busy) return;
353
+ if (mode === 'log') { mode = 'menu'; drawFull(); return; }
354
+
355
+ const s = currentStatus();
356
+ const list = items(s.running);
357
+ if (key.name === 'up') { sel = (sel - 1 + list.length) % list.length; drawFull(); return; }
358
+ if (key.name === 'down') { sel = (sel + 1) % list.length; drawFull(); return; }
359
+ if (key.name === 'return' || key.name === 'enter') { activate(list[sel].id); return; }
360
+
361
+ const ch = (key.name || str || '').toLowerCase();
362
+ if (ch === 'q') return exitWith('Keluar.');
363
+ if (ch === 'h') return exitWith('Server disembunyikan & tetap berjalan di latar.');
364
+ });
365
+
366
+ process.stdout.on('resize', drawFull);
367
+ }
368
+
369
+ // ==================================================
370
+ // SUBCOMMAND
371
+ // ==================================================
372
+ async function cmdStart() {
373
+ const s = currentStatus();
374
+ banner();
375
+ if (s.running) {
376
+ console.log(' ' + C.yellow + 'Server sudah berjalan.' + C.reset);
377
+ statusLine();
378
+ console.log('');
379
+ return;
380
+ }
381
+ const port = portFromArgs();
382
+ startServer(port);
383
+ process.stdout.write(' ' + C.gray + 'Menjalankan server\u2026' + C.reset);
384
+ const ok = await waitForPort(port);
385
+ process.stdout.write('\r' + ' '.repeat(40) + '\r');
386
+ if (ok) {
387
+ const st = readState();
388
+ console.log(' ' + C.green + '\u25cf Server aktif' + C.reset + C.gray + ' (PID ' + (st?.pid || '-') + ')' + C.reset);
389
+ console.log(' ' + C.dim + 'Lokal ' + C.reset + C.cyan + 'http://localhost:' + port + C.reset);
390
+ const ip = getLocalIp();
391
+ if (ip) console.log(' ' + C.dim + 'Jaringan ' + C.reset + C.cyan + 'http://' + ip + ':' + port + C.reset);
392
+ console.log('');
393
+ console.log(' ' + C.gray + 'Hentikan dengan: ' + C.reset + C.cyan + 'foliokit stop' + C.reset);
394
+ } else {
395
+ console.log(' ' + C.red + 'Gagal menjalankan server. Cek log: ' + LOG_FILE + C.reset);
396
+ }
397
+ console.log('');
398
+ }
399
+
400
+ async function cmdStop() {
401
+ banner();
402
+ const s = currentStatus();
403
+ if (!s.running) { console.log(' ' + C.yellow + 'Tidak ada server yang berjalan.' + C.reset + '\n'); return; }
404
+ const ok = await stopServer();
405
+ console.log(ok
406
+ ? ' ' + C.red + '\u25a0 Server dihentikan.' + C.reset
407
+ : ' ' + C.yellow + 'Tidak ada proses yang bisa dihentikan.' + C.reset);
408
+ console.log('');
409
+ }
410
+
411
+ async function cmdRestart() {
412
+ banner();
413
+ await stopServer();
414
+ const port = portFromArgs();
415
+ startServer(port);
416
+ const ok = await waitForPort(port);
417
+ console.log(ok
418
+ ? ' ' + C.green + '\u25cf Server dimulai ulang di http://localhost:' + port + C.reset
419
+ : ' ' + C.red + 'Gagal memulai ulang server.' + C.reset);
420
+ console.log('');
421
+ }
422
+
423
+ function cmdLogs() { printLog(); }
424
+
425
+ function cmdHelp() {
426
+ banner();
427
+ console.log(' ' + C.bold + 'Penggunaan' + C.reset);
428
+ console.log('');
429
+ console.log(' ' + C.cyan + 'foliokit' + C.reset + ' Menu interaktif');
430
+ console.log(' ' + C.cyan + 'foliokit start' + C.reset + ' Jalankan di latar belakang');
431
+ console.log(' ' + C.cyan + 'foliokit stop' + C.reset + ' Hentikan server');
432
+ console.log(' ' + C.cyan + 'foliokit restart' + C.reset + ' Mulai ulang server');
433
+ console.log(' ' + C.cyan + 'foliokit status' + C.reset + ' Tampilkan status');
434
+ console.log(' ' + C.cyan + 'foliokit logs' + C.reset + ' Tampilkan log terakhir');
435
+ console.log(' ' + C.cyan + 'foliokit --port 8080' + C.reset + ' Tentukan port lain');
436
+ console.log(' ' + C.cyan + 'foliokit --help' + C.reset + ' Bantuan ini');
437
+ console.log('');
438
+ }
439
+
440
+ // ==================================================
441
+ // MAIN
442
+ // ==================================================
443
+ async function main() {
444
+ const cmd = (process.argv[2] || '').toLowerCase();
445
+
446
+ if (cmd === '--help' || cmd === '-h' || cmd === 'help') return cmdHelp();
447
+ if (cmd === '--version' || cmd === '-v') return console.log('foliokit ' + VERSION);
448
+ if (cmd === 'stop') return cmdStop();
449
+ if (cmd === 'status') return printStatus();
450
+ if (cmd === 'logs') return cmdLogs();
451
+ if (cmd === 'restart') return cmdRestart();
452
+ if (cmd === 'start') return cmdStart();
453
+
454
+ // default: menu interaktif — pastikan server aktif lebih dulu
455
+ const s = currentStatus();
456
+ if (!s.running) {
457
+ const port = portFromArgs();
458
+ startServer(port);
459
+ const ok = await waitForPort(port);
460
+ if (!ok) {
461
+ banner();
462
+ console.log(' ' + C.red + 'Gagal menjalankan server pada port ' + port + '.' + C.reset);
463
+ console.log(' ' + C.gray + 'Cek log: ' + LOG_FILE + C.reset + '\n');
464
+ return;
465
+ }
466
+ }
467
+ menu();
468
+ }
469
+
470
+ process.on('uncaughtException', (err) => {
471
+ if (err && err.code === 'EPIPE') process.exit(0);
472
+ console.error(C.red + 'Terjadi kesalahan: ' + (err.message || err) + C.reset);
473
+ process.exit(1);
474
+ });
475
+
476
+ main();