@aixcut/vibevideo 0.0.0-stage → 0.1.0-beta.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/package.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "name": "@aixcut/vibevideo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Local video studio for editable HTML, PixiJS and Three.js graphics",
5
+ "type": "module",
6
+ "bin": { "vibevideo": "bin/vibevideo.mjs" },
7
+ "files": ["bin", "src", "dist", "README.md"],
8
+ "engines": { "node": ">=22" },
9
+ "repository": { "type": "git", "url": "https://github.com/aixcut/vibevideo.git", "directory": "packages/cli" },
10
+ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/", "tag": "beta" },
11
+ "scripts": { "test": "node --test test/*.test.mjs", "prepack": "node ../../scripts/package-cli.mjs" }
12
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,113 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, readFile, rm, writeFile, access } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { parseArgs } from 'node:util';
7
+ import { startServer } from './server.mjs';
8
+ import { initProject, validateProject } from './project.mjs';
9
+
10
+ const root = fileURLToPath(new URL('../', import.meta.url));
11
+ const help = `Vibevideo — local video studio
12
+
13
+ vibevideo Open Studio
14
+ vibevideo init <directory> Create and open a project
15
+ vibevideo open <directory> Open an existing project (autosaves)
16
+ vibevideo doctor Check Node and packaged resources
17
+ vibevideo agent <type> Send a Studio command
18
+
19
+ Options:
20
+ --port <number> Local port (default: automatically selected)
21
+ --no-open Print URL without opening a browser
22
+ --session <file> Connection file for an agent command
23
+ --file <file> Graphic source for agent import
24
+ --seconds <number> Time for agent seek
25
+ --command <file> JSON command for agent scene/object/update
26
+ --json Machine-readable result
27
+ --version, --help
28
+
29
+ The server stays in the foreground. Press Ctrl+C to stop.
30
+ Project directories and exports work best in Chrome or Edge.
31
+ `;
32
+ function openBrowser(url) {
33
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';
34
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
35
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
36
+ child.on('error', () => console.error('Could not open a browser. Open the printed URL manually.'));
37
+ child.unref();
38
+ }
39
+ async function agent(type, values) {
40
+ if (!values.session) throw new Error('Use --session with the connection file printed by Studio.');
41
+ const connection = JSON.parse(await readFile(path.resolve(values.session), 'utf8'));
42
+ const url = new URL(connection.url);
43
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1') throw new Error('Invalid local connection URL');
44
+ async function request(route = '', command) {
45
+ const response = await fetch(`${url.origin}/__vibevideo/agent${route}`, { method: command ? 'POST' : 'GET', headers: { Authorization: `Bearer ${connection.token}`, 'Content-Type': 'application/json' }, body: command ? JSON.stringify(command) : undefined, signal: AbortSignal.timeout(10000) });
46
+ const result = await response.json();
47
+ if (!response.ok) throw new Error(result.error);
48
+ return result;
49
+ }
50
+ if (type === 'status' || !type) return request();
51
+ let command = { type };
52
+ if (values.command) command = JSON.parse(await readFile(path.resolve(values.command), 'utf8'));
53
+ else if (type === 'import') {
54
+ if (!values.file) throw new Error('agent import requires --file');
55
+ command = { type, name: path.basename(values.file), source: await readFile(path.resolve(values.file), 'utf8') };
56
+ } else if (type === 'seek') command.seconds = Number(values.seconds);
57
+ const { id } = await request('', command);
58
+ const deadline = Date.now() + 90000;
59
+ while (Date.now() < deadline) {
60
+ const job = await request(`?job=${encodeURIComponent(id)}`);
61
+ if (job.status === 'complete') return job.result;
62
+ if (job.status === 'failed') throw new Error(JSON.stringify(job.result));
63
+ await new Promise(resolve => setTimeout(resolve, 350));
64
+ }
65
+ throw new Error(`Job ${id} timed out; inspect Studio before retrying.`);
66
+ }
67
+ export async function main(args) {
68
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
69
+ help: { type: 'boolean' }, version: { type: 'boolean' }, json: { type: 'boolean' }, 'no-open': { type: 'boolean' },
70
+ port: { type: 'string' }, session: { type: 'string' }, file: { type: 'string' }, seconds: { type: 'string' }, command: { type: 'string' },
71
+ } });
72
+ const print = value => console.log(JSON.stringify(value, null, values.json ? 0 : 2));
73
+ if (values.help) { console.log(help); return; }
74
+ const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
75
+ if (values.version) { console.log(pkg.version); return; }
76
+ const command = positionals[0] ?? 'studio';
77
+ if (command === 'agent') { print(await agent(positionals[1], values)); return; }
78
+ if (command === 'doctor') {
79
+ const checks = await Promise.all(['dist/studio/index.html', 'dist/studio/sandbox-runtime.js', 'dist/project-template.json'].map(async file => ({ name: file, ok: await access(path.join(root, file)).then(() => true, () => false) })));
80
+ checks.unshift({ name: 'Node.js >=22', ok: Number(process.versions.node.split('.')[0]) >= 22 });
81
+ print({ ok: checks.every(c => c.ok), version: pkg.version, checks, browser: 'Use current Chrome or Edge; codec support is detected during export.' });
82
+ if (!checks.every(c => c.ok)) process.exitCode = 1;
83
+ return;
84
+ }
85
+ if (!['studio', 'init', 'open'].includes(command) || positionals.length > (command === 'studio' ? 1 : 2)) throw new Error('Unknown command or extra arguments. Run vibevideo --help.');
86
+ const port = values.port === undefined ? 0 : Number(values.port);
87
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('--port must be an integer from 0 to 65535');
88
+ let project;
89
+ if (command !== 'studio') {
90
+ if (!positionals[1]) throw new Error(`${command} requires a project directory`);
91
+ project = path.resolve(positionals[1]);
92
+ if (command === 'init') await initProject(project, JSON.parse(await readFile(path.join(root, 'dist/project-template.json'), 'utf8')));
93
+ await validateProject(project);
94
+ }
95
+ const server = await startServer({ studio: path.join(root, 'dist/studio'), project, port });
96
+ const sessions = path.join(homedir(), '.vibevideo', 'sessions');
97
+ const connectionFile = path.join(sessions, `${process.pid}.json`);
98
+ try {
99
+ await mkdir(sessions, { recursive: true, mode: 0o700 });
100
+ await writeFile(connectionFile, JSON.stringify({ url: server.url, token: server.token, project, pid: process.pid }), { mode: 0o600, flag: 'wx' });
101
+ } catch (error) { await server.close(); throw error; }
102
+ const url = `${server.url}/?agent=1`;
103
+ let stopping = false;
104
+ const stop = async () => {
105
+ if (stopping) return;
106
+ stopping = true;
107
+ await server.close(); await rm(connectionFile, { force: true });
108
+ };
109
+ process.once('SIGINT', () => void stop()); process.once('SIGTERM', () => void stop());
110
+ if (values.json) print({ ok: true, url, project: project ?? null, session: connectionFile });
111
+ else console.log(`Studio: ${url}\n${project ? `Project: ${project}\n` : ''}Agent session: ${connectionFile}\nPress Ctrl+C to stop.`);
112
+ if (!values['no-open']) openBrowser(url);
113
+ }
@@ -0,0 +1,19 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ export const manifestName = 'vibevideo.project.json';
5
+ export async function initProject(directory, template) {
6
+ // Refuse existing directories, including nonempty folders without a manifest.
7
+ await mkdir(directory);
8
+ const document = structuredClone(template);
9
+ document.name = path.basename(directory);
10
+ document.timeline.meta.name = document.name;
11
+ document.timeline.meta.createdAt = document.timeline.meta.updatedAt = Date.now();
12
+ await writeFile(path.join(directory, manifestName), JSON.stringify(document, null, 2), { flag: 'wx' });
13
+ }
14
+ export async function validateProject(directory) {
15
+ const document = JSON.parse(await readFile(path.join(directory, manifestName), 'utf8'));
16
+ if (document.format !== 'vibevideo-project-directory' || document.version !== 1 || !document.timeline || !Array.isArray(document.media)) {
17
+ throw new Error(`Invalid Vibevideo project: ${directory}`);
18
+ }
19
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,115 @@
1
+ import { createServer } from 'node:http';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.wasm': 'application/wasm', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.mp4': 'video/mp4' };
7
+ const forbidden = () => Object.assign(new Error('Access denied'), { status: 403 });
8
+ async function safePath(root, relative, allowRoot = false) {
9
+ const parts = relative.split('/');
10
+ if ((!relative && !allowRoot) || path.isAbsolute(relative) || relative.includes('\\') || relative.includes('\0') || parts.some(p => p === '..' || p.startsWith('.'))) throw forbidden();
11
+ let current = root;
12
+ for (const part of parts.filter(Boolean)) {
13
+ current = path.join(current, part);
14
+ const info = await lstat(current).catch(error => { if (error.code !== 'ENOENT') throw error; return null; });
15
+ if (info?.isSymbolicLink()) throw forbidden();
16
+ }
17
+ return current;
18
+ }
19
+ async function body(req, limit) {
20
+ const chunks = []; let length = 0;
21
+ for await (const chunk of req) {
22
+ length += chunk.length;
23
+ if (length > limit) throw Object.assign(new Error('Request is too large'), { status: 413 });
24
+ chunks.push(chunk);
25
+ }
26
+ return Buffer.concat(chunks);
27
+ }
28
+
29
+ export async function startServer({ studio, project, port = 0 }) {
30
+ studio = await realpath(studio);
31
+ if (project) project = await realpath(project);
32
+ const token = randomUUID(), jobs = new Map();
33
+ let heartbeat = 0, editor = null;
34
+ const server = createServer(async (req, res) => {
35
+ const json = (status, value) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); };
36
+ try {
37
+ const host = `127.0.0.1:${server.address().port}`;
38
+ if (req.headers.host !== host || (req.headers.origin && req.headers.origin !== `http://${host}`) || req.headers['sec-fetch-site'] === 'cross-site') throw forbidden();
39
+ const url = new URL(req.url, `http://${host}`);
40
+ if (url.pathname === '/__vibevideo/session' && req.method === 'GET') {
41
+ json(200, { token, project: project ? path.basename(project) : null }); return;
42
+ }
43
+ if (url.pathname.startsWith('/__vibevideo/')) {
44
+ if (req.headers.authorization !== `Bearer ${token}`) throw forbidden();
45
+ if (url.pathname === '/__vibevideo/fs') {
46
+ if (!project) throw forbidden();
47
+ const file = await safePath(project, url.searchParams.get('path') ?? '', req.method === 'GET');
48
+ if (req.method === 'GET') {
49
+ const info = await stat(file);
50
+ if (info.isDirectory()) {
51
+ const entries = await readdir(file, { withFileTypes: true });
52
+ json(200, entries.filter(e => !e.name.startsWith('.') && !e.isSymbolicLink()).map(e => ({ name: e.name, kind: e.isDirectory() ? 'directory' : 'file' }))); return;
53
+ }
54
+ res.writeHead(200, { 'Content-Type': mime[path.extname(file)] ?? 'application/octet-stream', 'X-Last-Modified': String(info.mtimeMs), 'Cache-Control': 'no-store' });
55
+ res.end(await readFile(file)); return;
56
+ }
57
+ if (req.method === 'PUT') {
58
+ if (url.searchParams.get('kind') === 'directory') await mkdir(file, { recursive: true });
59
+ else {
60
+ const data = await body(req, 256 * 1024 * 1024);
61
+ await mkdir(path.dirname(file), { recursive: true });
62
+ const temporary = path.join(path.dirname(file), `.vibevideo-${randomUUID()}.tmp`);
63
+ try {
64
+ await writeFile(temporary, data, { flag: 'wx' });
65
+ await rename(temporary, file);
66
+ } finally { await rm(temporary, { force: true }); }
67
+ }
68
+ json(200, { ok: true }); return;
69
+ }
70
+ }
71
+ if (url.pathname.startsWith('/__vibevideo/agent')) {
72
+ const route = url.pathname.slice('/__vibevideo/agent'.length);
73
+ if (req.method === 'GET') {
74
+ if (route === '/next') {
75
+ heartbeat = Date.now();
76
+ const job = [...jobs.values()].find(j => j.status === 'queued');
77
+ if (job) job.status = 'running';
78
+ json(200, job ?? null);
79
+ } else if (url.searchParams.has('job')) {
80
+ const job = jobs.get(url.searchParams.get('job'));
81
+ json(job ? 200 : 404, job ?? { error: 'Job not found' });
82
+ } else json(200, { connected: Date.now() - heartbeat < 5000, editor });
83
+ return;
84
+ }
85
+ if (req.method === 'POST') {
86
+ const input = JSON.parse((await body(req, 8 * 1024 * 1024)).toString());
87
+ if (route === '/result') {
88
+ const job = jobs.get(input.id);
89
+ if (!job || job.status !== 'running') { json(409, { error: 'Job is not running' }); return; }
90
+ job.status = input.ok ? 'complete' : 'failed'; job.result = input.result; editor = input.state; delete job.command;
91
+ json(200, { ok: true }); return;
92
+ }
93
+ if (Date.now() - heartbeat >= 5000) { json(409, { error: 'Studio is not connected; open the printed URL first' }); return; }
94
+ if (!['import', 'seek', 'play', 'pause', 'inspect', 'scene', 'object', 'update'].includes(input.type)) { json(400, { error: 'Unknown command' }); return; }
95
+ if (input.type === 'import' && (typeof input.name !== 'string' || typeof input.source !== 'string')) { json(400, { error: 'Import requires name and source' }); return; }
96
+ if (input.type === 'seek' && (!Number.isFinite(input.seconds) || input.seconds < 0)) { json(400, { error: 'Invalid seek time' }); return; }
97
+ for (const [id, job] of jobs) if (jobs.size >= 100 && ['complete', 'failed'].includes(job.status)) jobs.delete(id);
98
+ if (jobs.size >= 100) { json(429, { error: 'Mailbox full' }); return; }
99
+ const id = randomUUID(); jobs.set(id, { id, command: input, status: 'queued' }); json(202, { id }); return;
100
+ }
101
+ }
102
+ json(404, { error: 'Unknown API route' }); return;
103
+ }
104
+ if (!['GET', 'HEAD'].includes(req.method)) { json(405, { error: 'Method not allowed' }); return; }
105
+ const file = await safePath(studio, decodeURIComponent(url.pathname).slice(1) || 'index.html');
106
+ const data = await readFile(file);
107
+ res.writeHead(200, { 'Content-Type': mime[path.extname(file)] ?? 'application/octet-stream', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' });
108
+ res.end(req.method === 'HEAD' ? undefined : data);
109
+ } catch (error) {
110
+ json(error.status ?? (error.code === 'ENOENT' ? 404 : 500), { error: error.status === 403 ? 'Access denied' : error.code === 'ENOENT' ? 'File not found' : error.message });
111
+ }
112
+ });
113
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
114
+ return { url: `http://127.0.0.1:${server.address().port}`, token, close: () => new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeIdleConnections(); }) };
115
+ }