@aivin-labs/cli 1.0.11 → 1.0.21
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/README.md +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { createRequire } from 'module';
|
|
6
|
+
import { gunzipSync } from 'zlib';
|
|
7
|
+
import axios from 'axios';
|
|
8
|
+
import { REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Runtime WebRTC native (`@roamhq/wrtc`) cho Desktop Scenecast. Cài qua npm → có sẵn trong node_modules. Bản một tệp (Bun) không mang được
|
|
12
|
+
* thư viện native → lần đầu cần thì tải gói npm đã GHIM (phiên bản + mã băm sha512 lấy từ package-lock), kiểm băm, bung vào
|
|
13
|
+
* `~/.aivin/runtime/wrtc-<bản>/node_modules`, các lần sau nạp từ đó. Tải hỏng / sai băm → không dùng, phiên xem lùi về JPEG.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const WRTC_VERSION = '0.10.0';
|
|
17
|
+
|
|
18
|
+
const REGISTRY = 'https://registry.npmjs.org';
|
|
19
|
+
const COMMON_PACKAGES = [
|
|
20
|
+
{ name: '@roamhq/wrtc', version: WRTC_VERSION, integrity: 'sha512-yFqQQ0EV1ZUHaphh3tmjoxPi2wzhW2vjmzoAVNRRLUjXYd2e1nvwi9TKfE2w4WNvNws/hBkouvOt23Xo9FkXkQ==' },
|
|
21
|
+
{ name: 'domexception', version: '4.0.0', integrity: 'sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==' },
|
|
22
|
+
{ name: 'webidl-conversions', version: '7.0.0', integrity: 'sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==' },
|
|
23
|
+
];
|
|
24
|
+
/** Gói native theo nền tảng — Desktop Scenecast hiện chỉ Windows. */
|
|
25
|
+
const NATIVE_PACKAGES = {
|
|
26
|
+
'win32-x64': { name: '@roamhq/wrtc-win32-x64', version: WRTC_VERSION, integrity: 'sha512-wEVXMvLrBizdLyrd+Zc7zb7zpwUuHUBXwrdIvI69e3i/AA8YsVYI2xo/sxk6GoQ+o8a14ONc4SStDS35TCjg+w==' },
|
|
27
|
+
};
|
|
28
|
+
const MAX_TARBALL_BYTES = 64 * 1024 * 1024;
|
|
29
|
+
|
|
30
|
+
export function runtimeDir(home = REMOTE_CONFIG_DIR) {
|
|
31
|
+
return path.join(home, 'runtime', `wrtc-${WRTC_VERSION}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function runtimePackages(triple = `${os.platform()}-${os.arch()}`) {
|
|
35
|
+
const native = NATIVE_PACKAGES[triple];
|
|
36
|
+
return native ? [...COMMON_PACKAGES, native] : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function tarballUrl({ name, version }) {
|
|
40
|
+
const base = name.split('/').pop();
|
|
41
|
+
return `${REGISTRY}/${name}/-/${base}-${version}.tgz`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function integrityOk(buf, integrity) {
|
|
45
|
+
const [algo, expected] = String(integrity).split('-');
|
|
46
|
+
if (algo !== 'sha512' || !expected) return false;
|
|
47
|
+
return createHash('sha512').update(buf).digest('base64') === expected;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Bung tarball npm (ustar, đã gunzip) vào `destDir`: chỉ tệp thường dưới `package/`, bỏ đường dẫn tuyệt đối / `..` (chống ghi ra ngoài).
|
|
52
|
+
*/
|
|
53
|
+
export function extractNpmTarball(tar, destDir) {
|
|
54
|
+
const root = path.resolve(destDir);
|
|
55
|
+
let offset = 0;
|
|
56
|
+
let longName = null;
|
|
57
|
+
while (offset + 512 <= tar.length) {
|
|
58
|
+
const header = tar.subarray(offset, offset + 512);
|
|
59
|
+
if (header.every((b) => b === 0)) break;
|
|
60
|
+
const field = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/s, '');
|
|
61
|
+
const size = parseInt(field(124, 12).trim() || '0', 8);
|
|
62
|
+
const type = String.fromCharCode(header[156] || 48);
|
|
63
|
+
const prefix = field(345, 155);
|
|
64
|
+
let name = longName || (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
|
|
65
|
+
longName = null;
|
|
66
|
+
const body = tar.subarray(offset + 512, offset + 512 + size);
|
|
67
|
+
offset += 512 + Math.ceil(size / 512) * 512;
|
|
68
|
+
if (type === 'L') { longName = body.toString('utf8').replace(/\0.*$/s, ''); continue; }
|
|
69
|
+
if (type !== '0' && type !== '\0') continue;
|
|
70
|
+
name = name.replace(/^package\//, '');
|
|
71
|
+
const target = path.resolve(root, name);
|
|
72
|
+
if (!target.startsWith(root + path.sep)) continue;
|
|
73
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
74
|
+
fs.writeFileSync(target, body);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function fetchTarball(pkg, get) {
|
|
79
|
+
const res = await get(tarballUrl(pkg), { responseType: 'arraybuffer', timeout: 120_000, maxContentLength: MAX_TARBALL_BYTES });
|
|
80
|
+
const buf = Buffer.from(res.data);
|
|
81
|
+
if (!integrityOk(buf, pkg.integrity)) throw new Error(`${pkg.name}: sai mã băm`);
|
|
82
|
+
return buf;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Tải + kiểm + bung mọi gói vào thư mục tạm rồi đổi tên một lần (không để lại bản dở). */
|
|
86
|
+
export async function installRuntime({ home = REMOTE_CONFIG_DIR, triple, get = axios.get } = {}) {
|
|
87
|
+
const packages = runtimePackages(triple);
|
|
88
|
+
if (!packages) return false;
|
|
89
|
+
const dir = runtimeDir(home);
|
|
90
|
+
const tmp = `${dir}.tmp-${process.pid}`;
|
|
91
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
92
|
+
try {
|
|
93
|
+
for (const pkg of packages) {
|
|
94
|
+
const tgz = await fetchTarball(pkg, get);
|
|
95
|
+
extractNpmTarball(gunzipSync(tgz), path.join(tmp, 'node_modules', ...pkg.name.split('/')));
|
|
96
|
+
}
|
|
97
|
+
fs.writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({ name: 'aivin-wrtc-runtime', private: true }));
|
|
98
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
99
|
+
fs.renameSync(tmp, dir);
|
|
100
|
+
return true;
|
|
101
|
+
} catch (e) {
|
|
102
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
103
|
+
throw e;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function loadFromDir(dir, log = () => {}) {
|
|
108
|
+
if (!fs.existsSync(path.join(dir, 'package.json'))) return null;
|
|
109
|
+
try {
|
|
110
|
+
return createRequire(path.join(dir, 'package.json'))('@roamhq/wrtc');
|
|
111
|
+
} catch (e) {
|
|
112
|
+
log(`Không nạp được WebRTC runtime ở ${dir}: ${e?.message || e}`);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Nạp runtime: node_modules → bản đã tải → (chưa có) tải nền một lần rồi trả `null` cho lần này (phiên đầu chạy JPEG, phiên sau có
|
|
119
|
+
* WebRTC). `AIVIN_NO_WRTC_DOWNLOAD=1` tắt việc tải.
|
|
120
|
+
*/
|
|
121
|
+
export function createWebRtcRuntimeLoader({ home = REMOTE_CONFIG_DIR, importNpm = () => import('@roamhq/wrtc'), install = installRuntime, log = () => {} } = {}) {
|
|
122
|
+
let installing = null;
|
|
123
|
+
return async function loadWebRtcRuntime() {
|
|
124
|
+
// Bản một tệp: Bun đã gói phần JS của wrtc nhưng không có tệp native — lần nhập đầu ném lỗi, lần sau trả module RỖNG (đo 02/11/2026).
|
|
125
|
+
// Chỉ nhận khi thật sự có RTCPeerConnection.
|
|
126
|
+
const npm = await importNpm().catch(() => null);
|
|
127
|
+
const npmRuntime = npm?.RTCPeerConnection ? npm : npm?.default?.RTCPeerConnection ? npm.default : null;
|
|
128
|
+
if (npmRuntime) return npmRuntime;
|
|
129
|
+
const cached = loadFromDir(runtimeDir(home), log);
|
|
130
|
+
if (cached) return cached;
|
|
131
|
+
if (process.env.AIVIN_NO_WRTC_DOWNLOAD === '1' || !runtimePackages()) return null;
|
|
132
|
+
installing ||= install({ home })
|
|
133
|
+
.then((ok) => { if (ok) log('WebRTC runtime đã tải — lần xem màn hình sau dùng video trực tiếp'); })
|
|
134
|
+
.catch((e) => { log(`Không tải được WebRTC runtime: ${e?.message || e} — xem màn hình dùng ảnh JPEG`); installing = null; });
|
|
135
|
+
return null;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import net from 'net';
|
|
2
|
+
import readline from 'readline';
|
|
3
|
+
import { spawn } from 'child_process';
|
|
4
|
+
import { createDesktopWebRtc } from './desktopWebRtc.mjs';
|
|
5
|
+
import { createRawFrameReader } from './desktopCast.mjs';
|
|
6
|
+
import { createWebRtcRuntimeLoader } from './webrtcRuntime.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* WebRTC của Desktop Scenecast chạy trong TIẾN TRÌNH CON riêng (`aivin __desktop-webrtc-worker`): thư viện native `@roamhq/wrtc` làm
|
|
10
|
+
* tiến trình sập lúc thoát (Bun: mọi cách thoát; Node: thoát tự nhiên — đo 02/11/2026). Ở tiến trình con thì sập không ảnh hưởng mã
|
|
11
|
+
* thoát của daemon (trình giữ chạy / tự lùi bản dựa vào mã đó), và lỗi native giữa phiên chỉ làm mất WebRTC (lùi JPEG), không mất daemon.
|
|
12
|
+
*
|
|
13
|
+
* Giao thức: mỗi dòng stdin / stdout một JSON.
|
|
14
|
+
* daemon → con: `start {sessionId, viewerId, iceServers, videoBitrate}` ·`signal {msg}` · `push {frame}` · `pipe {name}` · `close {viewerId}` · `closeAll`
|
|
15
|
+
* daemon → con (con trỏ): `cursor {cursor}` · `cursorShape {shape}`
|
|
16
|
+
* con → daemon: `started {viewerId, ok}` · `signal {payload}` · `status {payload}` · `input {raw, viewerId}` · `peerReady {viewerId}` ·
|
|
17
|
+
* `state {needsFallback, needsJpeg, hasVideo, videoLive, localCursor}` · `log {text}`
|
|
18
|
+
* Khung thô I420 không đi qua daemon: con tự nối named pipe của tiến trình quay.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const DESKTOP_WEBRTC_WORKER_ARG = '__desktop-webrtc-worker';
|
|
22
|
+
const VIDEO_LIVE_MS = 3000;
|
|
23
|
+
|
|
24
|
+
export async function runDesktopWebRtcWorker({ input = process.stdin, output = process.stdout } = {}) {
|
|
25
|
+
const send = (msg) => { try { output.write(JSON.stringify(msg) + '\n'); } catch { /* daemon đã đóng */ } };
|
|
26
|
+
let lastRawAt = 0;
|
|
27
|
+
let lastState = '';
|
|
28
|
+
let rtc;
|
|
29
|
+
const sendState = () => {
|
|
30
|
+
const state = {
|
|
31
|
+
needsFallback: rtc.needsFallback(), needsJpeg: rtc.needsJpeg(), hasVideo: rtc.hasVideo(), videoLive: Date.now() - lastRawAt < VIDEO_LIVE_MS, localCursor: rtc.localCursor(),
|
|
32
|
+
};
|
|
33
|
+
const key = JSON.stringify(state);
|
|
34
|
+
if (key !== lastState) { lastState = key; send({ t: 'state', ...state }); }
|
|
35
|
+
};
|
|
36
|
+
rtc = createDesktopWebRtc({
|
|
37
|
+
emitSignal: (payload) => send({ t: 'signal', payload }),
|
|
38
|
+
emitStatus: (payload) => { send({ t: 'status', payload }); sendState(); },
|
|
39
|
+
onInput: (raw, viewerId) => send({ t: 'input', raw, viewerId }),
|
|
40
|
+
onPeerReady: (viewerId) => { send({ t: 'peerReady', viewerId }); sendState(); },
|
|
41
|
+
onCursorMode: () => sendState(),
|
|
42
|
+
loadRuntime: createWebRtcRuntimeLoader({ log: (text) => send({ t: 'log', text }) }),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
let pipeSocket = null;
|
|
46
|
+
let pipeName = '';
|
|
47
|
+
const connectPipe = (name, attempt = 0) => {
|
|
48
|
+
if (attempt === 0 && name === pipeName && pipeSocket) return;
|
|
49
|
+
pipeName = name;
|
|
50
|
+
pipeSocket?.destroy();
|
|
51
|
+
const sock = net.connect(`\\\\.\\pipe\\${name}`);
|
|
52
|
+
const read = createRawFrameReader((frame) => { if (rtc.pushRaw(frame)) lastRawAt = Date.now(); }, () => sock.destroy());
|
|
53
|
+
sock.on('data', read);
|
|
54
|
+
sock.on('error', () => {});
|
|
55
|
+
sock.on('close', () => {
|
|
56
|
+
if (pipeSocket !== sock) return;
|
|
57
|
+
pipeSocket = null;
|
|
58
|
+
if (attempt < 20) setTimeout(() => { if (!pipeSocket) connectPipe(name, attempt + 1); }, Math.min(2000, 100 * 2 ** attempt));
|
|
59
|
+
});
|
|
60
|
+
pipeSocket = sock;
|
|
61
|
+
};
|
|
62
|
+
const stateTimer = setInterval(sendState, 1000);
|
|
63
|
+
|
|
64
|
+
const handlers = {
|
|
65
|
+
start: async (m) => {
|
|
66
|
+
const ok = await rtc.start({ sessionId: m.sessionId, viewerId: m.viewerId, iceServers: m.iceServers || [], videoBitrate: m.videoBitrate || null }).catch(() => false);
|
|
67
|
+
send({ t: 'started', viewerId: m.viewerId, ok });
|
|
68
|
+
sendState();
|
|
69
|
+
},
|
|
70
|
+
signal: (m) => rtc.signal(m.msg).catch(() => false),
|
|
71
|
+
push: (m) => rtc.push(m.frame),
|
|
72
|
+
cursor: (m) => rtc.pushCursor(m.cursor),
|
|
73
|
+
cursorShape: (m) => rtc.pushCursorShape(m.shape),
|
|
74
|
+
pipe: (m) => { if (m.name) connectPipe(String(m.name)); },
|
|
75
|
+
close: (m) => { rtc.close(m.viewerId); sendState(); },
|
|
76
|
+
closeAll: () => { rtc.closeAll(); const sock = pipeSocket; pipeSocket = null; pipeName = ''; sock?.destroy(); sendState(); },
|
|
77
|
+
};
|
|
78
|
+
const rl = readline.createInterface({ input });
|
|
79
|
+
rl.on('line', (line) => {
|
|
80
|
+
let msg;
|
|
81
|
+
try { msg = JSON.parse(line); } catch { return; }
|
|
82
|
+
void Promise.resolve(handlers[msg?.t]?.(msg)).catch(() => undefined);
|
|
83
|
+
});
|
|
84
|
+
// Daemon thoát / đóng ống → con thoát theo (Windows không tự giết con khi cha chết).
|
|
85
|
+
await new Promise((resolve) => rl.on('close', resolve));
|
|
86
|
+
clearInterval(stateTimer);
|
|
87
|
+
rtc.closeAll();
|
|
88
|
+
process.exit(0);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Phía daemon: cùng API với createDesktopWebRtc (start / signal / push / needsFallback / needsJpeg / hasVideo / close / closeAll) + `attachPipe`
|
|
93
|
+
* và `videoLive`. Tiến trình con dựng khi phiên đầu cần, tắt khi `closeAll`; con chết giữa phiên → coi như không ai có WebRTC (lùi JPEG).
|
|
94
|
+
*/
|
|
95
|
+
export function createDesktopWebRtcWorker({
|
|
96
|
+
command, emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onPeerReady = () => {}, onState = () => {}, log = () => {}, spawnImpl = spawn,
|
|
97
|
+
} = {}) {
|
|
98
|
+
let child = null;
|
|
99
|
+
const NO_PEER_STATE = { needsFallback: true, needsJpeg: true, hasVideo: false, videoLive: false, localCursor: false };
|
|
100
|
+
let state = NO_PEER_STATE;
|
|
101
|
+
const waiting = new Map();
|
|
102
|
+
const peers = new Set();
|
|
103
|
+
|
|
104
|
+
const ensure = () => {
|
|
105
|
+
if (child) return child;
|
|
106
|
+
const [exe, ...args] = command;
|
|
107
|
+
const proc = spawnImpl(exe, [...args, DESKTOP_WEBRTC_WORKER_ARG], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
|
|
108
|
+
child = proc;
|
|
109
|
+
readline.createInterface({ input: proc.stdout }).on('line', (line) => {
|
|
110
|
+
let m;
|
|
111
|
+
try { m = JSON.parse(line); } catch { return; }
|
|
112
|
+
if (m.t === 'signal') emitSignal(m.payload);
|
|
113
|
+
else if (m.t === 'status') emitStatus(m.payload);
|
|
114
|
+
else if (m.t === 'input') onInput(m.raw, m.viewerId);
|
|
115
|
+
else if (m.t === 'peerReady') onPeerReady(m.viewerId);
|
|
116
|
+
else if (m.t === 'state') {
|
|
117
|
+
state = { needsFallback: !!m.needsFallback, needsJpeg: !!m.needsJpeg, hasVideo: !!m.hasVideo, videoLive: !!m.videoLive, localCursor: !!m.localCursor };
|
|
118
|
+
onState();
|
|
119
|
+
}
|
|
120
|
+
else if (m.t === 'log') log(String(m.text || ''));
|
|
121
|
+
else if (m.t === 'started') { waiting.get(m.viewerId)?.(!!m.ok); waiting.delete(m.viewerId); }
|
|
122
|
+
});
|
|
123
|
+
const gone = () => {
|
|
124
|
+
if (child !== proc) return;
|
|
125
|
+
child = null;
|
|
126
|
+
state = NO_PEER_STATE;
|
|
127
|
+
onState();
|
|
128
|
+
for (const done of waiting.values()) done(false);
|
|
129
|
+
waiting.clear();
|
|
130
|
+
peers.clear();
|
|
131
|
+
};
|
|
132
|
+
proc.on('exit', gone);
|
|
133
|
+
proc.on('error', gone);
|
|
134
|
+
proc.stdin.on('error', () => {});
|
|
135
|
+
return proc;
|
|
136
|
+
};
|
|
137
|
+
const send = (msg) => {
|
|
138
|
+
if (!child?.stdin?.writable) return;
|
|
139
|
+
try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* con vừa chết */ }
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
function start({ sessionId, viewerId, iceServers = [], videoBitrate = null }) {
|
|
143
|
+
ensure();
|
|
144
|
+
peers.add(viewerId);
|
|
145
|
+
return new Promise((resolve) => {
|
|
146
|
+
const timer = setTimeout(() => { waiting.delete(viewerId); resolve(false); }, 30_000);
|
|
147
|
+
timer.unref?.();
|
|
148
|
+
waiting.set(viewerId, (ok) => { clearTimeout(timer); resolve(ok); });
|
|
149
|
+
send({ t: 'start', sessionId, viewerId, iceServers, videoBitrate });
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function closeAll() {
|
|
154
|
+
peers.clear();
|
|
155
|
+
if (!child) return;
|
|
156
|
+
const proc = child;
|
|
157
|
+
send({ t: 'closeAll' });
|
|
158
|
+
try { proc.stdin.end(); } catch { /* đã đóng */ }
|
|
159
|
+
// Con tự thoát khi stdin đóng; kẹt thì giết.
|
|
160
|
+
setTimeout(() => { try { proc.kill(); } catch { /* đã thoát */ } }, 3000).unref?.();
|
|
161
|
+
child = null;
|
|
162
|
+
state = NO_PEER_STATE;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
start,
|
|
167
|
+
signal: async (msg) => { send({ t: 'signal', msg }); return true; },
|
|
168
|
+
push: (frame) => { if (child && peers.size) send({ t: 'push', frame }); },
|
|
169
|
+
pushCursor: (cursor) => { if (child && peers.size) send({ t: 'cursor', cursor }); },
|
|
170
|
+
// Hình gửi cả khi chưa có người xem: bộ quay chỉ gửi mỗi hình một lần, tiến trình con giữ lại cho người xem sau.
|
|
171
|
+
pushCursorShape: (shape) => { if (child) send({ t: 'cursorShape', shape }); },
|
|
172
|
+
attachPipe: (name) => { if (name) send({ t: 'pipe', name }); },
|
|
173
|
+
close: (viewerId) => { peers.delete(viewerId); send({ t: 'close', viewerId }); },
|
|
174
|
+
closeAll,
|
|
175
|
+
needsFallback: () => state.needsFallback,
|
|
176
|
+
needsJpeg: () => state.needsJpeg,
|
|
177
|
+
hasVideo: () => state.hasVideo,
|
|
178
|
+
videoLive: () => state.videoLive,
|
|
179
|
+
localCursor: () => state.localCursor,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
@@ -95,6 +95,17 @@ export async function extractDocText(abs, size, maxChars = 600) {
|
|
|
95
95
|
await handle.close();
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
+
if (ext === '.pdf') {
|
|
99
|
+
const handle = await fs.promises.open(abs, 'r');
|
|
100
|
+
try {
|
|
101
|
+
const readLen = Math.min(size, 2 * 1024 * 1024);
|
|
102
|
+
const buf = Buffer.alloc(readLen);
|
|
103
|
+
const { bytesRead } = await handle.read(buf, 0, readLen, 0);
|
|
104
|
+
return extractPdfText(buf.subarray(0, bytesRead), maxChars);
|
|
105
|
+
} finally {
|
|
106
|
+
await handle.close();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
98
109
|
if (!officeParts(ext, ['ppt/slides/slide1.xml']).length || size > MAX_ZIP_BYTES) return '';
|
|
99
110
|
return clean(officeText(await fs.promises.readFile(abs), ext), maxChars);
|
|
100
111
|
} catch {
|
|
@@ -115,3 +126,77 @@ export function wellFormed(text) {
|
|
|
115
126
|
export function isDocFile(abs) {
|
|
116
127
|
return DOC_EXTENSIONS.has(path.extname(abs).toLowerCase());
|
|
117
128
|
}
|
|
129
|
+
|
|
130
|
+
function unescapePdfString(s) {
|
|
131
|
+
return String(s || '')
|
|
132
|
+
.replace(/\\([()\\])/g, '$1')
|
|
133
|
+
.replace(/\\n/g, '\n')
|
|
134
|
+
.replace(/\\r/g, '\r')
|
|
135
|
+
.replace(/\\t/g, '\t')
|
|
136
|
+
.replace(/\\([0-7]{1,3})/g, (_, oct) => String.fromCharCode(parseInt(oct, 8)));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Trích xuất nội dung văn bản từ các stream PDF (hỗ trợ cả stream nén FlateDecode và uncompressed). */
|
|
140
|
+
function extractPdfText(buf, maxChars) {
|
|
141
|
+
if (!buf || buf.length < 8) return '';
|
|
142
|
+
const str = buf.toString('latin1');
|
|
143
|
+
const textPieces = [];
|
|
144
|
+
let totalLen = 0;
|
|
145
|
+
|
|
146
|
+
const streamRe = /stream\r?\n([\s\S]*?)\r?\nendstream/g;
|
|
147
|
+
let m;
|
|
148
|
+
while ((m = streamRe.exec(str)) !== null) {
|
|
149
|
+
if (totalLen >= maxChars * 2) break;
|
|
150
|
+
const streamStart = m.index + m[0].indexOf('\n') + 1;
|
|
151
|
+
const streamEnd = m.index + m[0].lastIndexOf('endstream');
|
|
152
|
+
const streamRaw = buf.subarray(streamStart, Math.max(streamStart, streamEnd));
|
|
153
|
+
const dictSlice = str.slice(Math.max(0, m.index - 300), m.index);
|
|
154
|
+
let decoded = '';
|
|
155
|
+
if (/\/FlateDecode/i.test(dictSlice)) {
|
|
156
|
+
try { decoded = zlib.inflateSync(streamRaw).toString('latin1'); }
|
|
157
|
+
catch { try { decoded = zlib.inflateRawSync(streamRaw).toString('latin1'); } catch { decoded = ''; } }
|
|
158
|
+
} else {
|
|
159
|
+
decoded = streamRaw.toString('latin1');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (!decoded || (!decoded.includes('BT') && !decoded.includes('Tj') && !decoded.includes('TJ'))) continue;
|
|
163
|
+
|
|
164
|
+
const tjRe = /\(((?:[^)\\]|\\.)*)\)\s*(?:Tj|'|")/g;
|
|
165
|
+
let tm;
|
|
166
|
+
while ((tm = tjRe.exec(decoded)) !== null) {
|
|
167
|
+
const parsed = unescapePdfString(tm[1]);
|
|
168
|
+
if (parsed.trim()) {
|
|
169
|
+
textPieces.push(parsed.trim());
|
|
170
|
+
totalLen += parsed.length;
|
|
171
|
+
if (totalLen >= maxChars * 2) break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const arrayTjRe = /\[((?:[^\]\\]|\\.)*)\]\s*TJ/g;
|
|
176
|
+
let am;
|
|
177
|
+
while ((am = arrayTjRe.exec(decoded)) !== null) {
|
|
178
|
+
const innerStr = am[1];
|
|
179
|
+
const innerRe = /\(((?:[^)\\]|\\.)*)\)/g;
|
|
180
|
+
let im;
|
|
181
|
+
while ((im = innerRe.exec(innerStr)) !== null) {
|
|
182
|
+
const parsed = unescapePdfString(im[1]);
|
|
183
|
+
if (parsed.trim()) {
|
|
184
|
+
textPieces.push(parsed.trim());
|
|
185
|
+
totalLen += parsed.length;
|
|
186
|
+
if (totalLen >= maxChars * 2) break;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (!textPieces.length) {
|
|
193
|
+
const rawTj = /\(((?:[^)\\]|\\.)*)\)\s*Tj/g;
|
|
194
|
+
let rm;
|
|
195
|
+
while ((rm = rawTj.exec(str)) !== null) {
|
|
196
|
+
const parsed = unescapePdfString(rm[1]);
|
|
197
|
+
if (parsed.trim()) textPieces.push(parsed.trim());
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return clean(textPieces.join(' '), maxChars);
|
|
202
|
+
}
|