hypeframe 0.1.0 → 0.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/dist/index.js ADDED
@@ -0,0 +1,2449 @@
1
+ // packages/hypeframe/src/cli/args.ts
2
+ var VALUE = new Map([
3
+ ["--gateway", "gateway"],
4
+ ["--web", "web"],
5
+ ["--name", "name"],
6
+ ["--nama", "name"],
7
+ ["--language", "language"],
8
+ ["--lang", "language"]
9
+ ]);
10
+ var SWITCH = new Map([
11
+ ["--gpu", "gpu"],
12
+ ["--no-browser", "noBrowser"],
13
+ ["--tanpa-browser", "noBrowser"],
14
+ ["--help", "help"],
15
+ ["-h", "help"],
16
+ ["--version", "version"],
17
+ ["-v", "version"]
18
+ ]);
19
+ var ALIAS = { keluar: "logout", masuk: "login", mulai: "start", bantuan: "help" };
20
+ function parseArgs(argv) {
21
+ const out = { command: null, rest: [], flags: {} };
22
+ for (let i = 0;i < argv.length; i++) {
23
+ const a = argv[i];
24
+ const [flag, inline] = a.startsWith("--") && a.includes("=") ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, undefined];
25
+ const v = VALUE.get(flag);
26
+ if (v) {
27
+ const value = inline ?? argv[i + 1];
28
+ if (inline === undefined)
29
+ i++;
30
+ if (value !== undefined && value !== "")
31
+ out.flags[v] = value;
32
+ continue;
33
+ }
34
+ const s = SWITCH.get(flag);
35
+ if (s) {
36
+ out.flags[s] = inline === undefined ? true : !/^(0|false|off|no)$/i.test(inline);
37
+ continue;
38
+ }
39
+ if (a === "--no-gpu") {
40
+ out.flags.gpu = false;
41
+ continue;
42
+ }
43
+ if (out.command === null && !a.startsWith("-"))
44
+ out.command = ALIAS[a] ?? a;
45
+ else
46
+ out.rest.push(a);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ // packages/hypeframe/src/config/account.ts
52
+ import fs2 from "node:fs";
53
+
54
+ // packages/hypeframe/src/config/paths.ts
55
+ import fs from "node:fs";
56
+ import os from "node:os";
57
+ import path from "node:path";
58
+ function dataDir() {
59
+ const d = process.env.HYPEFRAME_DIR || process.env.HYPEFRAME_MESIN_DIR || path.join(os.homedir(), ".hypeframe");
60
+ fs.mkdirSync(d, { recursive: true, mode: 448 });
61
+ return d;
62
+ }
63
+ var sub = (...p) => {
64
+ const d = path.join(dataDir(), ...p);
65
+ fs.mkdirSync(d, { recursive: true });
66
+ return d;
67
+ };
68
+ var accountFile = () => path.join(dataDir(), "akun.json");
69
+ var settingsFile = () => path.join(dataDir(), "settings.json");
70
+ var lockFile = () => path.join(dataDir(), "mesin.kunci");
71
+ var logDir = () => sub("log");
72
+ var cacheDir = () => sub("cache");
73
+ var renderDir = () => sub("kerja", "render");
74
+
75
+ // packages/hypeframe/src/config/account.ts
76
+ function readAccount() {
77
+ try {
78
+ const a = JSON.parse(fs2.readFileSync(accountFile(), "utf8"));
79
+ return a && typeof a.token === "string" ? a : null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+ function saveAccount(a) {
85
+ const f = accountFile();
86
+ fs2.writeFileSync(`${f}.tmp`, JSON.stringify(a), { mode: 384 });
87
+ fs2.renameSync(`${f}.tmp`, f);
88
+ }
89
+ function deleteAccount() {
90
+ fs2.rmSync(accountFile(), { force: true });
91
+ }
92
+ function maskEmail(email) {
93
+ const m = String(email || "").match(/^(.)[^@\s]*(@[^\s]+)$/);
94
+ return m ? `${m[1]}***${m[2]}`.replace(/[\u0000-\u001f\u007f]/g, "") : "-";
95
+ }
96
+
97
+ // packages/hypeframe/src/config/settings.ts
98
+ import fs3 from "node:fs";
99
+ import os2 from "node:os";
100
+ var DEFAULT_GATEWAY = "https://api.sairipedia.com";
101
+ var DEFAULT_WEB = "https://hype-frame.com";
102
+ function readSettings() {
103
+ try {
104
+ return JSON.parse(fs3.readFileSync(settingsFile(), "utf8"));
105
+ } catch {
106
+ return {};
107
+ }
108
+ }
109
+ function saveSettings(s) {
110
+ const f = settingsFile();
111
+ fs3.writeFileSync(`${f}.tmp`, JSON.stringify({ ...readSettings(), ...s }, null, 2), { mode: 384 });
112
+ fs3.renameSync(`${f}.tmp`, f);
113
+ }
114
+ function resolveSettings(flags = {}) {
115
+ const s = readSettings();
116
+ const clean = (u) => u.replace(/\/+$/, "");
117
+ return {
118
+ gateway: clean(flags.gateway || process.env.HYPEFRAME_GATEWAY_URL || s.gateway || DEFAULT_GATEWAY),
119
+ web: clean(flags.web || process.env.HYPEFRAME_WEB_URL || s.web || DEFAULT_WEB),
120
+ name: (flags.name || s.name || os2.hostname()).slice(0, 40),
121
+ gpu: flags.gpu ?? s.gpu ?? false
122
+ };
123
+ }
124
+ function osName() {
125
+ return { win32: "windows", darwin: "macos", linux: "linux", android: "android" }[process.platform] || process.platform;
126
+ }
127
+
128
+ // packages/hypeframe/src/ui/locale.ts
129
+ function systemLang() {
130
+ const env = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || Intl.DateTimeFormat().resolvedOptions().locale || "";
131
+ return /^id\b|^id[-_]|^in[-_]/i.test(env) ? "id" : "en";
132
+ }
133
+ var cached = null;
134
+ function lang() {
135
+ if (cached)
136
+ return cached;
137
+ const forced = process.env.HYPEFRAME_LANG;
138
+ const s = forced === "id" || forced === "en" ? forced : readSettings().language;
139
+ cached = s === "id" || s === "en" ? s : systemLang();
140
+ return cached;
141
+ }
142
+ var resetLang = () => void (cached = null);
143
+ var id = {
144
+ "banner.tagline": "mesin lokal untuk HypeFrame Web",
145
+ "start.title": "HypeFrame mesin {versi} ({os}, {nama})",
146
+ "pair.open": "Buka {link} lalu tekan Sambungkan. Kode: {code}",
147
+ "pair.done": "Tersambung ke akun {email}",
148
+ "pair.unreachable": "Gateway tidak terjangkau. Mencoba lagi...",
149
+ "pair.busy": "Terlalu banyak permintaan kode. Mencoba lagi sebentar lagi...",
150
+ "pair.refused": "Gateway menolak permintaan kode ({status}). Mencoba lagi...",
151
+ "pair.expired": "Kode sudah kedaluwarsa. Jalankan lagi: npx hypeframe",
152
+ "pair.badCode": "Gateway mengirim kode yang tidak sah.",
153
+ "pair.badWeb": "Alamat HypeFrame Web tidak sah.",
154
+ "login.already": "Perangkat ini sudah tersambung. Untuk ganti akun: hypeframe logout, lalu hypeframe login.",
155
+ "logout.done": "Perangkat ini sudah dilepas dari akun. Jalankan lagi npx hypeframe untuk menyambungkan ulang.",
156
+ "engine.ready": "Mesin siap. Biarkan jendela ini terbuka selama memakai HypeFrame Web.",
157
+ "engine.reconnected": "Tersambung lagi.",
158
+ "engine.lost": "Sambungan ke HypeFrame putus, mencoba lagi...",
159
+ "engine.revoked": "Perangkat ini sudah diputus dari akun. Jalankan lagi untuk menyambungkan ulang.",
160
+ "engine.tooOld": "Versi mesin ini terlalu lama. Jalankan: npx hypeframe@latest",
161
+ "engine.replaced": "Mesin ini sudah tersambung dari jendela atau komputer lain dengan akun yang sama, jadi yang ini berhenti.",
162
+ "engine.running": "Mesin sudah berjalan di terminal lain.",
163
+ "engine.stopHint": "Tekan Ctrl+C untuk berhenti.",
164
+ "engine.stopped": "Mesin berhenti.",
165
+ "render.ready": "Render siap (Chrome {chrome}{extra}).",
166
+ "render.noAlpha": "; klip transparan dibuat di tempat lain",
167
+ "render.notYet": "Render di mesin ini belum bisa: {reason}. Mesin tetap tersambung; dicoba lagi 10 menit lagi.",
168
+ "render.noH264": "Chrome {chrome} tidak bisa membuat video H.264",
169
+ "render.downloading": "Mengunduh Chrome untuk render (sekali saja)",
170
+ "render.job": "Render {kind} dimulai {size}",
171
+ "render.jobDone": "Render selesai dalam {sec} ({size})",
172
+ "render.jobFailed": "Render gagal: {reason}",
173
+ "render.jobCancelled": "Render dibatalkan dari web.",
174
+ "render.kindVideo": "video",
175
+ "render.kindClip": "klip",
176
+ "menu.question": "Mau apa?",
177
+ "menu.start": "Nyalakan mesin",
178
+ "menu.startPair": "sambungkan akun dulu",
179
+ "menu.open": "Buka HypeFrame Web",
180
+ "menu.bench": "Tes kecepatan render",
181
+ "menu.history": "Riwayat render",
182
+ "menu.agent": "Asisten AI di mesin",
183
+ "menu.soon": "segera hadir",
184
+ "menu.autostart": "Nyala otomatis",
185
+ "menu.config": "Pengaturan",
186
+ "menu.doctor": "Periksa perangkat",
187
+ "menu.clean": "Bersihkan ruang",
188
+ "menu.report": "Buat laporan masalah",
189
+ "menu.update": "Perbarui hypeframe",
190
+ "menu.login": "Sambungkan ke akun",
191
+ "menu.logout": "Lepas perangkat dari akun",
192
+ "menu.exit": "Keluar",
193
+ "menu.bye": "Sampai jumpa.",
194
+ "agent.soon": "Asisten AI yang bekerja langsung di perangkatmu sedang disiapkan.",
195
+ "status.account": "Akun",
196
+ "status.engine": "Mesin",
197
+ "status.device": "Perangkat",
198
+ "status.render": "Render",
199
+ "status.recent": "24 jam",
200
+ "status.recentCount": "{n} render",
201
+ "status.version": "Versi",
202
+ "status.notPaired": "belum tersambung",
203
+ "status.running": "berjalan (pid {pid})",
204
+ "status.stopped": "mati",
205
+ "status.chromeLater": "Chrome diunduh saat mesin menyala",
206
+ "status.gpu": "GPU",
207
+ "status.on": "nyala",
208
+ "status.off": "mati",
209
+ "confirm.logout": "Lepas perangkat ini dari akun?",
210
+ "config.name": "Nama perangkat",
211
+ "config.gpu": "Render memakai GPU perangkat? (lebih cepat; tanpa GPU hasilnya sama persis dengan server)",
212
+ "config.language": "Bahasa tampilan",
213
+ "config.auto": "Ikuti sistem",
214
+ "config.saved": "Pengaturan disimpan.",
215
+ "config.restart": "Berlaku saat mesin dinyalakan berikutnya.",
216
+ "doctor.title": "Memeriksa perangkat",
217
+ "doctor.nodeOld": "(butuh 20.3 atau lebih baru)",
218
+ "doctor.disk": "Ruang data",
219
+ "doctor.free": "{size} kosong",
220
+ "doctor.noFfmpeg": "ffmpeg tidak tersedia untuk sistem ini",
221
+ "doctor.chromeLater": "belum ada; diunduh otomatis saat mesin menyala",
222
+ "doctor.alpha": "Klip transparan",
223
+ "doctor.alphaNo": "tidak didukung Chrome ini; dibuat di server atau HP",
224
+ "doctor.yes": "bisa",
225
+ "doctor.no": "tidak bisa",
226
+ "doctor.unreachable": "tidak terjangkau",
227
+ "doctor.summaryOk": "Semua siap.",
228
+ "doctor.summaryWarn": "{n} hal perlu perhatian, render tetap jalan.",
229
+ "doctor.summaryBad": "{n} masalah menghalangi render.",
230
+ "bench.title": "Tes kecepatan render",
231
+ "bench.gpu": "GPU perangkat",
232
+ "bench.cpu": "tanpa GPU, sama dengan server",
233
+ "bench.running": "Mengukur {size}...",
234
+ "bench.estimate": "video 60 detik ≈ {time}",
235
+ "bench.note": "Perkiraan. Proyek dengan banyak efek butuh waktu lebih lama.",
236
+ "history.empty": "Belum ada render dalam 24 jam terakhir.",
237
+ "history.cancelled": "dibatalkan",
238
+ "history.openFolder": "Buka folder hasil render?",
239
+ "autostart.question": "Nyalakan mesin otomatis saat masuk ke komputer?",
240
+ "autostart.on": "Nyala otomatis aktif: mesin menyala saat kamu masuk ke komputer.",
241
+ "autostart.off": "Nyala otomatis dimatikan.",
242
+ "autostart.isOn": "Nyala otomatis: nyala.",
243
+ "autostart.isOff": "Nyala otomatis: mati.",
244
+ "autostart.needGlobal": "Nyala otomatis butuh hypeframe yang terpasang tetap, bukan salinan sementara npx.",
245
+ "autostart.needLogin": "Sambungkan perangkat ke akun dulu (hypeframe login).",
246
+ "clean.question": "Hapus Chrome unduhan, cache halaman render, log lama, dan render yang gagal? Video yang sudah jadi tetap disimpan.",
247
+ "clean.running": "Matikan mesin dulu sebelum membersihkan.",
248
+ "clean.done": "Ruang dibersihkan: {size}.",
249
+ "report.done": "Laporan disimpan: {file}",
250
+ "report.hint": "Kirim berkas ini ke tim HypeFrame. Token tidak ikut di dalamnya.",
251
+ "update.running": "Memperbarui hypeframe...",
252
+ "update.done": "hypeframe sudah versi terbaru.",
253
+ "update.failed": "Pembaruan gagal. Coba jalankan sendiri: npm i -g hypeframe@latest",
254
+ "update.npx": "Kamu menjalankan hypeframe lewat npx; versi terbaru dipakai dengan:",
255
+ "open.done": "Membuka {web}",
256
+ "help.usage": "Pakai",
257
+ "help.commands": "Perintah",
258
+ "help.options": "Pilihan",
259
+ "help.noCommand": "Tanpa perintah: menu di terminal, langsung menyalakan mesin bila bukan terminal.",
260
+ "help.unknown": "Perintah tidak dikenal: {command}",
261
+ "help.start": "nyalakan mesin (menyambungkan akun bila perlu)",
262
+ "help.login": "sambungkan perangkat ini ke akun HypeFrame",
263
+ "help.logout": "lepas perangkat ini dari akun",
264
+ "help.status": "akun, mesin, render, versi",
265
+ "help.open": "buka HypeFrame Web di browser",
266
+ "help.doctor": "periksa Node, Chrome, ffmpeg, koneksi, ruang disk",
267
+ "help.bench": "ukur kecepatan render 720p dan 1080p",
268
+ "help.history": "render 24 jam terakhir",
269
+ "help.autostart": "nyalakan mesin saat masuk ke komputer",
270
+ "help.config": "nama perangkat, GPU, bahasa",
271
+ "help.clean": "hapus cache dan render yang gagal",
272
+ "help.report": "buat laporan masalah (tanpa token)",
273
+ "help.update": "perbarui ke versi terbaru",
274
+ "help.gpu": "render memakai GPU perangkat",
275
+ "help.name": "nama perangkat yang terlihat di web",
276
+ "help.noBrowser": "jangan buka browser saat menyambungkan",
277
+ "help.language": "bahasa tampilan",
278
+ "help.addresses": "alamat gateway / web lain (untuk pengembang)"
279
+ };
280
+ var en = {
281
+ "banner.tagline": "local engine for HypeFrame Web",
282
+ "start.title": "HypeFrame engine {versi} ({os}, {nama})",
283
+ "pair.open": "Open {link} and press Connect. Code: {code}",
284
+ "pair.done": "Connected to account {email}",
285
+ "pair.unreachable": "Gateway unreachable. Retrying...",
286
+ "pair.busy": "Too many code requests. Retrying shortly...",
287
+ "pair.refused": "Gateway refused the code request ({status}). Retrying...",
288
+ "pair.expired": "The code expired. Run again: npx hypeframe",
289
+ "pair.badCode": "The gateway sent an invalid code.",
290
+ "pair.badWeb": "Invalid HypeFrame Web address.",
291
+ "login.already": "This device is already connected. To switch accounts: hypeframe logout, then hypeframe login.",
292
+ "logout.done": "This device was removed from the account. Run npx hypeframe again to reconnect.",
293
+ "engine.ready": "Engine ready. Keep this window open while you use HypeFrame Web.",
294
+ "engine.reconnected": "Reconnected.",
295
+ "engine.lost": "Lost connection to HypeFrame, retrying...",
296
+ "engine.revoked": "This device was disconnected from the account. Run again to reconnect.",
297
+ "engine.tooOld": "This engine is too old. Run: npx hypeframe@latest",
298
+ "engine.replaced": "This engine is already connected from another window or computer with the same account, so this one stops.",
299
+ "engine.running": "The engine is already running in another terminal.",
300
+ "engine.stopHint": "Press Ctrl+C to stop.",
301
+ "engine.stopped": "Engine stopped.",
302
+ "render.ready": "Render ready (Chrome {chrome}{extra}).",
303
+ "render.noAlpha": "; transparent clips are made elsewhere",
304
+ "render.notYet": "Rendering is not available yet: {reason}. The engine stays connected; retrying in 10 minutes.",
305
+ "render.noH264": "Chrome {chrome} cannot encode H.264 video",
306
+ "render.downloading": "Downloading Chrome for rendering (one time)",
307
+ "render.job": "Rendering {kind} {size}",
308
+ "render.jobDone": "Render finished in {sec} ({size})",
309
+ "render.jobFailed": "Render failed: {reason}",
310
+ "render.jobCancelled": "Render cancelled from the web.",
311
+ "render.kindVideo": "video",
312
+ "render.kindClip": "clip",
313
+ "menu.question": "What would you like to do?",
314
+ "menu.start": "Start the engine",
315
+ "menu.startPair": "connects your account first",
316
+ "menu.open": "Open HypeFrame Web",
317
+ "menu.bench": "Render speed test",
318
+ "menu.history": "Render history",
319
+ "menu.agent": "AI assistant on this machine",
320
+ "menu.soon": "coming soon",
321
+ "menu.autostart": "Start automatically",
322
+ "menu.config": "Settings",
323
+ "menu.doctor": "Check this machine",
324
+ "menu.clean": "Free up space",
325
+ "menu.report": "Create a problem report",
326
+ "menu.update": "Update hypeframe",
327
+ "menu.login": "Connect to an account",
328
+ "menu.logout": "Disconnect this device",
329
+ "menu.exit": "Exit",
330
+ "menu.bye": "See you.",
331
+ "agent.soon": "An AI assistant that works right on your device is on the way.",
332
+ "status.account": "Account",
333
+ "status.engine": "Engine",
334
+ "status.device": "Device",
335
+ "status.render": "Render",
336
+ "status.recent": "24 hours",
337
+ "status.recentCount": "{n} renders",
338
+ "status.version": "Version",
339
+ "status.notPaired": "not connected",
340
+ "status.running": "running (pid {pid})",
341
+ "status.stopped": "stopped",
342
+ "status.chromeLater": "Chrome is downloaded when the engine starts",
343
+ "status.gpu": "GPU",
344
+ "status.on": "on",
345
+ "status.off": "off",
346
+ "confirm.logout": "Disconnect this device from the account?",
347
+ "config.name": "Device name",
348
+ "config.gpu": "Render with this machine’s GPU? (faster; without it the output matches the server exactly)",
349
+ "config.language": "Display language",
350
+ "config.auto": "Follow the system",
351
+ "config.saved": "Settings saved.",
352
+ "config.restart": "Applies the next time the engine starts.",
353
+ "doctor.title": "Checking this machine",
354
+ "doctor.nodeOld": "(needs 20.3 or newer)",
355
+ "doctor.disk": "Data space",
356
+ "doctor.free": "{size} free",
357
+ "doctor.noFfmpeg": "ffmpeg is not available for this system",
358
+ "doctor.chromeLater": "not yet; downloaded automatically when the engine starts",
359
+ "doctor.alpha": "Transparent clips",
360
+ "doctor.alphaNo": "not supported by this Chrome; made on the server or phone",
361
+ "doctor.yes": "yes",
362
+ "doctor.no": "no",
363
+ "doctor.unreachable": "unreachable",
364
+ "doctor.summaryOk": "All set.",
365
+ "doctor.summaryWarn": "{n} things need attention; rendering still works.",
366
+ "doctor.summaryBad": "{n} problems block rendering.",
367
+ "bench.title": "Render speed test",
368
+ "bench.gpu": "device GPU",
369
+ "bench.cpu": "no GPU, same as the server",
370
+ "bench.running": "Measuring {size}...",
371
+ "bench.estimate": "60-second video ≈ {time}",
372
+ "bench.note": "An estimate. Projects with many effects take longer.",
373
+ "history.empty": "No renders in the last 24 hours.",
374
+ "history.cancelled": "cancelled",
375
+ "history.openFolder": "Open the render folder?",
376
+ "autostart.question": "Start the engine automatically when you sign in?",
377
+ "autostart.on": "Autostart on: the engine starts when you sign in.",
378
+ "autostart.off": "Autostart off.",
379
+ "autostart.isOn": "Autostart: on.",
380
+ "autostart.isOff": "Autostart: off.",
381
+ "autostart.needGlobal": "Autostart needs an installed hypeframe, not the temporary npx copy.",
382
+ "autostart.needLogin": "Connect this device to an account first (hypeframe login).",
383
+ "clean.question": "Delete the downloaded Chrome, cached render pages, old logs and failed renders? Finished videos are kept.",
384
+ "clean.running": "Stop the engine before cleaning up.",
385
+ "clean.done": "Freed {size}.",
386
+ "report.done": "Report saved: {file}",
387
+ "report.hint": "Send this file to the HypeFrame team. Tokens are not included.",
388
+ "update.running": "Updating hypeframe...",
389
+ "update.done": "hypeframe is up to date.",
390
+ "update.failed": "Update failed. Try it yourself: npm i -g hypeframe@latest",
391
+ "update.npx": "You are running hypeframe through npx; the latest version runs with:",
392
+ "open.done": "Opening {web}",
393
+ "help.usage": "Usage",
394
+ "help.commands": "Commands",
395
+ "help.options": "Options",
396
+ "help.noCommand": "No command: a menu in a terminal, the engine straight away otherwise.",
397
+ "help.unknown": "Unknown command: {command}",
398
+ "help.start": "start the engine (connects your account when needed)",
399
+ "help.login": "connect this device to a HypeFrame account",
400
+ "help.logout": "disconnect this device from the account",
401
+ "help.status": "account, engine, render, version",
402
+ "help.open": "open HypeFrame Web in the browser",
403
+ "help.doctor": "check Node, Chrome, ffmpeg, network, disk space",
404
+ "help.bench": "measure render speed at 720p and 1080p",
405
+ "help.history": "renders from the last 24 hours",
406
+ "help.autostart": "start the engine when you sign in",
407
+ "help.config": "device name, GPU, language",
408
+ "help.clean": "remove caches and failed renders",
409
+ "help.report": "create a problem report (no tokens)",
410
+ "help.update": "update to the latest version",
411
+ "help.gpu": "render with the device GPU",
412
+ "help.name": "device name shown on the web",
413
+ "help.noBrowser": "do not open a browser while connecting",
414
+ "help.language": "display language",
415
+ "help.addresses": "another gateway / web address (for developers)"
416
+ };
417
+ function t(key, vars = {}) {
418
+ const s = lang() === "id" ? id[key] : en[key];
419
+ return s.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? `{${k}}`));
420
+ }
421
+
422
+ // packages/hypeframe/src/ui/log.ts
423
+ import fs4 from "node:fs";
424
+ import path2 from "node:path";
425
+
426
+ // packages/hypeframe/src/ui/theme.ts
427
+ import picocolors from "picocolors";
428
+ var env = process.env;
429
+ var enabled = !("NO_COLOR" in env) && env.TERM !== "dumb" && ("FORCE_COLOR" in env ? env.FORCE_COLOR !== "0" : !!process.stdout.isTTY);
430
+ var pc = picocolors.createColors(enabled);
431
+ var truecolor = enabled && (/truecolor|24bit/i.test(env.COLORTERM ?? "") || !!env.WT_SESSION || env.TERM_PROGRAM === "vscode" || env.TERM_PROGRAM === "iTerm.app");
432
+ function hex(color, fallback) {
433
+ if (!truecolor)
434
+ return fallback;
435
+ const n = Number.parseInt(color.slice(1), 16);
436
+ const open = `\x1B[38;2;${n >> 16 & 255};${n >> 8 & 255};${n & 255}m`;
437
+ return (s) => `${open}${s}\x1B[39m`;
438
+ }
439
+ var color = {
440
+ brand: hex("#3DD6C3", pc.cyan),
441
+ ai: hex("#B49CFF", pc.magenta),
442
+ ok: hex("#4ADE80", pc.green),
443
+ warn: hex("#FACC15", pc.yellow),
444
+ error: hex("#F87171", pc.red),
445
+ info: hex("#7DD3FC", pc.blue),
446
+ muted: pc.dim,
447
+ bold: pc.bold,
448
+ underline: pc.underline
449
+ };
450
+ var icon = {
451
+ info: "●",
452
+ ok: "✔",
453
+ warn: "▲",
454
+ error: "✖",
455
+ detail: "↳",
456
+ dot: "·"
457
+ };
458
+ var plain = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
459
+
460
+ // packages/hypeframe/src/ui/log.ts
461
+ var SECRET = /\b(hfm_[A-Za-z0-9_-]{20,}|hms_[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|v1\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,})\b/g;
462
+ var mask = (s) => s.replace(SECRET, (m) => `${m.slice(0, 4)}…`);
463
+ var MAX_FILE = 1024 * 1024;
464
+ var fileReady = false;
465
+ function toFile(line) {
466
+ try {
467
+ const f = path2.join(logDir(), "hypeframe.log");
468
+ if (!fileReady) {
469
+ fileReady = true;
470
+ if (fs4.existsSync(f) && fs4.statSync(f).size > MAX_FILE)
471
+ fs4.renameSync(f, `${f}.1`);
472
+ }
473
+ fs4.appendFileSync(f, `${new Date().toISOString()} ${line}
474
+ `, { mode: 384 });
475
+ } catch {}
476
+ }
477
+ var time = () => new Date().toTimeString().slice(0, 8);
478
+ var paint = { info: color.info, ok: color.ok, warn: color.warn, error: color.error, detail: color.muted };
479
+ var silent = false;
480
+ function write(level, message) {
481
+ const text = mask(message);
482
+ toFile(`${level.toUpperCase().padEnd(5)} ${plain(text)}`);
483
+ if (silent)
484
+ return;
485
+ const out = level === "error" ? process.stderr : process.stdout;
486
+ const body = level === "detail" ? color.muted(text) : level === "error" ? color.error(text) : text;
487
+ out.write(`${color.muted(time())} ${paint[level](icon[level])} ${body}
488
+ `);
489
+ }
490
+ var log = {
491
+ info: (m) => write("info", m),
492
+ ok: (m) => write("ok", m),
493
+ warn: (m) => write("warn", m),
494
+ error: (m) => write("error", m),
495
+ detail: (m) => write("detail", m)
496
+ };
497
+
498
+ // packages/hypeframe/src/cli/commands/start.ts
499
+ import crypto3 from "node:crypto";
500
+ import ffmpegPath from "ffmpeg-static";
501
+
502
+ // packages/protocol/src/index.ts
503
+ var PROTOCOL_VERSION = 1;
504
+ var ALLOWED_KINDS = ["status", "kunci"];
505
+ var CloseCode = {
506
+ BadHello: 4001,
507
+ Replaced: 4002,
508
+ TokenRevoked: 4011,
509
+ ProtocolUnsupported: 4012
510
+ };
511
+ var PAIRING_CODE = /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/;
512
+ var JOB_ID = /^r_[a-f0-9]{16}$/;
513
+ var EngineError = {
514
+ NotReady: "Render di mesin ini belum siap.",
515
+ ChromeStopped: "Chrome berhenti mendadak.",
516
+ Timeout: "Render melebihi batas waktu dan dihentikan.",
517
+ EmptyResult: "Hasil render kosong.",
518
+ NoTransparent: "Klip transparan belum bisa dibuat di mesin ini.",
519
+ Restarted: "Mesin dimulai ulang saat videomu diproses. Coba render lagi.",
520
+ ServiceError: "Galat layanan render.",
521
+ QueueFull: "Antrean render di mesin ini sedang penuh.",
522
+ BadPackage: "Paket berisi berkas yang tidak diizinkan."
523
+ };
524
+
525
+ // packages/hypeframe/src/config/lock.ts
526
+ import fs5 from "node:fs";
527
+ class AlreadyRunning extends Error {
528
+ code = "SUDAH_JALAN";
529
+ }
530
+ var alive = (pid) => {
531
+ try {
532
+ process.kill(pid, 0);
533
+ return true;
534
+ } catch (e) {
535
+ return e.code === "EPERM";
536
+ }
537
+ };
538
+ function runningPid() {
539
+ try {
540
+ const pid = Number(fs5.readFileSync(lockFile(), "utf8"));
541
+ return Number.isInteger(pid) && pid > 0 && pid !== process.pid && alive(pid) ? pid : null;
542
+ } catch {
543
+ return null;
544
+ }
545
+ }
546
+ function singleInstance() {
547
+ const f = lockFile();
548
+ for (let attempt = 0;attempt < 2; attempt++) {
549
+ try {
550
+ const fd = fs5.openSync(f, "wx");
551
+ fs5.writeSync(fd, String(process.pid));
552
+ fs5.closeSync(fd);
553
+ const release = () => {
554
+ try {
555
+ if (fs5.readFileSync(f, "utf8") === String(process.pid))
556
+ fs5.rmSync(f, { force: true });
557
+ } catch {}
558
+ process.off("exit", release);
559
+ };
560
+ process.on("exit", release);
561
+ return { release };
562
+ } catch (e) {
563
+ if (e.code !== "EEXIST")
564
+ throw e;
565
+ const pid = Number(fs5.readFileSync(f, "utf8"));
566
+ if (Number.isInteger(pid) && pid > 0 && alive(pid))
567
+ throw new AlreadyRunning("engine already running");
568
+ fs5.rmSync(f, { force: true });
569
+ }
570
+ }
571
+ throw new AlreadyRunning("engine already running");
572
+ }
573
+
574
+ // packages/hypeframe/src/config/version.ts
575
+ import fs6 from "node:fs";
576
+ function readPkg() {
577
+ for (const rel of ["../package.json", "../../package.json"]) {
578
+ try {
579
+ const p = JSON.parse(fs6.readFileSync(new URL(rel, import.meta.url), "utf8"));
580
+ if (p.name === "hypeframe")
581
+ return p;
582
+ } catch {}
583
+ }
584
+ return { version: "0.0.0" };
585
+ }
586
+ var VERSION = process.env.HF_MESIN_VERSI || readPkg().version;
587
+
588
+ // packages/hypeframe/src/engine/connection.ts
589
+ import { EventEmitter } from "node:events";
590
+ import WebSocket from "ws";
591
+ var SILENCE_MAX_MS = 70000;
592
+
593
+ class Connection extends EventEmitter {
594
+ o;
595
+ url;
596
+ ws = null;
597
+ running = false;
598
+ delay;
599
+ retry;
600
+ silence;
601
+ id = null;
602
+ constructor(o) {
603
+ super();
604
+ this.o = o;
605
+ this.url = `${o.gateway.replace(/^http/, "ws").replace(/\/+$/, "")}/mesin/ws`;
606
+ this.delay = o.initialDelay ?? 1000;
607
+ }
608
+ start() {
609
+ if (this.running)
610
+ return;
611
+ this.running = true;
612
+ this.connect();
613
+ }
614
+ stop(reason) {
615
+ this.running = false;
616
+ clearTimeout(this.retry);
617
+ clearTimeout(this.silence);
618
+ if (this.ws && this.ws.readyState <= 1)
619
+ this.ws.close(1000);
620
+ if (reason)
621
+ this.emit("stopped", reason);
622
+ }
623
+ setInfo(next) {
624
+ this.o.info = { ...this.o.info, ...next };
625
+ }
626
+ news(kind, body = {}) {
627
+ this.send({ ...body, t: "kabar", jenis: kind });
628
+ }
629
+ get connected() {
630
+ return this.ws?.readyState === WebSocket.OPEN && !!this.id;
631
+ }
632
+ send(m) {
633
+ if (this.ws?.readyState === WebSocket.OPEN)
634
+ this.ws.send(JSON.stringify(m));
635
+ }
636
+ watchSilence() {
637
+ clearTimeout(this.silence);
638
+ this.silence = setTimeout(() => this.ws?.terminate(), SILENCE_MAX_MS);
639
+ this.silence.unref?.();
640
+ }
641
+ connect() {
642
+ if (!this.running)
643
+ return;
644
+ const ws = new WebSocket(this.url, { handshakeTimeout: 15000 });
645
+ this.ws = ws;
646
+ ws.on("open", () => {
647
+ this.watchSilence();
648
+ ws.send(JSON.stringify({ t: "halo", token: this.o.token, protokol: PROTOCOL_VERSION, ...this.o.info }));
649
+ });
650
+ ws.on("ping", () => this.watchSilence());
651
+ ws.on("message", async (data) => {
652
+ this.watchSilence();
653
+ let m;
654
+ try {
655
+ m = JSON.parse(String(data));
656
+ } catch {
657
+ return;
658
+ }
659
+ if (m.t === "ok") {
660
+ this.id = String(m.id);
661
+ this.delay = this.o.initialDelay ?? 1000;
662
+ this.emit("connected", { id: m.id });
663
+ } else if (m.t === "perintah") {
664
+ const result = await this.o.handler(m);
665
+ if (ws === this.ws)
666
+ this.send({ t: "balas", ke: m.dari, id: m.id, ...result });
667
+ }
668
+ });
669
+ ws.on("error", () => {
670
+ return;
671
+ });
672
+ ws.on("close", (code) => {
673
+ clearTimeout(this.silence);
674
+ if (ws !== this.ws)
675
+ return;
676
+ this.id = null;
677
+ if (code === CloseCode.TokenRevoked) {
678
+ deleteAccount();
679
+ this.running = false;
680
+ return this.emit("revoked");
681
+ }
682
+ if (code === CloseCode.ProtocolUnsupported)
683
+ return this.stop("protocol");
684
+ if (code === CloseCode.Replaced)
685
+ return this.stop("replaced");
686
+ if (!this.running)
687
+ return;
688
+ this.emit("disconnected", { code });
689
+ this.retry = setTimeout(() => this.connect(), this.delay);
690
+ this.delay = Math.min(this.o.maxDelay ?? 30000, this.delay * 2);
691
+ });
692
+ }
693
+ }
694
+
695
+ // packages/hypeframe/src/engine/handler.ts
696
+ function createHandler(work) {
697
+ return async function handle(c) {
698
+ const kind = String(c?.jenis || "");
699
+ if (!ALLOWED_KINDS.includes(kind))
700
+ return { ok: false, error: "jenis" };
701
+ try {
702
+ return { ok: true, ...await work[kind](c) };
703
+ } catch (e) {
704
+ return { ok: false, error: "galat", pesan: String(e?.message || e).slice(0, 200) };
705
+ }
706
+ };
707
+ }
708
+
709
+ // packages/hypeframe/src/engine/pairing.ts
710
+ var sleep = (ms, signal) => new Promise((ok, fail) => {
711
+ const timer = setTimeout(ok, ms);
712
+ signal?.addEventListener("abort", () => (clearTimeout(timer), fail(new Error("Dibatalkan."))), { once: true });
713
+ });
714
+ function webOrigin(web) {
715
+ try {
716
+ const u = new URL(String(web));
717
+ if (u.protocol !== "https:" && u.protocol !== "http:")
718
+ return null;
719
+ if (u.username || u.password || !/^[A-Za-z0-9.-]+$/.test(u.hostname))
720
+ return null;
721
+ return u.origin;
722
+ } catch {
723
+ return null;
724
+ }
725
+ }
726
+ async function post(gateway, route, body, signal) {
727
+ const r = await fetch(`${gateway}${route}`, {
728
+ method: "POST",
729
+ headers: { "content-type": "application/json" },
730
+ body: JSON.stringify(body),
731
+ signal: AbortSignal.any([AbortSignal.timeout(20000), ...signal ? [signal] : []])
732
+ });
733
+ return { status: r.status, body: await r.json().catch(() => ({})) };
734
+ }
735
+
736
+ class Fatal extends Error {
737
+ }
738
+ async function pair(o) {
739
+ const interval = o.interval ?? 2000;
740
+ const origin = webOrigin(o.web);
741
+ if (!origin)
742
+ throw new Error(t("pair.badWeb"));
743
+ let code = "";
744
+ let secret = "";
745
+ for (;; ) {
746
+ try {
747
+ const r = await post(o.gateway, "/mesin/kode", { nama: o.name, os: o.os, versi: o.version }, o.signal);
748
+ if (r.status === 200 && r.body.kode) {
749
+ if (!PAIRING_CODE.test(String(r.body.kode)) || typeof r.body.rahasia !== "string")
750
+ throw new Fatal(t("pair.badCode"));
751
+ code = String(r.body.kode);
752
+ secret = r.body.rahasia;
753
+ break;
754
+ }
755
+ o.print(r.status === 429 || r.status === 503 ? t("pair.busy") : t("pair.refused", { status: Number(r.status) }));
756
+ } catch (e) {
757
+ if (e instanceof Fatal || o.signal?.aborted)
758
+ throw e;
759
+ o.print(t("pair.unreachable"));
760
+ }
761
+ await sleep(Math.max(interval, 5000), o.signal);
762
+ }
763
+ const link = `${origin}/sambung?kode=${code}`;
764
+ o.print(t("pair.open", { link: color.underline(color.brand(link)), code: color.bold(code) }));
765
+ try {
766
+ o.openBrowser(link);
767
+ } catch {}
768
+ for (;; ) {
769
+ await sleep(interval, o.signal);
770
+ let r;
771
+ try {
772
+ r = await post(o.gateway, "/mesin/token", { rahasia: secret }, o.signal);
773
+ } catch {
774
+ if (o.signal?.aborted)
775
+ throw new Error("Dibatalkan.");
776
+ continue;
777
+ }
778
+ if (r.status === 200 && typeof r.body.token === "string")
779
+ return { token: r.body.token, id: String(r.body.id || ""), email: String(r.body.email || "") };
780
+ if (r.status === 410)
781
+ throw new Error(t("pair.expired"));
782
+ }
783
+ }
784
+
785
+ // packages/hypeframe/src/render/chrome.ts
786
+ import { execFileSync } from "node:child_process";
787
+ import fs7 from "node:fs";
788
+ import http from "node:http";
789
+ import path3 from "node:path";
790
+ import { Browser, detectBrowserPlatform, getInstalledBrowsers, install, resolveBuildId } from "@puppeteer/browsers";
791
+ import puppeteer from "puppeteer-core";
792
+ function candidates() {
793
+ const e = process.env;
794
+ if (process.platform === "win32") {
795
+ return [e.PROGRAMFILES, e["PROGRAMFILES(X86)"], e.LOCALAPPDATA].filter((d) => !!d).flatMap((d) => [path3.join(d, "Google", "Chrome", "Application", "chrome.exe"), path3.join(d, "Microsoft", "Edge", "Application", "msedge.exe")]);
796
+ }
797
+ if (process.platform === "darwin") {
798
+ return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];
799
+ }
800
+ const found = [];
801
+ for (const n of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]) {
802
+ try {
803
+ const p = execFileSync("which", [n], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
804
+ if (p)
805
+ found.push(p);
806
+ } catch {}
807
+ }
808
+ return found;
809
+ }
810
+ function findChrome() {
811
+ const forced = process.env.HYPEFRAME_CHROME;
812
+ if (forced)
813
+ return fs7.existsSync(forced) ? forced : null;
814
+ return candidates().find((p) => fs7.existsSync(p)) || null;
815
+ }
816
+ async function cachedChrome(cacheDir) {
817
+ try {
818
+ const all = await getInstalledBrowsers({ cacheDir: path3.join(cacheDir, "chrome") });
819
+ return all.find((b) => b.browser === Browser.CHROME && fs7.existsSync(b.executablePath))?.executablePath ?? null;
820
+ } catch {
821
+ return null;
822
+ }
823
+ }
824
+ async function prepareChrome(cacheDir, progress = () => {
825
+ return;
826
+ }) {
827
+ const found = findChrome();
828
+ if (found)
829
+ return found;
830
+ const platform = detectBrowserPlatform();
831
+ if (!platform)
832
+ throw new Error("Sistem ini belum didukung untuk render (Chrome tidak tersedia).");
833
+ const dir = path3.join(cacheDir, "chrome");
834
+ const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
835
+ progress(0, `Chrome ${buildId}`);
836
+ const r = await install({
837
+ browser: Browser.CHROME,
838
+ buildId,
839
+ cacheDir: dir,
840
+ platform,
841
+ downloadProgressCallback: (a, b) => void (b > 0 && progress(Math.floor(a / b * 100), `Chrome ${buildId}`))
842
+ });
843
+ return r.executablePath;
844
+ }
845
+ var softwareGpuArgs = ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"];
846
+ var TRY_ENCODER = `async (c) => {
847
+ const s = await VideoEncoder.isConfigSupported(c).catch(() => ({ supported: false }));
848
+ if (s.supported !== true) return false;
849
+ return await new Promise((ok) => {
850
+ const e = new VideoEncoder({ output: () => ok(true), error: () => ok(false) });
851
+ e.configure(c);
852
+ const k = new OffscreenCanvas(c.width, c.height);
853
+ k.getContext('2d').fillRect(0, 0, 8, 8);
854
+ const f = new VideoFrame(k, { timestamp: 0 });
855
+ e.encode(f, { keyFrame: true });
856
+ f.close();
857
+ e.flush().catch(() => ok(false));
858
+ setTimeout(() => ok(false), 10000);
859
+ });
860
+ }`;
861
+ async function checkChrome(chrome, { gpu = false } = {}) {
862
+ const srv = http.createServer((_q, r) => (r.writeHead(200, { "content-type": "text/html" }), r.end("<!doctype html><title>check</title>")));
863
+ await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));
864
+ const b = await puppeteer.launch({ executablePath: chrome, headless: true, protocolTimeout: 60000, args: ["--no-first-run", "--disable-extensions", ...gpu ? [] : softwareGpuArgs] });
865
+ try {
866
+ const p = await b.newPage();
867
+ await p.goto(`http://127.0.0.1:${srv.address().port}/`);
868
+ const attempt = (cfg) => p.evaluate(`(${TRY_ENCODER})(${JSON.stringify(cfg)})`).then((r) => r === true).catch(() => false);
869
+ return {
870
+ version: (await b.version()).replace(/^[^/]*\//, ""),
871
+ avc: await attempt({ codec: "avc1.42001f", width: 320, height: 568, bitrate: 1e6, framerate: 30 }),
872
+ transparent: await attempt({ codec: "vp09.00.10.08", width: 320, height: 568, bitrate: 1e6, framerate: 30, alpha: "keep" })
873
+ };
874
+ } finally {
875
+ await b.close().catch(() => {
876
+ return;
877
+ });
878
+ srv.close();
879
+ }
880
+ }
881
+
882
+ // packages/hypeframe/src/render/job.ts
883
+ import { spawn } from "node:child_process";
884
+ import crypto from "node:crypto";
885
+ import fs8 from "node:fs";
886
+ import fsp from "node:fs/promises";
887
+ import path4 from "node:path";
888
+ import puppeteer2 from "puppeteer-core";
889
+ var LIMIT_SECONDS = 1800;
890
+ function run(cmd, args, limitSeconds = 600) {
891
+ return new Promise((ok, fail) => {
892
+ const p = spawn(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
893
+ let err = "";
894
+ p.stderr.on("data", (d) => err = (err + d).slice(-2000));
895
+ const timer = setTimeout(() => p.kill("SIGKILL"), limitSeconds * 1000);
896
+ p.on("close", (code) => (clearTimeout(timer), code === 0 ? ok() : fail(new Error(`ffmpeg keluar ${code}: ${err.split(`
897
+ `).slice(-3).join(" ")}`))));
898
+ p.on("error", (e) => (clearTimeout(timer), fail(e)));
899
+ });
900
+ }
901
+ function saveBody(req, to, max) {
902
+ return new Promise((ok, fail) => {
903
+ let n = 0;
904
+ const out = fs8.createWriteStream(to);
905
+ req.on("data", (d) => {
906
+ n += d.length;
907
+ if (n > max)
908
+ req.destroy(), out.destroy(), fail(new Error("terlalu besar"));
909
+ });
910
+ req.pipe(out);
911
+ out.on("finish", () => ok(n));
912
+ out.on("error", fail);
913
+ });
914
+ }
915
+ async function readJson(req) {
916
+ let s = "";
917
+ for await (const d of req)
918
+ if ((s += d).length > 65536)
919
+ break;
920
+ try {
921
+ return JSON.parse(s || "{}");
922
+ } catch {
923
+ return {};
924
+ }
925
+ }
926
+ function createJobRunner(o) {
927
+ const { chrome, ffmpeg, page, gpu = false, transparent = true, note = () => {
928
+ return;
929
+ } } = o;
930
+ let port = 0;
931
+ const running = new Map;
932
+ const renderer = async (task, { progress, signal }) => {
933
+ if (task.kind === "klip" && task.transparent && !transparent)
934
+ throw new Error(EngineError.NoTransparent);
935
+ const key = crypto.randomBytes(16).toString("hex");
936
+ let finish;
937
+ const finished = new Promise((ok) => finish = ok);
938
+ running.set(task.job, { key, task, progress, finish });
939
+ const clip = task.kind === "klip";
940
+ const timer = setTimeout(() => finish({ error: EngineError.Timeout }), LIMIT_SECONDS * 1000);
941
+ const abort = () => finish({ error: "Dibatalkan." });
942
+ signal?.addEventListener("abort", abort);
943
+ let browser;
944
+ try {
945
+ progress(0, "Menyiapkan");
946
+ const profile = path4.join(task.dir, "profil");
947
+ await fsp.mkdir(path4.join(profile, "Default"), { recursive: true });
948
+ await fsp.writeFile(path4.join(profile, "Default", "Preferences"), JSON.stringify({ webkit: { webprefs: { fonts: { standard: { Zyyy: "Roboto" }, sansserif: { Zyyy: "Roboto" }, serif: { Zyyy: "Noto Serif" } } } } }));
949
+ browser = await puppeteer2.launch({
950
+ executablePath: chrome,
951
+ headless: true,
952
+ userDataDir: profile,
953
+ args: [
954
+ "--no-first-run",
955
+ "--mute-audio",
956
+ "--disable-extensions",
957
+ "--disable-background-networking",
958
+ "--disable-sync",
959
+ "--metrics-recording-only",
960
+ "--autoplay-policy=no-user-gesture-required",
961
+ "--disable-dev-shm-usage",
962
+ ...gpu ? [] : softwareGpuArgs,
963
+ "--enable-unsafe-webgpu",
964
+ ...gpu ? [] : ["--use-webgpu-adapter=swiftshader"],
965
+ "--enable-features=Vulkan",
966
+ "--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1"
967
+ ]
968
+ });
969
+ browser.on("disconnected", () => finish({ error: EngineError.ChromeStopped }));
970
+ const tab = await browser.newPage();
971
+ tab.on("pageerror", (e) => note(`page error ${task.job}: ${String(e?.message || e).slice(0, 300)}`));
972
+ tab.on("console", (m) => void (m.type() === "error" && note(`console ${task.job}: ${m.text().slice(0, 300)}`)));
973
+ await tab.goto(`http://127.0.0.1:${port}/render/render.html?job=${task.job}&kunci=${key}${clip ? "&jenis=klip" : ""}`, { waitUntil: "load", timeout: 120000 });
974
+ const result = await finished;
975
+ if (result.error)
976
+ throw new Error(result.error);
977
+ progress(99, clip ? "Menyelesaikan klip" : "Menyelesaikan video");
978
+ const raw = path4.join(task.dir, "mentah.mp4");
979
+ const webm = clip && task.transparent;
980
+ const file = path4.join(task.dir, webm ? "hasil.webm" : "hasil.mp4");
981
+ if (clip)
982
+ await fsp.rename(raw, file);
983
+ else
984
+ await run(ffmpeg, ["-y", "-v", "error", "-i", raw, "-map", "0", "-c:v", "copy", ...result.audio === "opus" ? ["-c:a", "aac", "-b:a", "192k"] : ["-c:a", "copy"], "-movflags", "+faststart", file]);
985
+ return { file, type: webm ? "video/webm" : "video/mp4" };
986
+ } finally {
987
+ clearTimeout(timer);
988
+ signal?.removeEventListener("abort", abort);
989
+ running.delete(task.job);
990
+ await browser?.close().catch(() => {
991
+ return;
992
+ });
993
+ }
994
+ };
995
+ const LOCAL = new RegExp(`^/lokal/(${JOB_ID.source.slice(1, -1)})/(proyek\\.json|klip\\.json|aset/([\\w-]+)|kemajuan|hasil|galat)$`);
996
+ const route = async (req, res, url) => {
997
+ if (await page.route(req, res, url))
998
+ return true;
999
+ const m = url.pathname.match(LOCAL);
1000
+ if (!m)
1001
+ return false;
1002
+ const r = running.get(m[1]);
1003
+ if (!r || url.searchParams.get("kunci") !== r.key)
1004
+ return res.writeHead(403), res.end(), true;
1005
+ const pkg = r.task.packageDir;
1006
+ if (m[2] === "proyek.json" || m[2] === "klip.json" || m[3]) {
1007
+ const f = m[3] ? path4.join(pkg, "aset", m[3]) : path4.join(pkg, m[2]);
1008
+ if (!fs8.existsSync(f))
1009
+ return res.writeHead(404), res.end(), true;
1010
+ res.writeHead(200, { "content-type": m[3] ? "application/octet-stream" : "application/json", "content-length": (await fsp.stat(f)).size });
1011
+ fs8.createReadStream(f).pipe(res);
1012
+ return true;
1013
+ }
1014
+ if (m[2] === "kemajuan") {
1015
+ const b = await readJson(req);
1016
+ const stage = typeof b.tahap === "string" ? b.tahap : "";
1017
+ if (Number(b.total) > 0)
1018
+ r.progress(Math.min(98, Math.floor(Number(b.selesai) / Number(b.total) * 98)), stage);
1019
+ else if (stage)
1020
+ r.progress(r.task.persen ?? 0, stage);
1021
+ return res.writeHead(204), res.end(), true;
1022
+ }
1023
+ if (m[2] === "galat") {
1024
+ const b = await readJson(req);
1025
+ r.finish({ error: String(b.pesan || "Render gagal.").slice(0, 300) });
1026
+ return res.writeHead(204), res.end(), true;
1027
+ }
1028
+ await saveBody(req, path4.join(r.task.dir, "mentah.mp4"), 8 * 1073741824);
1029
+ r.finish({ audio: String(req.headers["x-kodek-audio"] || "") });
1030
+ res.writeHead(204);
1031
+ res.end();
1032
+ return true;
1033
+ };
1034
+ return { renderer, route, setPort: (p) => void (port = p) };
1035
+ }
1036
+
1037
+ // packages/hypeframe/src/render/page.ts
1038
+ import fs9 from "node:fs";
1039
+ import fsp2 from "node:fs/promises";
1040
+ import path5 from "node:path";
1041
+ var TYPES = {
1042
+ ".html": "text/html; charset=utf-8",
1043
+ ".js": "text/javascript",
1044
+ ".mjs": "text/javascript",
1045
+ ".css": "text/css",
1046
+ ".woff2": "font/woff2",
1047
+ ".woff": "font/woff",
1048
+ ".ttf": "font/ttf",
1049
+ ".svg": "image/svg+xml",
1050
+ ".png": "image/png",
1051
+ ".webp": "image/webp",
1052
+ ".jpg": "image/jpeg",
1053
+ ".json": "application/json",
1054
+ ".wasm": "application/wasm",
1055
+ ".txt": "text/plain; charset=utf-8"
1056
+ };
1057
+ var SAFE_PATH = /^[\w@.+-]+(?:\/[\w@.+-]+)*$/;
1058
+ var VERSION_ID = /^[0-9a-f]{12}$/;
1059
+ function createPage({ web, cacheDir }) {
1060
+ const base = `${String(web || "").replace(/\/+$/, "")}/render/`;
1061
+ const root = path5.join(cacheDir, "halaman");
1062
+ let version = null;
1063
+ const versionDir = () => path5.join(root, version);
1064
+ const pending = new Map;
1065
+ async function download(rel) {
1066
+ const target = path5.join(versionDir(), rel);
1067
+ if (fs9.existsSync(target))
1068
+ return target;
1069
+ if (!pending.has(rel)) {
1070
+ pending.set(rel, (async () => {
1071
+ const r = await fetch(base + rel.split("/").map(encodeURIComponent).join("/"));
1072
+ if (!r.ok)
1073
+ throw Object.assign(new Error(`halaman ${rel}: ${r.status}`), { status: r.status });
1074
+ const body = Buffer.from(await r.arrayBuffer());
1075
+ await fsp2.mkdir(path5.dirname(target), { recursive: true });
1076
+ await fsp2.writeFile(`${target}.tmp`, body);
1077
+ await fsp2.rename(`${target}.tmp`, target);
1078
+ return target;
1079
+ })().finally(() => pending.delete(rel)));
1080
+ }
1081
+ return pending.get(rel);
1082
+ }
1083
+ async function prepare() {
1084
+ if (!web)
1085
+ throw new Error("Alamat HypeFrame Web belum diatur (--web atau HYPEFRAME_WEB_URL).");
1086
+ const r = await fetch(`${base}versi.json`, { cache: "no-store" });
1087
+ if (!r.ok)
1088
+ throw new Error(`Halaman render tidak bisa diambil dari web (${r.status}).`);
1089
+ const v = await r.json();
1090
+ if (!VERSION_ID.test(String(v.versi)) || !Array.isArray(v.utama))
1091
+ throw new Error("versi.json halaman render tidak sah.");
1092
+ const old = version;
1093
+ version = String(v.versi);
1094
+ for (const f of v.utama)
1095
+ if (typeof f === "string" && SAFE_PATH.test(f))
1096
+ await download(f);
1097
+ if (old !== version) {
1098
+ const all = (await fsp2.readdir(root).catch(() => [])).filter((d) => VERSION_ID.test(d));
1099
+ const dated = await Promise.all(all.map(async (d) => ({ d, t: (await fsp2.stat(path5.join(root, d))).mtimeMs })));
1100
+ for (const { d } of dated.sort((a, b) => b.t - a.t).slice(2))
1101
+ if (d !== version)
1102
+ await fsp2.rm(path5.join(root, d), { recursive: true, force: true });
1103
+ }
1104
+ return { version };
1105
+ }
1106
+ async function route(_req, res, url) {
1107
+ if (!url.pathname.startsWith("/render/"))
1108
+ return false;
1109
+ let rel = "";
1110
+ try {
1111
+ rel = decodeURIComponent(url.pathname.slice("/render/".length));
1112
+ } catch {
1113
+ rel = "";
1114
+ }
1115
+ if (!version || !SAFE_PATH.test(rel) || rel.includes(".."))
1116
+ return res.writeHead(404), res.end(), true;
1117
+ try {
1118
+ const f = await download(rel);
1119
+ res.writeHead(200, { "content-type": TYPES[path5.extname(f)] || "application/octet-stream", "cache-control": "no-store" });
1120
+ fs9.createReadStream(f).pipe(res);
1121
+ } catch (e) {
1122
+ res.writeHead(e.status === 404 ? 404 : 502);
1123
+ res.end();
1124
+ }
1125
+ return true;
1126
+ }
1127
+ return {
1128
+ prepare,
1129
+ route,
1130
+ get version() {
1131
+ return version;
1132
+ }
1133
+ };
1134
+ }
1135
+
1136
+ // packages/hypeframe/src/render/service.ts
1137
+ import crypto2 from "node:crypto";
1138
+ import fs10 from "node:fs";
1139
+ import fsp3 from "node:fs/promises";
1140
+ import http2 from "node:http";
1141
+ import path6 from "node:path";
1142
+ import yauzl from "yauzl";
1143
+ var ACTIVE = new Set(["unggah", "antre", "jalan"]);
1144
+ var safeEqual = (a, b) => a.length === b.length && crypto2.timingSafeEqual(Buffer.from(a), Buffer.from(b));
1145
+ var BAD_ENTRY = /relative path|absolute path|invalid characters/i;
1146
+ function listZip(f) {
1147
+ return new Promise((ok, fail) => {
1148
+ const refuse = (e) => fail(BAD_ENTRY.test(e.message) ? new Error(EngineError.BadPackage) : e);
1149
+ yauzl.open(f, { lazyEntries: true }, (e, zip) => {
1150
+ if (e || !zip)
1151
+ return refuse(e ?? new Error("zip"));
1152
+ const entries = [];
1153
+ zip.on("entry", (en) => (entries.push({ name: en.fileName, size: en.uncompressedSize }), zip.readEntry()));
1154
+ zip.on("end", () => ok(entries));
1155
+ zip.on("error", refuse);
1156
+ zip.readEntry();
1157
+ });
1158
+ });
1159
+ }
1160
+ function extractZip(f, to) {
1161
+ return new Promise((ok, fail) => {
1162
+ yauzl.open(f, { lazyEntries: true }, (e, zip) => {
1163
+ if (e || !zip)
1164
+ return fail(e ?? new Error("zip"));
1165
+ zip.on("entry", (en) => {
1166
+ if (en.fileName.endsWith("/"))
1167
+ return zip.readEntry();
1168
+ const target = path6.join(to, en.fileName);
1169
+ if (!target.startsWith(to + path6.sep))
1170
+ return fail(new Error(EngineError.BadPackage));
1171
+ fs10.mkdirSync(path6.dirname(target), { recursive: true });
1172
+ zip.openReadStream(en, (e2, s) => {
1173
+ if (e2 || !s)
1174
+ return fail(e2 ?? new Error("zip"));
1175
+ const out = fs10.createWriteStream(target);
1176
+ s.pipe(out);
1177
+ out.on("finish", () => zip.readEntry());
1178
+ out.on("error", fail);
1179
+ });
1180
+ });
1181
+ zip.on("end", () => ok());
1182
+ zip.on("error", fail);
1183
+ zip.readEntry();
1184
+ });
1185
+ });
1186
+ }
1187
+ function saveBody2(req, to, max) {
1188
+ return new Promise((ok, fail) => {
1189
+ let n = 0;
1190
+ const out = fs10.createWriteStream(to);
1191
+ req.on("data", (d) => {
1192
+ n += d.length;
1193
+ if (n > max) {
1194
+ req.destroy();
1195
+ out.destroy();
1196
+ fs10.rm(to, { force: true }, () => fail(new Error("terlalu besar")));
1197
+ }
1198
+ });
1199
+ req.pipe(out);
1200
+ out.on("finish", () => ok(n));
1201
+ out.on("error", fail);
1202
+ req.on("error", fail);
1203
+ });
1204
+ }
1205
+ function readJson2(req, max = 64 * 1024) {
1206
+ return new Promise((ok, fail) => {
1207
+ let s = "";
1208
+ req.on("data", (d) => (s += d, s.length > max && (req.destroy(), fail(new Error("terlalu besar")))));
1209
+ req.on("end", () => {
1210
+ try {
1211
+ ok(s ? JSON.parse(s) : {});
1212
+ } catch (e) {
1213
+ fail(e);
1214
+ }
1215
+ });
1216
+ req.on("error", fail);
1217
+ });
1218
+ }
1219
+ async function createRenderService(o) {
1220
+ const { folder, key, renderer, partMb = 8, maxQueue = 30, maxUnzippedMb = 3000, keepHours = 24, extraRoute = null, onJob = () => {
1221
+ return;
1222
+ } } = o;
1223
+ const origins = new Set([].concat(o.origin || []));
1224
+ const sign = (kind, body) => crypto2.createHmac("sha256", key).update(`${kind}.${body}`).digest("base64url");
1225
+ const dir = (job) => path6.join(folder, job);
1226
+ await fsp3.mkdir(folder, { recursive: true });
1227
+ function readTicket(req) {
1228
+ const tk = String(req.headers.authorization || "").replace(/^Bearer\s+/i, "");
1229
+ const [v, body, sig] = tk.split(".");
1230
+ if (v !== "v1" || !body || !sig || !safeEqual(sig, sign("tiket", body)))
1231
+ return null;
1232
+ let j;
1233
+ try {
1234
+ j = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
1235
+ } catch {
1236
+ return null;
1237
+ }
1238
+ if (!JOB_ID.test(j.job || "") || !(Number(j.exp) > Date.now()))
1239
+ return null;
1240
+ if (j.jenis !== "video" && j.jenis !== "klip")
1241
+ return null;
1242
+ return j;
1243
+ }
1244
+ const jobs = new Map;
1245
+ const queue = [];
1246
+ let current = null;
1247
+ const persist = (t) => fsp3.writeFile(path6.join(dir(t.job), "status.json"), JSON.stringify(t)).catch(() => {
1248
+ return;
1249
+ });
1250
+ const update = (t, patch) => (Object.assign(t, patch, { diperbarui: Date.now() }), void persist(t));
1251
+ const summary = (t) => ({
1252
+ job: t.job,
1253
+ jenis: t.tiket.jenis,
1254
+ status: t.status,
1255
+ antrean: t.status === "antre" ? queue.indexOf(t.job) + 1 || null : null,
1256
+ persen: t.persen ?? 0,
1257
+ tahap: t.tahap || "",
1258
+ galat: t.galat || null,
1259
+ ukuran: t.hasilUkuran || null,
1260
+ menit: 0,
1261
+ kedaluwarsa: t.status === "selesai" ? t.selesaiPada + keepHours * 3600000 : null,
1262
+ kwitansi: null
1263
+ });
1264
+ async function clearFiles(t, all = false) {
1265
+ for (const n of all ? ["."] : ["paket", "paket.zip", "profil", "mentah.mp4", "mentah.webm"])
1266
+ await fsp3.rm(path6.join(dir(t.job), n), { recursive: true, force: true }).catch(() => {
1267
+ return;
1268
+ });
1269
+ if (!all) {
1270
+ for (const f of await fsp3.readdir(dir(t.job)).catch(() => []))
1271
+ if (/^p\d+$/.test(f))
1272
+ await fsp3.rm(path6.join(dir(t.job), f), { force: true });
1273
+ }
1274
+ }
1275
+ async function openPackage(t) {
1276
+ const d = dir(t.job);
1277
+ const main = t.tiket.jenis === "klip" ? "klip.json" : "proyek.json";
1278
+ const entries = await listZip(path6.join(d, "paket.zip"));
1279
+ const names = entries.map((x) => x.name).filter((n) => !n.endsWith("/"));
1280
+ if (names.some((n) => n.startsWith("/") || n.includes("..") || n.includes("\\") || n !== main && !/^aset\/[\w-]+$/.test(n)))
1281
+ throw new Error(EngineError.BadPackage);
1282
+ if (!names.includes(main))
1283
+ throw new Error(`Paket tidak berisi ${main}.`);
1284
+ if (entries.reduce((a, x) => a + x.size, 0) > maxUnzippedMb * 1048576)
1285
+ throw new Error("Isi paket terlalu besar.");
1286
+ await extractZip(path6.join(d, "paket.zip"), path6.join(d, "paket"));
1287
+ await fsp3.rm(path6.join(d, "paket.zip"), { force: true });
1288
+ const j = JSON.parse(await fsp3.readFile(path6.join(d, "paket", main), "utf8"));
1289
+ const has = (id) => /^[\w-]+$/.test(id) && fs10.existsSync(path6.join(d, "paket", "aset", id));
1290
+ if (main === "klip.json") {
1291
+ const k = j.klip || {};
1292
+ const seconds = Number(k.durationInFrames) / Number(k.fps);
1293
+ if (!(seconds > 0) || seconds > t.tiket.detik + 0.5)
1294
+ throw new Error("Panjang klip tidak sama dengan tiket.");
1295
+ if (Number(k.width) !== t.tiket.w || Number(k.height) !== t.tiket.h || Number(k.fps) !== t.tiket.fps)
1296
+ throw new Error("Ukuran atau fps klip tidak sama dengan tiket.");
1297
+ if (!["remotion", "html", "gsap", "halaman"].includes(k.engine))
1298
+ throw new Error("Jenis kode klip tidak dikenal.");
1299
+ for (const id of Array.isArray(k.assetIds) ? k.assetIds : [])
1300
+ if (!has(id))
1301
+ throw new Error(`Bahan ${String(id).slice(0, 60)} tidak ada di paket.`);
1302
+ t.transparan = !!k.transparent;
1303
+ return;
1304
+ }
1305
+ const p = j.proyek || {};
1306
+ const s = j.setelan || {};
1307
+ const seconds = Number(p.duration) / Number(p.fps);
1308
+ if (!(seconds > 0) || seconds > t.tiket.detik + 0.5)
1309
+ throw new Error("Panjang video tidak sama dengan tiket.");
1310
+ if (Number(s.width) !== t.tiket.w || Number(s.height) !== t.tiket.h || Number(s.fps) !== t.tiket.fps)
1311
+ throw new Error("Ukuran atau fps video tidak sama dengan tiket.");
1312
+ for (const id of Object.keys(p.assets || {}))
1313
+ if (!has(id))
1314
+ throw new Error(`Bahan ${String(p.assets[id]?.name || id).slice(0, 60)} tidak ada di paket.`);
1315
+ }
1316
+ function next() {
1317
+ if (current)
1318
+ return;
1319
+ const job = queue.shift();
1320
+ if (!job)
1321
+ return;
1322
+ const t = jobs.get(job);
1323
+ if (!t || t.status !== "antre")
1324
+ return next();
1325
+ work(t);
1326
+ }
1327
+ async function work(t) {
1328
+ const cancel = new AbortController;
1329
+ current = { job: t.job, cancel };
1330
+ update(t, { status: "jalan", mulaiPada: Date.now(), persen: 0, tahap: "Menyiapkan" });
1331
+ onJob("started", t);
1332
+ try {
1333
+ const task = {
1334
+ job: t.job,
1335
+ kind: t.tiket.jenis,
1336
+ dir: dir(t.job),
1337
+ packageDir: path6.join(dir(t.job), "paket"),
1338
+ transparent: !!t.transparan,
1339
+ persen: t.persen,
1340
+ width: t.tiket.w,
1341
+ height: t.tiket.h,
1342
+ fps: t.tiket.fps,
1343
+ seconds: t.tiket.detik
1344
+ };
1345
+ const progress = (percent, stage) => {
1346
+ if (t.status !== "jalan")
1347
+ return;
1348
+ task.persen = Math.min(99, Math.max(0, Math.round(percent)));
1349
+ update(t, { persen: task.persen, ...stage ? { tahap: String(stage).slice(0, 80) } : {} });
1350
+ };
1351
+ const h = await renderer(task, { progress, signal: cancel.signal });
1352
+ if (cancel.signal.aborted)
1353
+ throw new Error("Dibatalkan.");
1354
+ const size = (await fsp3.stat(h.file)).size;
1355
+ if (size < 200)
1356
+ throw new Error(EngineError.EmptyResult);
1357
+ update(t, { status: "selesai", persen: 100, tahap: "", selesaiPada: Date.now(), hasilUkuran: size, hasilBerkas: path6.basename(h.file), hasilJenis: h.type });
1358
+ onJob("done", t);
1359
+ } catch (e) {
1360
+ if (t.status !== "batal") {
1361
+ update(t, { status: "gagal", galat: String(e?.message || e).slice(0, 300), tahap: "" });
1362
+ onJob("failed", t);
1363
+ }
1364
+ } finally {
1365
+ current = null;
1366
+ await clearFiles(t);
1367
+ next();
1368
+ }
1369
+ }
1370
+ function cors(req) {
1371
+ const origin = req.headers.origin;
1372
+ if (!origin || !origins.has(origin))
1373
+ return {};
1374
+ return {
1375
+ "access-control-allow-origin": origin,
1376
+ vary: "Origin",
1377
+ "access-control-allow-headers": "authorization, content-type, range, x-sha256",
1378
+ "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
1379
+ "access-control-expose-headers": "content-length, content-range, content-type",
1380
+ "access-control-max-age": "600",
1381
+ ...req.headers["access-control-request-private-network"] === "true" ? { "access-control-allow-private-network": "true" } : {}
1382
+ };
1383
+ }
1384
+ const json = (req, res, code, body) => (res.writeHead(code, { ...cors(req), "content-type": "application/json", "cache-control": "no-store" }), res.end(JSON.stringify(body)));
1385
+ async function sendFile(req, res, f, type, name) {
1386
+ const st = await fsp3.stat(f);
1387
+ const range = /^bytes=(\d+)-(\d*)$/.exec(String(req.headers.range || ""));
1388
+ const h = { ...cors(req), "content-type": type, "accept-ranges": "bytes", "cache-control": "no-store", "content-disposition": `attachment; filename="${name}"` };
1389
+ if (range) {
1390
+ const a = Number(range[1]);
1391
+ const z = range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
1392
+ if (a > z)
1393
+ return res.writeHead(416, { ...h, "content-range": `bytes */${st.size}` }), res.end();
1394
+ res.writeHead(206, { ...h, "content-length": z - a + 1, "content-range": `bytes ${a}-${z}/${st.size}` });
1395
+ return void fs10.createReadStream(f, { start: a, end: z }).pipe(res);
1396
+ }
1397
+ res.writeHead(200, { ...h, "content-length": st.size });
1398
+ fs10.createReadStream(f).pipe(res);
1399
+ }
1400
+ const ROUTE = /^\/tugas(?:\/(r_[a-f0-9]{16})(\/potongan\/(\d{1,4})|\/mulai|\/hasil)?)?$/;
1401
+ const server = http2.createServer(async (req, res) => {
1402
+ try {
1403
+ if (req.method === "OPTIONS")
1404
+ return res.writeHead(204, cors(req)), res.end();
1405
+ const url = new URL(req.url || "/", "http://x");
1406
+ if (extraRoute && await extraRoute(req, res, url))
1407
+ return;
1408
+ if (url.pathname === "/sehat")
1409
+ return json(req, res, 200, { ok: true, antrean: queue.length, berjalan: current ? 1 : 0 });
1410
+ const m = url.pathname.match(ROUTE);
1411
+ if (!m)
1412
+ return json(req, res, 404, { galat: "tidak ada" });
1413
+ const ticket = readTicket(req);
1414
+ if (!ticket)
1415
+ return json(req, res, 401, { galat: "Tiket render tidak sah atau kedaluwarsa." });
1416
+ if (m[1] && m[1] !== ticket.job)
1417
+ return json(req, res, 403, { galat: "Tiket bukan untuk tugas ini." });
1418
+ const job = ticket.job;
1419
+ let t = jobs.get(job);
1420
+ if (!m[1] && req.method === "POST") {
1421
+ if (t)
1422
+ return json(req, res, 200, summary(t));
1423
+ if (queue.length >= maxQueue)
1424
+ return json(req, res, 503, { galat: EngineError.QueueFull });
1425
+ await fsp3.mkdir(dir(job), { recursive: true });
1426
+ t = { job, tiket: ticket, status: "unggah", dibuat: Date.now(), diperbarui: Date.now(), terunggah: 0 };
1427
+ jobs.set(job, t);
1428
+ persist(t);
1429
+ return json(req, res, 201, { ...summary(t), potonganMb: partMb });
1430
+ }
1431
+ if (!t)
1432
+ return json(req, res, 404, { galat: "Tugas render tidak ditemukan (mungkin sudah dihapus)." });
1433
+ if (m[2]?.startsWith("/potongan") && req.method === "PUT") {
1434
+ if (t.status !== "unggah")
1435
+ return json(req, res, 409, { galat: "Unggahan sudah ditutup." });
1436
+ const n = Number(m[3]);
1437
+ const f = path6.join(dir(job), `p${n}`);
1438
+ const before = fs10.existsSync(f) ? (await fsp3.stat(f)).size : 0;
1439
+ const room = Number(ticket.maksMb) * 1048576 - (t.terunggah - before);
1440
+ const size = await saveBody2(req, f, Math.min(partMb * 1048576 + 1024, room));
1441
+ const expected = String(req.headers["x-sha256"] || "").toLowerCase();
1442
+ if (expected) {
1443
+ const digest = crypto2.createHash("sha256").update(await fsp3.readFile(f)).digest("hex");
1444
+ if (digest !== expected) {
1445
+ await fsp3.rm(f, { force: true });
1446
+ update(t, { terunggah: t.terunggah - before });
1447
+ return json(req, res, 400, { galat: "Potongan rusak di jalan. Kirim ulang." });
1448
+ }
1449
+ }
1450
+ update(t, { terunggah: t.terunggah - before + size });
1451
+ return json(req, res, 200, { ok: true, n, ukuran: size });
1452
+ }
1453
+ if (m[2] === "/mulai" && req.method === "POST") {
1454
+ if (t.status !== "unggah")
1455
+ return json(req, res, 200, summary(t));
1456
+ const b = await readJson2(req);
1457
+ const count = Number(b.jumlah);
1458
+ if (!(count > 0 && count < 1e4))
1459
+ return json(req, res, 400, { galat: "Jumlah potongan tidak valid." });
1460
+ const zip = path6.join(dir(job), "paket.zip");
1461
+ const out = fs10.createWriteStream(zip);
1462
+ const hash = crypto2.createHash("sha256");
1463
+ let total = 0;
1464
+ for (let i = 0;i < count; i++) {
1465
+ const f = path6.join(dir(job), `p${i}`);
1466
+ if (!fs10.existsSync(f))
1467
+ return out.destroy(), json(req, res, 400, { galat: `Potongan ${i + 1} belum terunggah.` });
1468
+ const part = await fsp3.readFile(f);
1469
+ hash.update(part);
1470
+ total += part.length;
1471
+ await new Promise((ok) => out.write(part) ? ok() : out.once("drain", ok));
1472
+ await fsp3.rm(f, { force: true });
1473
+ }
1474
+ await new Promise((ok) => out.end(ok));
1475
+ const digest = hash.digest("hex");
1476
+ if (total !== Number(b.ukuran) || b.sha256 && digest !== String(b.sha256).toLowerCase()) {
1477
+ await fsp3.rm(zip, { force: true });
1478
+ update(t, { terunggah: 0 });
1479
+ return json(req, res, 400, { galat: "Unggahan rusak di jalan. Coba render lagi." });
1480
+ }
1481
+ try {
1482
+ await openPackage(t);
1483
+ } catch (e) {
1484
+ update(t, { status: "gagal", galat: String(e.message || e).slice(0, 300) });
1485
+ onJob("failed", t);
1486
+ await clearFiles(t);
1487
+ return json(req, res, 200, summary(t));
1488
+ }
1489
+ update(t, { status: "antre", antrePada: Date.now() });
1490
+ queue.push(t.job);
1491
+ onJob("queued", t);
1492
+ next();
1493
+ return json(req, res, 200, summary(t));
1494
+ }
1495
+ if (m[2] === "/hasil" && (req.method === "GET" || req.method === "HEAD")) {
1496
+ const f = t.hasilBerkas ? path6.join(dir(job), t.hasilBerkas) : "";
1497
+ if (t.status !== "selesai" || !f || !fs10.existsSync(f))
1498
+ return json(req, res, 409, { galat: "Video belum jadi." });
1499
+ const webm = t.hasilJenis === "video/webm";
1500
+ return sendFile(req, res, f, webm ? "video/webm" : "video/mp4", `hypeframe-${job}.${webm ? "webm" : "mp4"}`);
1501
+ }
1502
+ if (!m[2] && req.method === "GET")
1503
+ return json(req, res, 200, summary(t));
1504
+ if (!m[2] && req.method === "DELETE") {
1505
+ if (ACTIVE.has(t.status)) {
1506
+ const i = queue.indexOf(job);
1507
+ if (i >= 0)
1508
+ queue.splice(i, 1);
1509
+ update(t, { status: "batal", tahap: "" });
1510
+ onJob("cancelled", t);
1511
+ if (current?.job === job)
1512
+ current.cancel.abort();
1513
+ else
1514
+ await clearFiles(t);
1515
+ }
1516
+ return json(req, res, 200, summary(t));
1517
+ }
1518
+ return json(req, res, 405, { galat: "Metode tidak didukung." });
1519
+ } catch {
1520
+ if (!res.headersSent)
1521
+ json(req, res, 500, { galat: EngineError.ServiceError });
1522
+ }
1523
+ });
1524
+ for (const job of await fsp3.readdir(folder).catch(() => [])) {
1525
+ if (!JOB_ID.test(job))
1526
+ continue;
1527
+ try {
1528
+ const t = JSON.parse(await fsp3.readFile(path6.join(dir(job), "status.json"), "utf8"));
1529
+ if (t.status === "jalan" || t.status === "antre")
1530
+ update(t, { status: "gagal", galat: EngineError.Restarted });
1531
+ jobs.set(job, t);
1532
+ } catch {
1533
+ await fsp3.rm(dir(job), { recursive: true, force: true });
1534
+ }
1535
+ }
1536
+ const sweep = setInterval(async () => {
1537
+ const now = Date.now();
1538
+ for (const t of [...jobs.values()]) {
1539
+ const age = now - (t.diperbarui || t.dibuat);
1540
+ if (t.status === "selesai" && now - t.selesaiPada > keepHours * 3600000 || t.status === "unggah" && age > 3 * 3600000 || (t.status === "gagal" || t.status === "batal") && age > 26 * 3600000) {
1541
+ await clearFiles(t, true);
1542
+ jobs.delete(t.job);
1543
+ }
1544
+ }
1545
+ }, 10 * 60000);
1546
+ sweep.unref();
1547
+ await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
1548
+ const addr = server.address();
1549
+ return {
1550
+ port: addr.port,
1551
+ address: addr.address,
1552
+ server,
1553
+ jobs,
1554
+ stop: async () => {
1555
+ clearInterval(sweep);
1556
+ current?.cancel.abort();
1557
+ await new Promise((ok) => server.close(() => ok()));
1558
+ }
1559
+ };
1560
+ }
1561
+
1562
+ // packages/hypeframe/src/ui/banner.ts
1563
+ function banner() {
1564
+ const mark = color.brand("◆");
1565
+ return `
1566
+ ${mark} ${color.bold("hypeframe")} ${color.muted(`v${VERSION}`)}
1567
+ ${color.muted(t("banner.tagline"))}
1568
+ `;
1569
+ }
1570
+
1571
+ // packages/hypeframe/src/util/format.ts
1572
+ function bytes(n) {
1573
+ if (!(n > 0))
1574
+ return "0 B";
1575
+ const units = ["B", "KB", "MB", "GB", "TB"];
1576
+ const i = Math.min(units.length - 1, Math.floor(Math.log(n) / Math.log(1024)));
1577
+ const v = n / 1024 ** i;
1578
+ return `${v >= 10 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
1579
+ }
1580
+ function seconds(ms) {
1581
+ const s = Math.max(0, ms / 1000);
1582
+ if (s < 60)
1583
+ return `${s < 10 ? s.toFixed(1) : Math.round(s)} s`;
1584
+ const m = Math.floor(s / 60);
1585
+ return `${m}m ${Math.round(s - m * 60)}s`;
1586
+ }
1587
+ async function sizeOf(p) {
1588
+ const fsp = await import("node:fs/promises");
1589
+ const path = await import("node:path");
1590
+ try {
1591
+ const st = await fsp.stat(p);
1592
+ if (!st.isDirectory())
1593
+ return st.size;
1594
+ let total = 0;
1595
+ for (const e of await fsp.readdir(p))
1596
+ total += await sizeOf(path.join(p, e));
1597
+ return total;
1598
+ } catch {
1599
+ return 0;
1600
+ }
1601
+ }
1602
+ function table(rows, indent = " ") {
1603
+ const w = Math.max(0, ...rows.map(([k]) => k.length));
1604
+ return rows.map(([k, v]) => `${indent}${k.padEnd(w)} ${v}`).join(`
1605
+ `);
1606
+ }
1607
+
1608
+ // packages/hypeframe/src/util/open.ts
1609
+ import { spawn as spawn2 } from "node:child_process";
1610
+ var PAIRING_LINK = new RegExp(`^https?://[A-Za-z0-9.-]+(:\\d+)?/sambung\\?kode=${PAIRING_CODE.source.slice(1, -1)}$`);
1611
+ var WEB_ORIGIN = /^https?:\/\/[A-Za-z0-9.-]+(:\d+)?\/?$/;
1612
+ function launch(target) {
1613
+ const [cmd, args] = process.platform === "win32" ? ["explorer.exe", [target]] : [process.platform === "darwin" ? "open" : "xdg-open", [target]];
1614
+ const p = spawn2(cmd, args, { stdio: "ignore", detached: true });
1615
+ p.on("error", () => {
1616
+ return;
1617
+ });
1618
+ p.unref();
1619
+ }
1620
+ function openUrl(url, allowed) {
1621
+ if (!allowed.test(url))
1622
+ return false;
1623
+ launch(url);
1624
+ return true;
1625
+ }
1626
+ function openFolder(dir) {
1627
+ launch(dir);
1628
+ }
1629
+
1630
+ // packages/hypeframe/src/cli/commands/start.ts
1631
+ async function pairDevice(s, noBrowser = false) {
1632
+ const a = await pair({
1633
+ gateway: s.gateway,
1634
+ web: s.web,
1635
+ name: s.name,
1636
+ os: osName(),
1637
+ version: VERSION,
1638
+ print: (line) => log.info(line),
1639
+ openBrowser: (url) => void (noBrowser || openUrl(url, PAIRING_LINK))
1640
+ });
1641
+ const account = { ...a, gateway: s.gateway };
1642
+ saveAccount(account);
1643
+ log.ok(t("pair.done", { email: color.bold(maskEmail(account.email)) }));
1644
+ return account;
1645
+ }
1646
+ var kindLabel = (j) => j.tiket.jenis === "klip" ? t("render.kindClip") : t("render.kindVideo");
1647
+ async function start(args, { fromMenu = false } = {}) {
1648
+ const s = resolveSettings(args.flags);
1649
+ try {
1650
+ singleInstance();
1651
+ } catch (e) {
1652
+ if (e instanceof AlreadyRunning) {
1653
+ log.error(t("engine.running"));
1654
+ process.exit(1);
1655
+ }
1656
+ throw e;
1657
+ }
1658
+ if (!fromMenu) {
1659
+ process.stdout.write(`${banner()}
1660
+ `);
1661
+ console.log(table([
1662
+ [color.muted(t("status.device")), `${s.name} ${color.muted(`(${osName()})`)}`],
1663
+ [color.muted(t("status.gpu")), s.gpu ? color.ok(t("status.on")) : color.muted(t("status.off"))],
1664
+ [color.muted("Web"), s.web]
1665
+ ]));
1666
+ }
1667
+ console.log("");
1668
+ log.info(t("start.title", { versi: VERSION, os: osName(), nama: s.name }));
1669
+ let account = readAccount();
1670
+ if (!account || account.gateway !== s.gateway)
1671
+ account = await pairDevice(s, args.flags.noBrowser);
1672
+ else
1673
+ log.ok(t("pair.done", { email: color.bold(maskEmail(account.email)) }));
1674
+ const capabilities = { render: false, chrome: null, transparan: false };
1675
+ const key = crypto3.randomBytes(32).toString("base64url");
1676
+ const cache = cacheDir();
1677
+ const page = createPage({ web: s.web, cacheDir: cache });
1678
+ let runner = null;
1679
+ const started = new Map;
1680
+ const service = await createRenderService({
1681
+ folder: renderDir(),
1682
+ key,
1683
+ origin: new URL(s.web).origin,
1684
+ renderer: (task, o) => runner ? runner.renderer(task, o) : Promise.reject(new Error(EngineError.NotReady)),
1685
+ extraRoute: (req, res, url) => runner ? runner.route(req, res, url) : page.route(req, res, url),
1686
+ onJob: (event, j) => {
1687
+ if (event === "started") {
1688
+ started.set(j.job, Date.now());
1689
+ log.info(t("render.job", { kind: kindLabel(j), size: color.muted(`${j.tiket.w}×${j.tiket.h} · ${j.tiket.fps} fps · ${j.tiket.detik} s`) }));
1690
+ } else if (event === "done") {
1691
+ log.ok(t("render.jobDone", { sec: seconds(Date.now() - (started.get(j.job) ?? Date.now())), size: bytes(j.hasilUkuran ?? 0) }));
1692
+ started.delete(j.job);
1693
+ } else if (event === "failed") {
1694
+ log.warn(t("render.jobFailed", { reason: j.galat || "?" }));
1695
+ started.delete(j.job);
1696
+ } else if (event === "cancelled") {
1697
+ log.detail(t("render.jobCancelled"));
1698
+ started.delete(j.job);
1699
+ }
1700
+ }
1701
+ });
1702
+ const handler = createHandler({
1703
+ status: () => ({ versi: VERSION, os: osName(), kemampuan: capabilities }),
1704
+ kunci: () => {
1705
+ if (!capabilities.render)
1706
+ throw new Error(EngineError.NotReady);
1707
+ return { port: service.port, kunci: key, versi: VERSION };
1708
+ }
1709
+ });
1710
+ const conn = new Connection({ gateway: s.gateway, token: account.token, info: { versi: VERSION, os: osName(), nama: s.name, kemampuan: capabilities, portLokal: service.port }, handler });
1711
+ let connectedBefore = false;
1712
+ conn.on("connected", () => {
1713
+ if (connectedBefore)
1714
+ log.ok(t("engine.reconnected"));
1715
+ else {
1716
+ log.ok(t("engine.ready"));
1717
+ log.detail(t("engine.stopHint"));
1718
+ }
1719
+ connectedBefore = true;
1720
+ });
1721
+ conn.on("disconnected", () => log.warn(t("engine.lost")));
1722
+ conn.on("revoked", () => {
1723
+ log.warn(t("engine.revoked"));
1724
+ process.exit(0);
1725
+ });
1726
+ conn.on("stopped", (reason) => {
1727
+ log.error(reason === "protocol" ? t("engine.tooOld") : t("engine.replaced"));
1728
+ process.exit(1);
1729
+ });
1730
+ conn.start();
1731
+ let lastPercent = -10;
1732
+ const chromeProgress = (percent, what) => {
1733
+ if (percent === 0)
1734
+ log.info(`${t("render.downloading")} ${color.muted(what)}`);
1735
+ else if (percent - lastPercent >= 10)
1736
+ log.detail(`${what} ${percent}%`);
1737
+ else
1738
+ return;
1739
+ lastPercent = percent;
1740
+ };
1741
+ async function prepareRender() {
1742
+ try {
1743
+ if (!ffmpegPath)
1744
+ throw new Error(t("doctor.noFfmpeg"));
1745
+ const chrome = await prepareChrome(cache, chromeProgress);
1746
+ const info = await checkChrome(chrome, { gpu: s.gpu });
1747
+ if (!info.avc)
1748
+ throw new Error(t("render.noH264", { chrome: info.version }));
1749
+ await page.prepare();
1750
+ runner = createJobRunner({ chrome, ffmpeg: ffmpegPath, page, gpu: s.gpu, transparent: info.transparent, note: (m) => log.detail(m) });
1751
+ runner.setPort(service.port);
1752
+ Object.assign(capabilities, { render: true, chrome: info.version, transparan: info.transparent });
1753
+ conn.setInfo({ kemampuan: capabilities });
1754
+ conn.news("status", { kemampuan: capabilities });
1755
+ log.ok(t("render.ready", { chrome: info.version, extra: info.transparent ? "" : t("render.noAlpha") }));
1756
+ } catch (e) {
1757
+ log.warn(t("render.notYet", { reason: e.message }));
1758
+ setTimeout(prepareRender, 10 * 60000).unref();
1759
+ }
1760
+ }
1761
+ prepareRender();
1762
+ setInterval(() => runner && void page.prepare().catch(() => {
1763
+ return;
1764
+ }), 6 * 3600000).unref();
1765
+ const stop = () => {
1766
+ console.log("");
1767
+ log.info(t("engine.stopped"));
1768
+ conn.stop();
1769
+ service.stop().finally(() => process.exit(0));
1770
+ setTimeout(() => process.exit(0), 2000).unref();
1771
+ };
1772
+ process.once("SIGINT", stop);
1773
+ process.once("SIGTERM", stop);
1774
+ return new Promise(() => {
1775
+ return;
1776
+ });
1777
+ }
1778
+
1779
+ // packages/hypeframe/src/cli/commands/account.ts
1780
+ async function login(args) {
1781
+ const s = resolveSettings(args.flags);
1782
+ const a = readAccount();
1783
+ if (a && a.gateway === s.gateway) {
1784
+ log.ok(t("pair.done", { email: color.bold(maskEmail(a.email)) }));
1785
+ log.detail(t("login.already"));
1786
+ return;
1787
+ }
1788
+ await pairDevice(s, args.flags.noBrowser);
1789
+ }
1790
+ function logout() {
1791
+ deleteAccount();
1792
+ log.ok(t("logout.done"));
1793
+ }
1794
+
1795
+ // packages/hypeframe/src/cli/commands/autostart.ts
1796
+ import { spawnSync } from "node:child_process";
1797
+ import fs11 from "node:fs";
1798
+ import os3 from "node:os";
1799
+ import path7 from "node:path";
1800
+ function entryFile() {
1801
+ const home = os3.homedir();
1802
+ if (process.platform === "win32")
1803
+ return path7.join(process.env.APPDATA || path7.join(home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "HypeFrame.cmd");
1804
+ if (process.platform === "darwin")
1805
+ return path7.join(home, "Library", "LaunchAgents", "com.hypeframe.engine.plist");
1806
+ if (hasSystemd())
1807
+ return path7.join(home, ".config", "systemd", "user", "hypeframe.service");
1808
+ return path7.join(home, ".config", "autostart", "hypeframe.desktop");
1809
+ }
1810
+ function hasSystemd() {
1811
+ return process.platform === "linux" && spawnSync("systemctl", ["--user", "--version"], { stdio: "ignore" }).status === 0;
1812
+ }
1813
+ function installedScript() {
1814
+ try {
1815
+ const script = fs11.realpathSync(process.argv[1] || "");
1816
+ return /[\\/]_npx[\\/]/.test(script) ? null : script;
1817
+ } catch {
1818
+ return null;
1819
+ }
1820
+ }
1821
+ var autostartEnabled = () => fs11.existsSync(entryFile());
1822
+ var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1823
+ function autostart(mode) {
1824
+ const file = entryFile();
1825
+ if (mode !== "on" && mode !== "off") {
1826
+ log.info(autostartEnabled() ? t("autostart.isOn") : t("autostart.isOff"));
1827
+ log.detail("hypeframe autostart on | off");
1828
+ return;
1829
+ }
1830
+ if (mode === "off") {
1831
+ if (process.platform === "linux" && file.endsWith(".service"))
1832
+ spawnSync("systemctl", ["--user", "disable", "hypeframe.service"], { stdio: "ignore" });
1833
+ fs11.rmSync(file, { force: true });
1834
+ log.ok(t("autostart.off"));
1835
+ return;
1836
+ }
1837
+ const script = installedScript();
1838
+ if (!script) {
1839
+ log.warn(t("autostart.needGlobal"));
1840
+ log.detail("npm i -g hypeframe");
1841
+ return;
1842
+ }
1843
+ if (!readAccount()) {
1844
+ log.warn(t("autostart.needLogin"));
1845
+ return;
1846
+ }
1847
+ const node = process.execPath;
1848
+ fs11.mkdirSync(path7.dirname(file), { recursive: true });
1849
+ if (process.platform === "win32") {
1850
+ fs11.writeFileSync(file, `@echo off\r
1851
+ start "HypeFrame" /min "${node}" "${script}" start --no-browser\r
1852
+ `);
1853
+ } else if (process.platform === "darwin") {
1854
+ const out = path7.join(logDir(), "autostart.log");
1855
+ fs11.writeFileSync(file, `<?xml version="1.0" encoding="UTF-8"?>
1856
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1857
+ <plist version="1.0"><dict>
1858
+ <key>Label</key><string>com.hypeframe.engine</string>
1859
+ <key>ProgramArguments</key><array><string>${xml(node)}</string><string>${xml(script)}</string><string>start</string><string>--no-browser</string></array>
1860
+ <key>RunAtLoad</key><true/>
1861
+ <key>StandardOutPath</key><string>${xml(out)}</string>
1862
+ <key>StandardErrorPath</key><string>${xml(out)}</string>
1863
+ </dict></plist>
1864
+ `);
1865
+ } else if (file.endsWith(".service")) {
1866
+ fs11.writeFileSync(file, `[Unit]
1867
+ Description=HypeFrame engine
1868
+ After=network-online.target
1869
+
1870
+ [Service]
1871
+ ExecStart="${node}" "${script}" start --no-browser
1872
+ Restart=on-failure
1873
+ RestartSec=60
1874
+
1875
+ [Install]
1876
+ WantedBy=default.target
1877
+ `);
1878
+ spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
1879
+ spawnSync("systemctl", ["--user", "enable", "hypeframe.service"], { stdio: "ignore" });
1880
+ } else {
1881
+ fs11.writeFileSync(file, `[Desktop Entry]
1882
+ Type=Application
1883
+ Name=HypeFrame engine
1884
+ Exec="${node}" "${script}" start --no-browser
1885
+ Terminal=false
1886
+ X-GNOME-Autostart-enabled=true
1887
+ `);
1888
+ }
1889
+ log.ok(t("autostart.on"));
1890
+ log.detail(file);
1891
+ }
1892
+
1893
+ // packages/hypeframe/src/cli/commands/bench.ts
1894
+ import http3 from "node:http";
1895
+ import puppeteer3 from "puppeteer-core";
1896
+ var FRAMES = 150;
1897
+ var SIZES = [
1898
+ { label: "720p", w: 1280, h: 720, codec: "avc1.64001f" },
1899
+ { label: "1080p", w: 1920, h: 1080, codec: "avc1.640028" }
1900
+ ];
1901
+ var ENCODE_BENCH = `async (cfg) => {
1902
+ const canvas = new OffscreenCanvas(cfg.w, cfg.h);
1903
+ const ctx = canvas.getContext('2d');
1904
+ let failed = null;
1905
+ const enc = new VideoEncoder({ output: () => {}, error: (e) => (failed = e) });
1906
+ enc.configure({ codec: cfg.codec, width: cfg.w, height: cfg.h, bitrate: cfg.w * cfg.h * 6, framerate: 30 });
1907
+ const t0 = performance.now();
1908
+ for (let i = 0; i < cfg.frames; i++) {
1909
+ const p = i / cfg.frames;
1910
+ const grad = ctx.createLinearGradient(0, 0, cfg.w, cfg.h);
1911
+ grad.addColorStop(0, 'hsl(' + (170 + p * 90) + ', 60%, 18%)');
1912
+ grad.addColorStop(1, 'hsl(' + (250 + p * 60) + ', 55%, 10%)');
1913
+ ctx.fillStyle = grad;
1914
+ ctx.fillRect(0, 0, cfg.w, cfg.h);
1915
+ for (let k = 0; k < 40; k++) {
1916
+ const a = p * Math.PI * 2 + k * 0.6;
1917
+ ctx.beginPath();
1918
+ ctx.fillStyle = 'hsla(' + ((k * 37) % 360) + ', 80%, 65%, 0.55)';
1919
+ ctx.arc(cfg.w / 2 + Math.cos(a) * cfg.w * 0.35 * Math.sin(k), cfg.h / 2 + Math.sin(a * 1.3) * cfg.h * 0.35, 20 + (k % 7) * 12, 0, Math.PI * 2);
1920
+ ctx.fill();
1921
+ }
1922
+ ctx.fillStyle = '#fff';
1923
+ ctx.font = '600 ' + Math.round(cfg.h / 9) + 'px sans-serif';
1924
+ ctx.fillText('HypeFrame', cfg.w * 0.1 + p * cfg.w * 0.4, cfg.h * 0.55);
1925
+ const frame = new VideoFrame(canvas, { timestamp: Math.round((i * 1e6) / 30) });
1926
+ enc.encode(frame, { keyFrame: i % 60 === 0 });
1927
+ frame.close();
1928
+ while (enc.encodeQueueSize > 4) await new Promise((r) => setTimeout(r, 1));
1929
+ if (failed) throw new Error(String(failed));
1930
+ }
1931
+ await enc.flush();
1932
+ enc.close();
1933
+ return cfg.frames / ((performance.now() - t0) / 1000);
1934
+ }`;
1935
+ async function bench(args) {
1936
+ const s = resolveSettings(args.flags);
1937
+ console.log(`
1938
+ ${color.bold(t("bench.title"))} ${color.muted(`(${s.gpu ? t("bench.gpu") : t("bench.cpu")})`)}
1939
+ `);
1940
+ const chrome = await prepareChrome(cacheDir(), (percent, what) => void (percent === 0 ? log.info(`${t("render.downloading")} ${color.muted(what)}`) : percent % 20 === 0 && log.detail(`${what} ${percent}%`)));
1941
+ const srv = http3.createServer((_q, r) => (r.writeHead(200, { "content-type": "text/html" }), r.end("<!doctype html><title>bench</title>")));
1942
+ await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));
1943
+ const b = await puppeteer3.launch({
1944
+ executablePath: chrome,
1945
+ headless: true,
1946
+ protocolTimeout: 300000,
1947
+ args: ["--no-first-run", "--disable-extensions", ...s.gpu ? [] : softwareGpuArgs]
1948
+ });
1949
+ const rows = [];
1950
+ try {
1951
+ const page = await b.newPage();
1952
+ await page.goto(`http://127.0.0.1:${srv.address().port}/`);
1953
+ for (const size of SIZES) {
1954
+ log.info(t("bench.running", { size: size.label }));
1955
+ try {
1956
+ const fps = Number(await page.evaluate(`(${ENCODE_BENCH})(${JSON.stringify({ w: size.w, h: size.h, codec: size.codec, frames: FRAMES })})`));
1957
+ if (!(fps > 0))
1958
+ throw new Error("encoder");
1959
+ const minute = 60 * 30 / fps;
1960
+ rows.push([color.muted(size.label), `${color.bold(fps.toFixed(0))} fps ${color.muted(t("bench.estimate", { time: seconds(minute * 1000) }))}`]);
1961
+ } catch (e) {
1962
+ rows.push([color.muted(size.label), color.error(String(e.message).split(`
1963
+ `)[0].slice(0, 80))]);
1964
+ }
1965
+ }
1966
+ } finally {
1967
+ await b.close().catch(() => {
1968
+ return;
1969
+ });
1970
+ srv.close();
1971
+ }
1972
+ console.log("");
1973
+ console.log(table(rows));
1974
+ console.log(`
1975
+ ${color.muted(t("bench.note"))}
1976
+ `);
1977
+ }
1978
+
1979
+ // packages/hypeframe/src/cli/commands/config.ts
1980
+ import * as p from "@clack/prompts";
1981
+ function print() {
1982
+ const s = resolveSettings();
1983
+ const saved = readSettings();
1984
+ console.log("");
1985
+ console.log(table([
1986
+ [color.muted(t("config.name")), s.name],
1987
+ [color.muted("GPU"), s.gpu ? t("status.on") : t("status.off")],
1988
+ [color.muted(t("config.language")), saved.language ?? `auto (${lang()})`],
1989
+ [color.muted("Gateway"), s.gateway],
1990
+ [color.muted("Web"), s.web]
1991
+ ]));
1992
+ console.log("");
1993
+ }
1994
+ async function config(args) {
1995
+ const f = args.flags;
1996
+ const patch = {};
1997
+ if (f.name)
1998
+ patch.name = f.name.slice(0, 40);
1999
+ if (f.gpu !== undefined)
2000
+ patch.gpu = f.gpu;
2001
+ if (f.language) {
2002
+ if (!["id", "en", "auto"].includes(f.language))
2003
+ return log.error("--language id | en | auto");
2004
+ patch.language = f.language;
2005
+ }
2006
+ for (const k of ["gateway", "web"]) {
2007
+ if (!f[k])
2008
+ continue;
2009
+ if (!webOrigin(f[k]))
2010
+ return log.error(t("pair.badWeb"));
2011
+ patch[k] = f[k].replace(/\/+$/, "");
2012
+ }
2013
+ if (Object.keys(patch).length) {
2014
+ saveSettings(patch);
2015
+ resetLang();
2016
+ log.ok(t("config.saved"));
2017
+ return print();
2018
+ }
2019
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
2020
+ return print();
2021
+ const s = resolveSettings();
2022
+ const name = await p.text({ message: t("config.name"), initialValue: s.name, validate: (v) => v && v.trim() ? undefined : "—" });
2023
+ if (p.isCancel(name))
2024
+ return;
2025
+ const gpu = await p.confirm({ message: t("config.gpu"), initialValue: s.gpu });
2026
+ if (p.isCancel(gpu))
2027
+ return;
2028
+ const language = await p.select({
2029
+ message: t("config.language"),
2030
+ initialValue: readSettings().language ?? "auto",
2031
+ options: [
2032
+ { value: "auto", label: t("config.auto") },
2033
+ { value: "id", label: "Bahasa Indonesia" },
2034
+ { value: "en", label: "English" }
2035
+ ]
2036
+ });
2037
+ if (p.isCancel(language))
2038
+ return;
2039
+ saveSettings({ name: String(name).trim().slice(0, 40), gpu: !!gpu, language });
2040
+ resetLang();
2041
+ log.ok(t("config.saved"));
2042
+ log.detail(t("config.restart"));
2043
+ }
2044
+
2045
+ // packages/hypeframe/src/cli/commands/doctor.ts
2046
+ import { spawnSync as spawnSync2 } from "node:child_process";
2047
+ import fs12 from "node:fs";
2048
+ import path8 from "node:path";
2049
+ import ffmpegPath2 from "ffmpeg-static";
2050
+ var mark = { ok: color.ok(icon.ok), warn: color.warn(icon.warn), error: color.error(icon.error) };
2051
+ async function reach(url) {
2052
+ const t0 = Date.now();
2053
+ try {
2054
+ const r = await fetch(url, { signal: AbortSignal.timeout(1e4), cache: "no-store" });
2055
+ const body = r.headers.get("content-type")?.includes("json") ? await r.json().catch(() => null) : null;
2056
+ return { ok: r.status < 500, status: r.status, ms: Date.now() - t0, body };
2057
+ } catch {
2058
+ return { ok: false, ms: Date.now() - t0 };
2059
+ }
2060
+ }
2061
+ async function doctor(args) {
2062
+ const s = resolveSettings(args.flags);
2063
+ const checks = [];
2064
+ const show = (c) => {
2065
+ checks.push(c);
2066
+ console.log(` ${mark[c.result]} ${c.label.padEnd(16)} ${c.result === "ok" ? color.muted(c.detail) : c.detail}`);
2067
+ };
2068
+ console.log(`
2069
+ ${color.bold(t("doctor.title"))}
2070
+ `);
2071
+ const [maj, min] = process.versions.node.split(".").map(Number);
2072
+ show({ label: "Node.js", result: maj > 20 || maj === 20 && min >= 3 ? "ok" : "error", detail: `${process.versions.node}${maj < 20 || maj === 20 && min < 3 ? ` ${t("doctor.nodeOld")}` : ""}` });
2073
+ try {
2074
+ const probe = path8.join(dataDir(), `.probe-${process.pid}`);
2075
+ fs12.writeFileSync(probe, "x");
2076
+ fs12.rmSync(probe);
2077
+ const st = fs12.statfsSync(dataDir());
2078
+ const free = st.bavail * st.bsize;
2079
+ show({ label: t("doctor.disk"), result: free > 2 * 1024 ** 3 ? "ok" : "warn", detail: `${dataDir()} ${color.muted(icon.dot)} ${t("doctor.free", { size: bytes(free) })}` });
2080
+ } catch (e) {
2081
+ show({ label: t("doctor.disk"), result: "error", detail: e.message });
2082
+ }
2083
+ const ff = ffmpegPath2;
2084
+ if (!ff || !fs12.existsSync(ff))
2085
+ show({ label: "ffmpeg", result: "error", detail: t("doctor.noFfmpeg") });
2086
+ else {
2087
+ const r = spawnSync2(ff, ["-hide_banner", "-version"], { encoding: "utf8", timeout: 15000 });
2088
+ const v = /ffmpeg version (\S+)/.exec(r.stdout || "")?.[1];
2089
+ show({ label: "ffmpeg", result: v ? "ok" : "error", detail: v || t("doctor.noFfmpeg") });
2090
+ }
2091
+ const chrome = findChrome() || await cachedChrome(cacheDir());
2092
+ if (!chrome)
2093
+ show({ label: "Chrome", result: "warn", detail: t("doctor.chromeLater") });
2094
+ else {
2095
+ try {
2096
+ const info = await checkChrome(chrome, { gpu: s.gpu });
2097
+ show({ label: "Chrome", result: info.avc ? "ok" : "error", detail: `${info.version} ${color.muted(icon.dot)} H.264 ${info.avc ? t("doctor.yes") : t("doctor.no")}` });
2098
+ show({ label: t("doctor.alpha"), result: info.transparent ? "ok" : "warn", detail: info.transparent ? t("doctor.yes") : t("doctor.alphaNo") });
2099
+ } catch (e) {
2100
+ show({ label: "Chrome", result: "error", detail: String(e.message).split(`
2101
+ `)[0].slice(0, 120) });
2102
+ }
2103
+ }
2104
+ const gw = await reach(`${s.gateway}/`);
2105
+ show({ label: "Gateway", result: gw.ok ? "ok" : "error", detail: gw.ok ? `${s.gateway} ${color.muted(`${gw.ms} ms`)}` : `${s.gateway} ${t("doctor.unreachable")}` });
2106
+ const web = await reach(`${s.web}/render/versi.json`);
2107
+ const webOk = web.status === 200 && !!web.body?.versi;
2108
+ show({ label: "HypeFrame Web", result: webOk ? "ok" : "error", detail: webOk ? `${s.web} ${color.muted(`${web.ms} ms`)}` : `${s.web} ${t("doctor.unreachable")}${web.status ? ` (${web.status})` : ""}` });
2109
+ const a = readAccount();
2110
+ show({ label: t("status.account"), result: a && a.gateway === s.gateway ? "ok" : "warn", detail: a && a.gateway === s.gateway ? maskEmail(a.email) : t("status.notPaired") });
2111
+ const bad = checks.filter((c) => c.result === "error").length;
2112
+ const warn = checks.filter((c) => c.result === "warn").length;
2113
+ console.log(`
2114
+ ${bad ? color.error(t("doctor.summaryBad", { n: bad })) : warn ? color.warn(t("doctor.summaryWarn", { n: warn })) : color.ok(t("doctor.summaryOk"))}
2115
+ `);
2116
+ return checks;
2117
+ }
2118
+
2119
+ // packages/hypeframe/src/cli/commands/history.ts
2120
+ import fs13 from "node:fs";
2121
+ import path9 from "node:path";
2122
+ function readHistory(hours = 24) {
2123
+ const root = renderDir();
2124
+ const since = Date.now() - hours * 3600000;
2125
+ const out = [];
2126
+ for (const name of fs13.readdirSync(root)) {
2127
+ if (!JOB_ID.test(name))
2128
+ continue;
2129
+ try {
2130
+ const j = JSON.parse(fs13.readFileSync(path9.join(root, name, "status.json"), "utf8"));
2131
+ if ((j.diperbarui || j.dibuat) < since)
2132
+ continue;
2133
+ const f = j.hasilBerkas ? path9.join(root, name, j.hasilBerkas) : null;
2134
+ out.push({ job: j, file: f && fs13.existsSync(f) ? f : null });
2135
+ } catch {}
2136
+ }
2137
+ return out.sort((a, b) => (b.job.diperbarui || 0) - (a.job.diperbarui || 0));
2138
+ }
2139
+ var time2 = (ms) => new Date(ms).toTimeString().slice(0, 5);
2140
+ function formatItem({ job: j, file }) {
2141
+ const mark = j.status === "selesai" ? color.ok(icon.ok) : j.status === "gagal" ? color.error(icon.error) : j.status === "batal" ? color.muted(icon.dot) : color.info(icon.info);
2142
+ const kind = j.tiket.jenis === "klip" ? t("render.kindClip") : t("render.kindVideo");
2143
+ const took = j.selesaiPada && j.mulaiPada ? ` ${color.muted(icon.dot)} ${seconds(j.selesaiPada - j.mulaiPada)}` : "";
2144
+ const detail = j.status === "selesai" ? `${bytes(j.hasilUkuran ?? 0)}${took}` : j.status === "gagal" ? color.error(String(j.galat || "").slice(0, 70)) : j.status === "batal" ? color.muted(t("history.cancelled")) : color.info(`${j.persen ?? 0}%`);
2145
+ return `${color.muted(time2(j.diperbarui || j.dibuat))} ${mark} ${kind} ${color.muted(`${j.tiket.w}×${j.tiket.h}`)} ${detail}${file ? `
2146
+ ${color.muted(icon.detail)} ${color.muted(file)}` : ""}`;
2147
+ }
2148
+ function history() {
2149
+ const items = readHistory();
2150
+ console.log("");
2151
+ if (!items.length)
2152
+ console.log(` ${color.muted(t("history.empty"))}`);
2153
+ for (const it of items)
2154
+ console.log(` ${formatItem(it)}`);
2155
+ console.log("");
2156
+ return items;
2157
+ }
2158
+
2159
+ // packages/hypeframe/src/cli/commands/maintenance.ts
2160
+ import { spawnSync as spawnSync3 } from "node:child_process";
2161
+ import fs14 from "node:fs";
2162
+ import os4 from "node:os";
2163
+ import path10 from "node:path";
2164
+ async function clean() {
2165
+ if (runningPid()) {
2166
+ log.warn(t("clean.running"));
2167
+ return;
2168
+ }
2169
+ const targets = [path10.join(cacheDir(), "chrome"), path10.join(cacheDir(), "halaman"), path10.join(logDir(), "hypeframe.log.1")];
2170
+ for (const job of fs14.readdirSync(renderDir())) {
2171
+ if (!JOB_ID.test(job))
2172
+ continue;
2173
+ try {
2174
+ const s = JSON.parse(fs14.readFileSync(path10.join(renderDir(), job, "status.json"), "utf8")).status;
2175
+ if (s === "gagal" || s === "batal" || s === "unggah")
2176
+ targets.push(path10.join(renderDir(), job));
2177
+ } catch {
2178
+ targets.push(path10.join(renderDir(), job));
2179
+ }
2180
+ }
2181
+ let freed = 0;
2182
+ for (const p of targets) {
2183
+ freed += await sizeOf(p);
2184
+ fs14.rmSync(p, { recursive: true, force: true });
2185
+ }
2186
+ log.ok(t("clean.done", { size: bytes(freed) }));
2187
+ }
2188
+ function report() {
2189
+ const s = resolveSettings();
2190
+ const a = readAccount();
2191
+ let recent = "";
2192
+ try {
2193
+ recent = fs14.readFileSync(path10.join(logDir(), "hypeframe.log"), "utf8").split(`
2194
+ `).slice(-400).join(`
2195
+ `);
2196
+ } catch {
2197
+ recent = "(no log yet)";
2198
+ }
2199
+ const lines = [
2200
+ `hypeframe ${VERSION}`,
2201
+ `created ${new Date().toISOString()}`,
2202
+ `node ${process.versions.node} · ${process.platform} ${os4.release()} ${process.arch} · ${os4.cpus()[0]?.model ?? "?"} ×${os4.cpus().length} · ${bytes(os4.totalmem())} RAM`,
2203
+ `gateway ${s.gateway}`,
2204
+ `web ${s.web}`,
2205
+ `gpu ${s.gpu}`,
2206
+ `language ${readSettings().language ?? "auto"}`,
2207
+ `account ${a ? maskEmail(a.email) : "-"}`,
2208
+ `engine running ${runningPid() ? "yes" : "no"}`,
2209
+ "",
2210
+ "--- log ---",
2211
+ recent
2212
+ ];
2213
+ const stamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, "");
2214
+ const file = path10.join(dataDir(), `laporan-${stamp}.txt`);
2215
+ fs14.writeFileSync(file, mask(lines.join(`
2216
+ `)), { mode: 384 });
2217
+ log.ok(t("report.done", { file }));
2218
+ log.detail(t("report.hint"));
2219
+ return file;
2220
+ }
2221
+ function update() {
2222
+ if (!installedScript()) {
2223
+ log.info(t("update.npx"));
2224
+ log.detail("npx hypeframe@latest");
2225
+ return;
2226
+ }
2227
+ log.info(t("update.running"));
2228
+ const r = spawnSync3("npm", ["i", "-g", "hypeframe@latest"], { stdio: "inherit", shell: process.platform === "win32" });
2229
+ if (r.status === 0)
2230
+ log.ok(t("update.done"));
2231
+ else
2232
+ log.error(t("update.failed"));
2233
+ }
2234
+ function openWeb(args) {
2235
+ const { web } = resolveSettings(args.flags);
2236
+ if (openUrl(web, WEB_ORIGIN))
2237
+ log.ok(t("open.done", { web }));
2238
+ else
2239
+ log.warn(t("pair.badWeb"));
2240
+ }
2241
+
2242
+ // packages/hypeframe/src/cli/commands/status.ts
2243
+ import fs15 from "node:fs";
2244
+ import path11 from "node:path";
2245
+ function statusRows(args) {
2246
+ const s = resolveSettings(args?.flags);
2247
+ const a = readAccount();
2248
+ const pid = runningPid();
2249
+ const chrome = findChrome() || fs15.existsSync(path11.join(cacheDir(), "chrome"));
2250
+ const recent = readHistory();
2251
+ const k = (key) => color.muted(t(key));
2252
+ return [
2253
+ [k("status.account"), a && a.gateway === s.gateway ? `${color.ok(icon.ok)} ${maskEmail(a.email)}` : `${color.warn(icon.warn)} ${t("status.notPaired")}`],
2254
+ [k("status.engine"), pid ? `${color.ok(icon.info)} ${t("status.running", { pid })}` : color.muted(t("status.stopped"))],
2255
+ [k("status.device"), `${s.name} ${color.muted(`(${osName()})`)}`],
2256
+ [k("status.render"), `${chrome ? "Chrome" : color.muted(t("status.chromeLater"))} ${color.muted(icon.dot)} ${t("status.gpu")} ${s.gpu ? color.ok(t("status.on")) : color.muted(t("status.off"))}`],
2257
+ [k("status.recent"), recent.length ? t("status.recentCount", { n: recent.length }) : color.muted("-")],
2258
+ [k("status.version"), `${VERSION} ${color.muted(icon.dot)} Node ${process.versions.node}`]
2259
+ ];
2260
+ }
2261
+ function status(args) {
2262
+ console.log("");
2263
+ console.log(table(statusRows(args)));
2264
+ console.log("");
2265
+ }
2266
+
2267
+ // packages/hypeframe/src/cli/menu.ts
2268
+ import * as p2 from "@clack/prompts";
2269
+ async function menu(args) {
2270
+ process.stdout.write(banner());
2271
+ console.log("");
2272
+ console.log(table(statusRows(args)));
2273
+ console.log("");
2274
+ for (;; ) {
2275
+ const s = resolveSettings(args.flags);
2276
+ const paired = !!readAccount() && readAccount()?.gateway === s.gateway;
2277
+ const running = !!runningPid();
2278
+ const choice = await p2.select({
2279
+ message: t("menu.question"),
2280
+ options: [
2281
+ { value: "start", label: color.brand(t("menu.start")), hint: running ? t("status.running", { pid: runningPid() ?? "" }) : paired ? undefined : t("menu.startPair") },
2282
+ { value: "open", label: t("menu.open"), hint: s.web.replace(/^https?:\/\//, "") },
2283
+ { value: "bench", label: t("menu.bench") },
2284
+ { value: "history", label: t("menu.history") },
2285
+ { value: "agent", label: `${color.ai("✦")} ${t("menu.agent")}`, hint: t("menu.soon") },
2286
+ { value: "autostart", label: t("menu.autostart"), hint: autostartEnabled() ? t("status.on") : t("status.off") },
2287
+ { value: "config", label: t("menu.config") },
2288
+ { value: "doctor", label: t("menu.doctor") },
2289
+ { value: "clean", label: t("menu.clean") },
2290
+ { value: "report", label: t("menu.report") },
2291
+ { value: "update", label: t("menu.update") },
2292
+ paired ? { value: "logout", label: t("menu.logout") } : { value: "login", label: t("menu.login") },
2293
+ { value: "exit", label: color.muted(t("menu.exit")) }
2294
+ ]
2295
+ });
2296
+ if (p2.isCancel(choice) || choice === "exit") {
2297
+ p2.outro(color.muted(t("menu.bye")));
2298
+ return;
2299
+ }
2300
+ try {
2301
+ switch (choice) {
2302
+ case "start":
2303
+ if (running) {
2304
+ p2.log.warn(t("engine.running"));
2305
+ break;
2306
+ }
2307
+ await start(args, { fromMenu: true });
2308
+ return;
2309
+ case "open":
2310
+ openWeb(args);
2311
+ break;
2312
+ case "bench":
2313
+ await bench(args);
2314
+ break;
2315
+ case "history": {
2316
+ const items = history();
2317
+ if (items.some((i) => i.file)) {
2318
+ const go = await p2.confirm({ message: t("history.openFolder"), initialValue: false });
2319
+ if (go === true)
2320
+ openFolder(renderDir());
2321
+ }
2322
+ break;
2323
+ }
2324
+ case "agent":
2325
+ p2.log.message(`${color.ai("✦")} ${t("agent.soon")}`);
2326
+ break;
2327
+ case "autostart": {
2328
+ const on = await p2.confirm({ message: t("autostart.question"), initialValue: !autostartEnabled() });
2329
+ if (!p2.isCancel(on))
2330
+ autostart(on ? "on" : "off");
2331
+ break;
2332
+ }
2333
+ case "config":
2334
+ await config({ ...args, flags: {} });
2335
+ break;
2336
+ case "doctor":
2337
+ await doctor(args);
2338
+ break;
2339
+ case "clean": {
2340
+ const ok = await p2.confirm({ message: t("clean.question"), initialValue: true });
2341
+ if (ok === true)
2342
+ await clean();
2343
+ break;
2344
+ }
2345
+ case "report":
2346
+ report();
2347
+ break;
2348
+ case "update":
2349
+ update();
2350
+ break;
2351
+ case "login":
2352
+ await login(args);
2353
+ break;
2354
+ case "logout": {
2355
+ const ok = await p2.confirm({ message: t("confirm.logout"), initialValue: false });
2356
+ if (ok === true)
2357
+ logout();
2358
+ break;
2359
+ }
2360
+ }
2361
+ } catch (e) {
2362
+ p2.log.error(`${icon.error} ${e.message}`);
2363
+ }
2364
+ }
2365
+ }
2366
+
2367
+ // packages/hypeframe/src/index.ts
2368
+ function help() {
2369
+ const rows = [
2370
+ ["start", t("help.start")],
2371
+ ["login", t("help.login")],
2372
+ ["logout", t("help.logout")],
2373
+ ["status", t("help.status")],
2374
+ ["open", t("help.open")],
2375
+ ["doctor", t("help.doctor")],
2376
+ ["bench", t("help.bench")],
2377
+ ["history", t("help.history")],
2378
+ ["autostart on|off", t("help.autostart")],
2379
+ ["config", t("help.config")],
2380
+ ["clean", t("help.clean")],
2381
+ ["report", t("help.report")],
2382
+ ["update", t("help.update")]
2383
+ ];
2384
+ const flags = [
2385
+ ["--gpu", t("help.gpu")],
2386
+ ["--name <name>", t("help.name")],
2387
+ ["--no-browser", t("help.noBrowser")],
2388
+ ["--language id|en|auto", t("help.language")],
2389
+ ["--gateway <url>, --web <url>", t("help.addresses")]
2390
+ ];
2391
+ const w = Math.max(...[...rows, ...flags].map(([k]) => k.length));
2392
+ process.stdout.write(banner());
2393
+ console.log(`
2394
+ ${color.bold(t("help.usage"))} hypeframe ${color.muted("[command] [options]")}
2395
+ `);
2396
+ console.log(` ${color.bold(t("help.commands"))}`);
2397
+ for (const [k, v] of rows)
2398
+ console.log(` ${color.brand(k.padEnd(w))} ${v}`);
2399
+ console.log(`
2400
+ ${color.bold(t("help.options"))}`);
2401
+ for (const [k, v] of flags)
2402
+ console.log(` ${color.brand(k.padEnd(w))} ${v}`);
2403
+ console.log(`
2404
+ ${color.muted(t("help.noCommand"))}
2405
+ `);
2406
+ }
2407
+ var COMMANDS = {
2408
+ start: (a) => start(a),
2409
+ login: (a) => login(a),
2410
+ logout: () => logout(),
2411
+ status: (a) => status(a),
2412
+ open: (a) => openWeb(a),
2413
+ doctor: async (a) => {
2414
+ const checks = await doctor(a);
2415
+ process.exitCode = checks.some((c) => c.result === "error") ? 1 : 0;
2416
+ },
2417
+ bench: (a) => bench(a),
2418
+ history: () => history(),
2419
+ autostart: (a) => autostart(a.rest[0]),
2420
+ config: (a) => config(a),
2421
+ clean: () => clean(),
2422
+ report: () => report(),
2423
+ update: () => update(),
2424
+ help: () => help()
2425
+ };
2426
+ async function main() {
2427
+ const args = parseArgs(process.argv.slice(2));
2428
+ if (args.flags.version)
2429
+ return console.log(VERSION);
2430
+ if (args.flags.help)
2431
+ return help();
2432
+ if (args.command === null) {
2433
+ if (process.stdin.isTTY && process.stdout.isTTY)
2434
+ return menu(args);
2435
+ return start(args);
2436
+ }
2437
+ const run = COMMANDS[args.command];
2438
+ if (!run) {
2439
+ log.error(t("help.unknown", { command: args.command }));
2440
+ log.detail("hypeframe help");
2441
+ process.exitCode = 1;
2442
+ return;
2443
+ }
2444
+ await run(args);
2445
+ }
2446
+ main().catch((e) => {
2447
+ log.error(e?.message || String(e));
2448
+ process.exit(1);
2449
+ });