tokocode 0.0.0-stage → 1.1.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,222 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import yauzl, {} from 'yauzl';
6
+ import { EXTRACTION_LIMITS, SOURCE_DIR_NAMES } from '../config/constants.js';
7
+ import { CliError } from '../utils/errors.js';
8
+ import { freeSpace, humanBytes, isInside } from '../utils/filesystem.js';
9
+ /**
10
+ * Safe ZIP extraction.
11
+ *
12
+ * Pass 1 (scan) reads only the central directory and rejects the archive before anything is
13
+ * written when it contains: absolute paths, drive letters, ".." segments (ZIP Slip), encrypted or
14
+ * unsupported entries, names Windows cannot store (on Windows), too many entries, or a zip bomb.
15
+ * It also detects a single wrapper folder ("project-v1/…") to strip, so the project does not end
16
+ * up nested one level too deep. Symbolic links are skipped, never created.
17
+ *
18
+ * Pass 2 writes every entry into `destination`, re-checking that each resolved path stays inside
19
+ * it. Entry sizes are validated by yauzl while streaming.
20
+ */
21
+ const UNIX_FILE_TYPE = 0o170000;
22
+ const UNIX_SYMLINK = 0o120000;
23
+ const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
24
+ // eslint-disable-next-line no-control-regex
25
+ const WINDOWS_INVALID = /[<>:"|?*\u0000-\u001F]/;
26
+ const JUNK = /(^|\/)(__MACOSX\/|\.DS_Store$|Thumbs\.db$)/;
27
+ export async function scanArchive(zipPath) {
28
+ const zip = await openZip(zipPath);
29
+ const raw = [];
30
+ let totalBytes = 0;
31
+ const problems = [];
32
+ try {
33
+ if (zip.entryCount > EXTRACTION_LIMITS.maxEntries) {
34
+ throw new CliError('zip_too_many_entries', `Paket berisi terlalu banyak file (${zip.entryCount}).`, 'Hubungi dukungan TokoCode.');
35
+ }
36
+ await forEachEntry(zip, async (entry) => {
37
+ const name = entry.fileName.replace(/\\/g, '/');
38
+ if (JUNK.test(name)) {
39
+ return;
40
+ }
41
+ checkPath(name);
42
+ if (entry.isEncrypted()) {
43
+ throw new CliError('zip_encrypted', 'Paket ZIP terenkripsi tidak didukung.', 'Hubungi dukungan TokoCode.');
44
+ }
45
+ if (!entry.canDecodeFileData()) {
46
+ throw new CliError('zip_unsupported', `Metode kompresi file "${name}" tidak didukung.`, 'Hubungi dukungan TokoCode.');
47
+ }
48
+ const mode = (entry.externalFileAttributes >>> 16) & 0xffff;
49
+ const symlink = (mode & UNIX_FILE_TYPE) === UNIX_SYMLINK;
50
+ const directory = name.endsWith('/');
51
+ if (!directory && !symlink) {
52
+ totalBytes += entry.uncompressedSize;
53
+ const ratio = entry.compressedSize > 0 ? entry.uncompressedSize / entry.compressedSize : entry.uncompressedSize > 0 ? Infinity : 0;
54
+ if (entry.uncompressedSize >= EXTRACTION_LIMITS.ratioCheckFromBytes && ratio > EXTRACTION_LIMITS.maxRatio) {
55
+ throw new CliError('zip_bomb', 'Paket ZIP mencurigakan (rasio kompresi tidak wajar).', 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
56
+ }
57
+ if (totalBytes > EXTRACTION_LIMITS.maxTotalBytes) {
58
+ throw new CliError('zip_bomb', `Isi paket terlalu besar (lebih dari ${humanBytes(EXTRACTION_LIMITS.maxTotalBytes)}).`, 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
59
+ }
60
+ }
61
+ if (process.platform === 'win32') {
62
+ const bad = name.split('/').filter((segment) => segment !== '').find((segment) => WINDOWS_RESERVED.test(segment) || WINDOWS_INVALID.test(segment) || /[. ]$/.test(segment));
63
+ if (bad !== undefined && problems.length < 5) {
64
+ problems.push(name);
65
+ }
66
+ }
67
+ raw.push({ name, directory, symlink, executable: (mode & 0o111) !== 0 && !directory, size: entry.uncompressedSize });
68
+ });
69
+ }
70
+ catch (error) {
71
+ zip.close();
72
+ throw unsafeArchive(error);
73
+ }
74
+ zip.close();
75
+ if (problems.length > 0) {
76
+ throw new CliError('zip_windows_names', 'Paket berisi nama file yang tidak dapat disimpan di Windows.', `Contoh: ${problems.join(', ')}. Pasang di WSL/Linux/macOS, atau hubungi dukungan TokoCode.`);
77
+ }
78
+ if (raw.length === 0) {
79
+ throw new CliError('zip_empty', 'Paket ZIP kosong.', 'Hubungi dukungan TokoCode.');
80
+ }
81
+ const strippedRoot = wrapperFolder(raw.map((entry) => entry.name));
82
+ const prefix = strippedRoot === null ? '' : strippedRoot + '/';
83
+ const entries = raw
84
+ .map((entry) => ({ ...entry, relative: entry.name.slice(prefix.length).replace(/\/+$/, '') }))
85
+ .filter((entry) => entry.relative !== '');
86
+ return { entries, totalBytes, strippedRoot };
87
+ }
88
+ /**
89
+ * Extracts into `destination` (an empty folder the caller created for this run).
90
+ */
91
+ export async function extractArchive(zipPath, destination, callbacks = {}) {
92
+ const plan = await scanArchive(zipPath);
93
+ const free = await freeSpace(destination);
94
+ if (free !== null && plan.totalBytes + 50 * 1024 * 1024 > free) {
95
+ throw new CliError('enospc', `Ruang penyimpanan tidak cukup: butuh ${humanBytes(plan.totalBytes)}, tersedia ${humanBytes(free)}.`, 'Kosongkan ruang disk atau pilih lokasi instalasi di drive lain.');
96
+ }
97
+ const byName = new Map(plan.entries.map((entry) => [entry.name, entry]));
98
+ const result = { files: 0, directories: 0, bytes: 0, skippedLinks: [], strippedRoot: plan.strippedRoot };
99
+ const root = path.resolve(destination);
100
+ await fs.mkdir(root, { recursive: true });
101
+ const zip = await openZip(zipPath);
102
+ try {
103
+ await forEachEntry(zip, async (entry) => {
104
+ const planned = byName.get(entry.fileName.replace(/\\/g, '/'));
105
+ if (!planned) {
106
+ return;
107
+ }
108
+ const target = path.resolve(root, ...planned.relative.split('/'));
109
+ if (!isInside(root, target) || target === root) {
110
+ throw new CliError('zip_slip', `Paket berisi path berbahaya: ${planned.name}`, 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
111
+ }
112
+ if (planned.symlink) {
113
+ result.skippedLinks.push(planned.relative);
114
+ return;
115
+ }
116
+ if (planned.directory) {
117
+ await fs.mkdir(target, { recursive: true });
118
+ result.directories++;
119
+ return;
120
+ }
121
+ await fs.mkdir(path.dirname(target), { recursive: true });
122
+ const stream = await openEntry(zip, entry);
123
+ await pipeline(stream, createWriteStream(target, { flags: 'w', mode: planned.executable ? 0o755 : 0o644 }));
124
+ try {
125
+ const modified = entry.getLastModDate();
126
+ await fs.utimes(target, modified, modified);
127
+ }
128
+ catch {
129
+ // Timestamps are cosmetic.
130
+ }
131
+ result.files++;
132
+ result.bytes += planned.size;
133
+ callbacks.onProgress?.(result.bytes, plan.totalBytes);
134
+ });
135
+ }
136
+ catch (error) {
137
+ throw unsafeArchive(error);
138
+ }
139
+ finally {
140
+ zip.close();
141
+ }
142
+ return result;
143
+ }
144
+ /**
145
+ * The single top-level folder that wraps everything ("toko-v1.0/…"), or null. A folder that is a
146
+ * project's own source folder (app/, src/, public/…) is never treated as a wrapper.
147
+ */
148
+ export function wrapperFolder(names) {
149
+ const roots = new Set();
150
+ let hasNested = false;
151
+ for (const name of names) {
152
+ const [first, ...rest] = name.split('/');
153
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === '')) {
154
+ // A file at the root (or the wrapper's own directory entry).
155
+ if (!name.endsWith('/')) {
156
+ return null;
157
+ }
158
+ }
159
+ else if (rest.some((segment) => segment !== '')) {
160
+ hasNested = true;
161
+ }
162
+ roots.add(first ?? '');
163
+ }
164
+ const [only] = [...roots];
165
+ return roots.size === 1 && hasNested && only !== undefined && only !== '' && !SOURCE_DIR_NAMES.has(only.toLowerCase()) ? only : null;
166
+ }
167
+ function checkPath(name) {
168
+ const segments = name.split('/');
169
+ if (name.startsWith('/') || /^[A-Za-z]:/.test(name) || name.startsWith('//') || segments.includes('..') || name.includes('\u0000')) {
170
+ throw new CliError('zip_slip', `Paket berisi path berbahaya: ${name.slice(0, 80)}`, 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
171
+ }
172
+ }
173
+ function unsafeArchive(error) {
174
+ if (error instanceof CliError) {
175
+ return error;
176
+ }
177
+ const message = error?.message ?? '';
178
+ if (/invalid relative path|absolute path|invalid characters in fileName/i.test(message)) {
179
+ return new CliError('zip_slip', 'Paket berisi path file berbahaya.', 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.', 1, { cause: error });
180
+ }
181
+ if (/end of central directory|invalid comment length|not a zip|unexpected EOF|invalid signature|too many length or distance symbols|invalid (stored|code|distance)|unknown compression|uncompressed size|compressed size|crc32/i.test(message)) {
182
+ return new CliError('zip_corrupt', 'File ZIP rusak atau tidak lengkap.', 'Jalankan ulang npx tokocode untuk mengunduh ulang. Jika berulang, hubungi dukungan TokoCode.', 1, { cause: error });
183
+ }
184
+ return error;
185
+ }
186
+ function openZip(file) {
187
+ return new Promise((resolve, reject) => {
188
+ yauzl.open(file, { lazyEntries: true, autoClose: false, decodeStrings: true, validateEntrySizes: true, strictFileNames: false }, (error, zip) => {
189
+ if (error || !zip) {
190
+ reject(unsafeArchive(error ?? new Error('invalid signature')));
191
+ return;
192
+ }
193
+ resolve(zip);
194
+ });
195
+ });
196
+ }
197
+ function forEachEntry(zip, handler) {
198
+ return new Promise((resolve, reject) => {
199
+ let failed = false;
200
+ zip.on('entry', (entry) => {
201
+ handler(entry).then(() => zip.readEntry(), (error) => {
202
+ failed = true;
203
+ reject(error);
204
+ });
205
+ });
206
+ zip.once('end', () => {
207
+ if (!failed) {
208
+ resolve();
209
+ }
210
+ });
211
+ zip.once('error', (error) => {
212
+ failed = true;
213
+ reject(error);
214
+ });
215
+ zip.readEntry();
216
+ });
217
+ }
218
+ function openEntry(zip, entry) {
219
+ return new Promise((resolve, reject) => {
220
+ zip.openReadStream(entry, (error, stream) => (error || !stream ? reject(error ?? new Error('stream unavailable')) : resolve(stream)));
221
+ });
222
+ }
@@ -0,0 +1,65 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { STATE_DIR } from '../config/constants.js';
5
+ import { debug } from '../utils/logger.js';
6
+ import { removeQuietly } from '../utils/filesystem.js';
7
+ /**
8
+ * Resumable installations. After a token is redeemed the CLI keeps the download session (short-
9
+ * lived secret, not the token) in the user's temp folder with owner-only permissions, so running
10
+ * `npx tokocode` again continues an interrupted download instead of needing a new token.
11
+ */
12
+ export function stateDir() {
13
+ return process.env.TOKOCODE_STATE_DIR || STATE_DIR;
14
+ }
15
+ export function statePath(sessionId) {
16
+ return path.join(stateDir(), `${sessionId}.json`);
17
+ }
18
+ export function partPath(sessionId) {
19
+ return path.join(stateDir(), `${sessionId}.zip.part`);
20
+ }
21
+ export async function saveState(state) {
22
+ await fs.mkdir(stateDir(), { recursive: true, mode: 0o700 });
23
+ const file = statePath(state.session.id);
24
+ const temp = `${file}.${randomBytes(4).toString('hex')}.tmp`;
25
+ await fs.writeFile(temp, JSON.stringify(state, null, 2), { mode: 0o600 });
26
+ await fs.rename(temp, file);
27
+ }
28
+ /**
29
+ * Unfinished installations for this store whose recovery window is still open (newest first).
30
+ * Expired ones are cleaned up.
31
+ */
32
+ export async function pendingStates(apiUrl) {
33
+ let files;
34
+ try {
35
+ files = (await fs.readdir(stateDir())).filter((name) => name.endsWith('.json'));
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ const states = [];
41
+ for (const name of files) {
42
+ const file = path.join(stateDir(), name);
43
+ try {
44
+ const state = JSON.parse(await fs.readFile(file, 'utf8'));
45
+ if (state.schema !== 1 || !state.session?.id || !/^[a-f0-9]{32}$/.test(state.session.id)) {
46
+ continue;
47
+ }
48
+ if (Date.parse(state.session.refresh_until) <= Date.now()) {
49
+ await discardState(state.session.id);
50
+ continue;
51
+ }
52
+ if (state.apiUrl === apiUrl) {
53
+ states.push(state);
54
+ }
55
+ }
56
+ catch (error) {
57
+ debug(`ignoring unreadable state ${name}`, error.message);
58
+ }
59
+ }
60
+ return states.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
61
+ }
62
+ export async function discardState(sessionId) {
63
+ await removeQuietly(statePath(sessionId));
64
+ await removeQuietly(partPath(sessionId));
65
+ }
@@ -0,0 +1,39 @@
1
+ import { EXIT } from '../config/constants.js';
2
+ import { CliError } from '../utils/errors.js';
3
+ import { ask, isInteractive, out } from '../utils/terminal.js';
4
+ import { formatToken, normalizeToken } from '../utils/validation.js';
5
+ const MAX_PROMPTS = 3;
6
+ /**
7
+ * Gets the installation token from --token, TOKOCODE_TOKEN or a prompt, and checks its format
8
+ * and checksum locally so a typo is caught before any network call.
9
+ *
10
+ * @returns the token formatted as TK-XXXX-…
11
+ */
12
+ export async function readInstallationToken(fromOption) {
13
+ const provided = fromOption ?? process.env.TOKOCODE_TOKEN;
14
+ if (provided !== undefined && provided !== '') {
15
+ const normalized = normalizeToken(provided);
16
+ if (!normalized) {
17
+ throw invalidFormat();
18
+ }
19
+ return formatToken(normalized);
20
+ }
21
+ if (!isInteractive()) {
22
+ throw new CliError('needs_input', 'Installation token belum diberikan.', 'Jalankan di terminal biasa, atau gunakan opsi --token TK-XXXX-…', EXIT.usage);
23
+ }
24
+ for (let attempt = 1; attempt <= MAX_PROMPTS; attempt++) {
25
+ const answer = await ask('Masukkan installation token Anda:');
26
+ const normalized = normalizeToken(answer);
27
+ if (normalized) {
28
+ return formatToken(normalized);
29
+ }
30
+ out.fail('Format token tidak valid.');
31
+ out.muted(attempt < MAX_PROMPTS
32
+ ? ' Token berbentuk TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX. Salin ulang dari dashboard TokoCode (Akun > Instalasi CLI).'
33
+ : '');
34
+ }
35
+ throw invalidFormat();
36
+ }
37
+ function invalidFormat() {
38
+ return new CliError('token_invalid', 'Token tidak valid atau tidak ditemukan.', 'Silakan periksa kembali installation token Anda. Token berbentuk TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX dan dapat disalin dari dashboard TokoCode (Akun > Instalasi CLI).');
39
+ }
@@ -0,0 +1,2 @@
1
+ /** Shapes of the TokoCode CLI API (/api/v1/cli) and of the CLI's own state. */
2
+ export {};
@@ -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
+ }