codemotion-studio 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @license React
3
+ * react.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */
10
+ (function(){'use strict';(function(c,x){"object"===typeof exports&&"undefined"!==typeof module?x(exports):"function"===typeof define&&define.amd?define(["exports"],x):(c=c||self,x(c.React={}))})(this,function(c){function x(a){if(null===a||"object"!==typeof a)return null;a=V&&a[V]||a["@@iterator"];return"function"===typeof a?a:null}function w(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Y(){}function K(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Z(a,b,
11
+ e){var m,d={},c=null,h=null;if(null!=b)for(m in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(c=""+b.key),b)aa.call(b,m)&&!ba.hasOwnProperty(m)&&(d[m]=b[m]);var l=arguments.length-2;if(1===l)d.children=e;else if(1<l){for(var f=Array(l),k=0;k<l;k++)f[k]=arguments[k+2];d.children=f}if(a&&a.defaultProps)for(m in l=a.defaultProps,l)void 0===d[m]&&(d[m]=l[m]);return{$$typeof:y,type:a,key:c,ref:h,props:d,_owner:L.current}}function oa(a,b){return{$$typeof:y,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}
12
+ function M(a){return"object"===typeof a&&null!==a&&a.$$typeof===y}function pa(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}function N(a,b){return"object"===typeof a&&null!==a&&null!=a.key?pa(""+a.key):b.toString(36)}function B(a,b,e,m,d){var c=typeof a;if("undefined"===c||"boolean"===c)a=null;var h=!1;if(null===a)h=!0;else switch(c){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case y:case qa:h=!0}}if(h)return h=a,d=d(h),a=""===m?"."+
13
+ N(h,0):m,ca(d)?(e="",null!=a&&(e=a.replace(da,"$&/")+"/"),B(d,b,e,"",function(a){return a})):null!=d&&(M(d)&&(d=oa(d,e+(!d.key||h&&h.key===d.key?"":(""+d.key).replace(da,"$&/")+"/")+a)),b.push(d)),1;h=0;m=""===m?".":m+":";if(ca(a))for(var l=0;l<a.length;l++){c=a[l];var f=m+N(c,l);h+=B(c,b,e,f,d)}else if(f=x(a),"function"===typeof f)for(a=f.call(a),l=0;!(c=a.next()).done;)c=c.value,f=m+N(c,l++),h+=B(c,b,e,f,d);else if("object"===c)throw b=String(a),Error("Objects are not valid as a React child (found: "+
14
+ ("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}function C(a,b,e){if(null==a)return a;var c=[],d=0;B(a,c,"","",function(a){return b.call(e,a,d++)});return c}function ra(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=
15
+ 0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}function O(a,b){var e=a.length;a.push(b);a:for(;0<e;){var c=e-1>>>1,d=a[c];if(0<D(d,b))a[c]=b,a[e]=d,e=c;else break a}}function p(a){return 0===a.length?null:a[0]}function E(a){if(0===a.length)return null;var b=a[0],e=a.pop();if(e!==b){a[0]=e;a:for(var c=0,d=a.length,k=d>>>1;c<k;){var h=2*(c+1)-1,l=a[h],f=h+1,g=a[f];if(0>D(l,e))f<d&&0>D(g,l)?(a[c]=g,a[f]=e,c=f):(a[c]=l,a[h]=e,c=h);else if(f<d&&0>D(g,e))a[c]=g,a[f]=e,c=f;else break a}}return b}
16
+ function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function P(a){for(var b=p(r);null!==b;){if(null===b.callback)E(r);else if(b.startTime<=a)E(r),b.sortIndex=b.expirationTime,O(q,b);else break;b=p(r)}}function Q(a){z=!1;P(a);if(!u)if(null!==p(q))u=!0,R(S);else{var b=p(r);null!==b&&T(Q,b.startTime-a)}}function S(a,b){u=!1;z&&(z=!1,ea(A),A=-1);F=!0;var c=k;try{P(b);for(n=p(q);null!==n&&(!(n.expirationTime>b)||a&&!fa());){var m=n.callback;if("function"===typeof m){n.callback=null;
17
+ k=n.priorityLevel;var d=m(n.expirationTime<=b);b=v();"function"===typeof d?n.callback=d:n===p(q)&&E(q);P(b)}else E(q);n=p(q)}if(null!==n)var g=!0;else{var h=p(r);null!==h&&T(Q,h.startTime-b);g=!1}return g}finally{n=null,k=c,F=!1}}function fa(){return v()-ha<ia?!1:!0}function R(a){G=a;H||(H=!0,I())}function T(a,b){A=ja(function(){a(v())},b)}function ka(a){throw Error("act(...) is not supported in production builds of React.");}var y=Symbol.for("react.element"),qa=Symbol.for("react.portal"),sa=Symbol.for("react.fragment"),
18
+ ta=Symbol.for("react.strict_mode"),ua=Symbol.for("react.profiler"),va=Symbol.for("react.provider"),wa=Symbol.for("react.context"),xa=Symbol.for("react.forward_ref"),ya=Symbol.for("react.suspense"),za=Symbol.for("react.memo"),Aa=Symbol.for("react.lazy"),V=Symbol.iterator,X={isMounted:function(a){return!1},enqueueForceUpdate:function(a,b,c){},enqueueReplaceState:function(a,b,c,m){},enqueueSetState:function(a,b,c,m){}},la=Object.assign,W={};w.prototype.isReactComponent={};w.prototype.setState=function(a,
19
+ b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState")};w.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};Y.prototype=w.prototype;var t=K.prototype=new Y;t.constructor=K;la(t,w.prototype);t.isPureReactComponent=!0;var ca=Array.isArray,aa=Object.prototype.hasOwnProperty,L={current:null},
20
+ ba={key:!0,ref:!0,__self:!0,__source:!0},da=/\/+/g,g={current:null},J={transition:null};if("object"===typeof performance&&"function"===typeof performance.now){var Ba=performance;var v=function(){return Ba.now()}}else{var ma=Date,Ca=ma.now();v=function(){return ma.now()-Ca}}var q=[],r=[],Da=1,n=null,k=3,F=!1,u=!1,z=!1,ja="function"===typeof setTimeout?setTimeout:null,ea="function"===typeof clearTimeout?clearTimeout:null,na="undefined"!==typeof setImmediate?setImmediate:null;"undefined"!==typeof navigator&&
21
+ void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var H=!1,G=null,A=-1,ia=5,ha=-1,U=function(){if(null!==G){var a=v();ha=a;var b=!0;try{b=G(!0,a)}finally{b?I():(H=!1,G=null)}}else H=!1};if("function"===typeof na)var I=function(){na(U)};else if("undefined"!==typeof MessageChannel){t=new MessageChannel;var Ea=t.port2;t.port1.onmessage=U;I=function(){Ea.postMessage(null)}}else I=function(){ja(U,0)};t={ReactCurrentDispatcher:g,
22
+ ReactCurrentOwner:L,ReactCurrentBatchConfig:J,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=k;k=a;try{return b()}finally{k=c}},unstable_next:function(a){switch(k){case 1:case 2:case 3:var b=3;break;default:b=k}var c=k;k=b;try{return a()}finally{k=c}},unstable_scheduleCallback:function(a,
23
+ b,c){var e=v();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?e+c:e):c=e;switch(a){case 1:var d=-1;break;case 2:d=250;break;case 5:d=1073741823;break;case 4:d=1E4;break;default:d=5E3}d=c+d;a={id:Da++,callback:b,priorityLevel:a,startTime:c,expirationTime:d,sortIndex:-1};c>e?(a.sortIndex=c,O(r,a),null===p(q)&&a===p(r)&&(z?(ea(A),A=-1):z=!0,T(Q,c-e))):(a.sortIndex=d,O(q,a),u||F||(u=!0,R(S)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b=
24
+ k;return function(){var c=k;k=b;try{return a.apply(this,arguments)}finally{k=c}}},unstable_getCurrentPriorityLevel:function(){return k},unstable_shouldYield:fa,unstable_requestPaint:function(){},unstable_continueExecution:function(){u||F||(u=!0,R(S))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return p(q)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):
25
+ ia=0<a?Math.floor(1E3/a):5},unstable_Profiling:null}};c.Children={map:C,forEach:function(a,b,c){C(a,function(){b.apply(this,arguments)},c)},count:function(a){var b=0;C(a,function(){b++});return b},toArray:function(a){return C(a,function(a){return a})||[]},only:function(a){if(!M(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};c.Component=w;c.Fragment=sa;c.Profiler=ua;c.PureComponent=K;c.StrictMode=ta;c.Suspense=ya;c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=
26
+ t;c.act=ka;c.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var e=la({},a.props),d=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=L.current);void 0!==b.key&&(d=""+b.key);if(a.type&&a.type.defaultProps)var l=a.type.defaultProps;for(f in b)aa.call(b,f)&&!ba.hasOwnProperty(f)&&(e[f]=void 0===b[f]&&void 0!==l?l[f]:b[f])}var f=arguments.length-2;if(1===f)e.children=c;else if(1<f){l=
27
+ Array(f);for(var g=0;g<f;g++)l[g]=arguments[g+2];e.children=l}return{$$typeof:y,type:a.type,key:d,ref:k,props:e,_owner:h}};c.createContext=function(a){a={$$typeof:wa,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:va,_context:a};return a.Consumer=a};c.createElement=Z;c.createFactory=function(a){var b=Z.bind(null,a);b.type=a;return b};c.createRef=function(){return{current:null}};c.forwardRef=function(a){return{$$typeof:xa,
28
+ render:a}};c.isValidElement=M;c.lazy=function(a){return{$$typeof:Aa,_payload:{_status:-1,_result:a},_init:ra}};c.memo=function(a,b){return{$$typeof:za,type:a,compare:void 0===b?null:b}};c.startTransition=function(a,b){b=J.transition;J.transition={};try{a()}finally{J.transition=b}};c.unstable_act=ka;c.useCallback=function(a,b){return g.current.useCallback(a,b)};c.useContext=function(a){return g.current.useContext(a)};c.useDebugValue=function(a,b){};c.useDeferredValue=function(a){return g.current.useDeferredValue(a)};
29
+ c.useEffect=function(a,b){return g.current.useEffect(a,b)};c.useId=function(){return g.current.useId()};c.useImperativeHandle=function(a,b,c){return g.current.useImperativeHandle(a,b,c)};c.useInsertionEffect=function(a,b){return g.current.useInsertionEffect(a,b)};c.useLayoutEffect=function(a,b){return g.current.useLayoutEffect(a,b)};c.useMemo=function(a,b){return g.current.useMemo(a,b)};c.useReducer=function(a,b,c){return g.current.useReducer(a,b,c)};c.useRef=function(a){return g.current.useRef(a)};
30
+ c.useState=function(a){return g.current.useState(a)};c.useSyncExternalStore=function(a,b,c){return g.current.useSyncExternalStore(a,b,c)};c.useTransition=function(){return g.current.useTransition()};c.version="18.3.1"});
31
+ })();
@@ -0,0 +1,25 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
6
+ const outDir = path.join(root, 'public', 'vendor');
7
+ fs.mkdirSync(outDir, { recursive: true });
8
+
9
+ const files = [
10
+ ['react/umd/react.development.js', 'react.development.js'],
11
+ ['react/umd/react.production.min.js', 'react.production.min.js'],
12
+ ['react-dom/umd/react-dom.development.js', 'react-dom.development.js'],
13
+ ['react-dom/umd/react-dom.production.min.js', 'react-dom.production.min.js'],
14
+ ['@babel/standalone/babel.min.js', 'babel.min.js']
15
+ ];
16
+
17
+ for (const [from, to] of files) {
18
+ const src = path.join(root, 'node_modules', from);
19
+ if (!fs.existsSync(src)) {
20
+ console.warn(`[vendor] lewat: ${from} tidak ditemukan (jalankan npm install)`);
21
+ continue;
22
+ }
23
+ fs.copyFileSync(src, path.join(outDir, to));
24
+ }
25
+ console.log(`[vendor] runtime browser disalin ke public/vendor (${files.length} file)`);
package/server/cli.js ADDED
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ // Headless render, Remotion-style:
3
+ // npm run render -- project.framecode.json --res=1080p
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { renderProject, startVendorServer } from './renderer.js';
8
+ import { RENDER_RESOLUTIONS } from '../src/lib/constants.js';
9
+
10
+ const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
11
+ const args = process.argv.slice(2);
12
+ const file = args.find((a) => !a.startsWith('--'));
13
+ const flag = (name, fallback) => {
14
+ const hit = args.find((a) => a.startsWith(`--${name}=`));
15
+ return hit ? hit.split('=')[1] : fallback;
16
+ };
17
+
18
+ if (!file) {
19
+ console.error('Pakai: npm run render -- <project.framecode.json> [--res=1080p] [--fps=30]');
20
+ process.exit(1);
21
+ }
22
+
23
+ const project = JSON.parse(fs.readFileSync(path.resolve(file), 'utf8'));
24
+ const resKey = flag('res', '');
25
+ if (RENDER_RESOLUTIONS[resKey]) project.resolution = RENDER_RESOLUTIONS[resKey];
26
+ project.fps = Number(flag('fps', project.fps || 30));
27
+
28
+ const vendor = await startVendorServer(path.join(rootDir, 'public'));
29
+ try {
30
+ const result = await renderProject(project, {
31
+ baseUrl: vendor.url,
32
+ outDir: path.join(rootDir, 'renders'),
33
+ onProgress: ({ frame, total, scene }) => {
34
+ process.stdout.write(`\r render ${frame}/${total} ${scene} `);
35
+ }
36
+ });
37
+ process.stdout.write('\n');
38
+ console.log(`Selesai: ${result.path}`);
39
+ } finally {
40
+ await vendor.close();
41
+ }
@@ -0,0 +1,261 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import express from 'express';
5
+ import { renderProject } from './renderer.js';
6
+
7
+ const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
8
+ const rendersDir = path.join(rootDir, 'renders');
9
+ const prod = process.argv.includes('--prod');
10
+ const port = Number(process.env.PORT) || 3333;
11
+
12
+ const c = {
13
+ reset: '\x1b[0m',
14
+ dim: '\x1b[2m',
15
+ bold: '\x1b[1m',
16
+ cyan: '\x1b[36m',
17
+ sky: '\x1b[96m',
18
+ green: '\x1b[32m',
19
+ yellow: '\x1b[33m',
20
+ red: '\x1b[31m',
21
+ magenta: '\x1b[35m'
22
+ };
23
+
24
+ function timestamp() {
25
+ return new Date().toTimeString().slice(0, 8);
26
+ }
27
+
28
+ function log(level, color, tag, message) {
29
+ console.log(
30
+ `${c.dim}[${timestamp()}]${c.reset} ${color}${c.bold}[${tag}]${c.reset} ${message}`
31
+ );
32
+ }
33
+
34
+ function printBanner() {
35
+ const banner = `
36
+ ${c.sky}${c.bold} ______ __ __ ___ __ _
37
+ / ____/___ ____/ /__ / |/ /___ / /_(_)___ ____
38
+ / / / __ \\/ __ / _ \\/ /|_/ / __ \\/ __/ / __ \\/ __ \\
39
+ / /___/ /_/ / /_/ / __/ / / / /_/ / /_/ / /_/ / / / /
40
+ \\____/\\____/\\__,_/\\___/_/ /_/\\____/\\__/_/\\____/_/ /_/${c.reset}
41
+ ${c.dim} Programmatic HTML/CSS/JS Video Studio • React UI • Puppeteer + FFmpeg${c.reset}
42
+ `;
43
+ console.log(banner);
44
+ console.log(` ${c.bold}Local:${c.reset} ${c.sky}http://localhost:${port}${c.reset}`);
45
+ console.log(` ${c.bold}Mode:${c.reset} ${prod ? `${c.green}production${c.reset}` : `${c.yellow}development (HMR)${c.reset}`}`);
46
+ console.log(` ${c.bold}Renders:${c.reset} ${c.dim}${rendersDir}${c.reset}\n`);
47
+ }
48
+
49
+ const app = express();
50
+ app.use(express.json({ limit: '250mb' }));
51
+
52
+ // Request logger for API, health, renders, and main document
53
+ app.use((req, res, next) => {
54
+ const isAsset =
55
+ req.path === '/health' ||
56
+ req.path === '/favicon.ico' ||
57
+ req.path.startsWith('/src/') ||
58
+ req.path.startsWith('/node_modules/') ||
59
+ req.path.startsWith('/@') ||
60
+ req.path.startsWith('/vendor/');
61
+ if (isAsset) return next();
62
+
63
+ const start = Date.now();
64
+ res.on('finish', () => {
65
+ const ms = Date.now() - start;
66
+ const statusColor =
67
+ res.statusCode >= 500 ? c.red : res.statusCode >= 400 ? c.yellow : c.green;
68
+ log(
69
+ 'http',
70
+ c.cyan,
71
+ 'HTTP',
72
+ `${req.method} ${req.originalUrl} ${statusColor}${res.statusCode}${c.reset} ${c.dim}(${ms}ms)${c.reset}`
73
+ );
74
+ });
75
+ next();
76
+ });
77
+
78
+ app.get('/health', (req, res) => {
79
+ res.json({ status: 'ok', engine: 'CodeMotion local renderer (Puppeteer + FFmpeg)' });
80
+ });
81
+
82
+ app.use('/renders', express.static(rendersDir));
83
+
84
+ app.post('/api/ai', async (req, res) => {
85
+ const {
86
+ provider = 'openai',
87
+ baseUrl = 'https://api.openai.com/v1/chat/completions',
88
+ apiKey = '',
89
+ model = 'gpt-4o-mini',
90
+ messages = []
91
+ } = req.body || {};
92
+
93
+ if (!apiKey && !String(baseUrl).includes('localhost') && !String(baseUrl).includes('127.0.0.1')) {
94
+ return res.status(400).json({ error: 'API Key belum diisi.' });
95
+ }
96
+
97
+ log('info', c.cyan, 'AI', `Request -> ${provider} (${model})`);
98
+
99
+ try {
100
+ if (provider === 'gemini') {
101
+ const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
102
+ const systemMsg = messages.find((m) => m.role === 'system')?.content || '';
103
+ const contents = messages
104
+ .filter((m) => m.role !== 'system')
105
+ .map((m) => ({
106
+ role: m.role === 'assistant' ? 'model' : 'user',
107
+ parts: [{ text: m.content }]
108
+ }));
109
+
110
+ const response = await fetch(endpoint, {
111
+ method: 'POST',
112
+ headers: { 'Content-Type': 'application/json' },
113
+ body: JSON.stringify({
114
+ ...(systemMsg ? { systemInstruction: { parts: [{ text: systemMsg }] } } : {}),
115
+ contents,
116
+ generationConfig: { temperature: 0.7 }
117
+ })
118
+ });
119
+ const data = await response.json();
120
+ if (!response.ok) {
121
+ const msg = data?.error?.message || `Gemini HTTP ${response.status}`;
122
+ log('error', c.red, 'AI', msg);
123
+ return res.status(response.status).json({ error: msg });
124
+ }
125
+ const reply = data?.candidates?.[0]?.content?.parts?.map((p) => p.text || '').join('') || '';
126
+ log('info', c.green, 'AI', `Response received (${reply.length} chars)`);
127
+ return res.json({ reply });
128
+ }
129
+
130
+ // OpenAI-compatible (OpenAI, Groq, OpenRouter, DeepSeek, Ollama, etc.)
131
+ const headers = { 'Content-Type': 'application/json' };
132
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
133
+
134
+ const response = await fetch(baseUrl, {
135
+ method: 'POST',
136
+ headers,
137
+ body: JSON.stringify({ model, messages, temperature: 0.7 })
138
+ });
139
+ const data = await response.json();
140
+ if (!response.ok) {
141
+ const msg = data?.error?.message || `AI HTTP ${response.status}`;
142
+ log('error', c.red, 'AI', msg);
143
+ return res.status(response.status).json({ error: msg });
144
+ }
145
+ const reply = data?.choices?.[0]?.message?.content || '';
146
+ log('info', c.green, 'AI', `Response received (${reply.length} chars)`);
147
+ return res.json({ reply });
148
+ } catch (err) {
149
+ const msg = err?.message || String(err);
150
+ log('error', c.red, 'AI', `Connection failed: ${msg}`);
151
+ return res.status(500).json({ error: msg });
152
+ }
153
+ });
154
+
155
+ app.post('/api/render', async (req, res) => {
156
+ res.setHeader('Content-Type', 'application/x-ndjson');
157
+ res.setHeader('Cache-Control', 'no-cache');
158
+ res.setHeader('X-Accel-Buffering', 'no');
159
+
160
+ const send = (msg) => res.write(`${JSON.stringify(msg)}\n`);
161
+ const controller = new AbortController();
162
+ res.on('close', () => {
163
+ if (!res.writableEnded) {
164
+ log('warn', c.yellow, 'RENDER', 'Client disconnected — aborting render');
165
+ controller.abort();
166
+ }
167
+ });
168
+
169
+ const started = Date.now();
170
+ const project = req.body || {};
171
+ const sceneCount = Array.isArray(project.scenes) ? project.scenes.length : 0;
172
+ const resLabel = project.resolution
173
+ ? `${project.resolution.width}x${project.resolution.height}`
174
+ : '1920x1080';
175
+ const fpsVal = project.fps || 30;
176
+
177
+ log(
178
+ 'info',
179
+ c.magenta,
180
+ 'RENDER',
181
+ `Starting "${project.projectName || project.name || 'video'}" (${sceneCount} scenes, ${resLabel} @ ${fpsVal}fps)`
182
+ );
183
+
184
+ let lastLoggedPct = -1;
185
+ try {
186
+ const result = await renderProject(project, {
187
+ baseUrl: `http://127.0.0.1:${port}`,
188
+ outDir: rendersDir,
189
+ signal: controller.signal,
190
+ onLog: ({ level = 'info', message }) => {
191
+ const color = level === 'error' ? c.red : level === 'warn' ? c.yellow : c.magenta;
192
+ const tag = level === 'error' ? 'ERROR' : 'RENDER';
193
+ log(level, color, tag, message);
194
+ send({ type: 'log', level, message });
195
+ },
196
+ onProgress: (p) => {
197
+ send({ type: 'progress', ...p });
198
+ if (typeof p.frame === 'number' && typeof p.total === 'number' && p.total > 0) {
199
+ const pct = Math.round((p.frame / p.total) * 100);
200
+ const bucket = Math.floor(pct / 25) * 25;
201
+ if (bucket > lastLoggedPct && bucket > 0) {
202
+ lastLoggedPct = bucket;
203
+ log(
204
+ 'info',
205
+ c.magenta,
206
+ 'RENDER',
207
+ `Progress ${pct}% — frame ${p.frame}/${p.total} (${p.scene})`
208
+ );
209
+ }
210
+ }
211
+ }
212
+ });
213
+ const elapsedMs = Date.now() - started;
214
+ log(
215
+ 'info',
216
+ c.green,
217
+ 'RENDER',
218
+ `Done: ${result.file} (${result.totalFrames} frames in ${(elapsedMs / 1000).toFixed(1)}s)`
219
+ );
220
+ send({
221
+ type: 'done',
222
+ url: `/renders/${encodeURIComponent(result.file)}`,
223
+ fileName: result.file,
224
+ filePath: result.path,
225
+ totalFrames: result.totalFrames,
226
+ elapsedMs
227
+ });
228
+ } catch (err) {
229
+ const message = err?.message || String(err);
230
+ log('error', c.red, 'RENDER', `Failed: ${message}`);
231
+ send({ type: 'error', message });
232
+ } finally {
233
+ res.end();
234
+ }
235
+ });
236
+
237
+ if (prod) {
238
+ const dist = path.join(rootDir, 'dist');
239
+ if (!fs.existsSync(path.join(dist, 'index.html'))) {
240
+ log('error', c.red, 'BOOT', 'dist/ belum ada. Jalankan "npm run build" dulu.');
241
+ process.exit(1);
242
+ }
243
+ app.use(express.static(dist));
244
+ app.get('*', (req, res) => res.sendFile(path.join(dist, 'index.html')));
245
+ } else {
246
+ log('info', c.cyan, 'VITE', 'Starting Vite dev middleware...');
247
+ const { createServer } = await import('vite');
248
+ const vite = await createServer({
249
+ root: rootDir,
250
+ server: { middlewareMode: true },
251
+ appType: 'spa'
252
+ });
253
+ app.use(vite.middlewares);
254
+ log('info', c.green, 'VITE', 'Vite HMR middleware ready');
255
+ }
256
+
257
+ app.listen(port, '127.0.0.1', () => {
258
+ printBanner();
259
+ log('info', c.green, 'SERVER', `Listening on http://127.0.0.1:${port}`);
260
+ log('info', c.cyan, 'READY', 'Waiting for connections and render jobs...');
261
+ });
@@ -0,0 +1,180 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import http from 'node:http';
4
+ import { spawn } from 'node:child_process';
5
+ import puppeteer from 'puppeteer';
6
+ import ffmpegPath from 'ffmpeg-static';
7
+ import { buildSceneDocument, transitionAt } from '../src/lib/sceneDocument.js';
8
+
9
+ const MIME = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html' };
10
+
11
+ // Minimal static server for /vendor so the CLI can render without the app running.
12
+ export function startVendorServer(rootDir) {
13
+ const server = http.createServer((req, res) => {
14
+ const file = path.join(rootDir, decodeURIComponent((req.url || '/').split('?')[0]));
15
+ if (!file.startsWith(rootDir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
16
+ res.writeHead(404).end('not found');
17
+ return;
18
+ }
19
+ res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream' });
20
+ fs.createReadStream(file).pipe(res);
21
+ });
22
+ return new Promise((resolve) => {
23
+ server.listen(0, '127.0.0.1', () => {
24
+ const { port } = server.address();
25
+ resolve({
26
+ url: `http://127.0.0.1:${port}`,
27
+ close: () => new Promise((done) => server.close(done))
28
+ });
29
+ });
30
+ });
31
+ }
32
+
33
+ function sanitize(name) {
34
+ return String(name || 'output').replace(/[^\w.-]+/g, '_').slice(0, 80);
35
+ }
36
+
37
+ function spawnFfmpeg(outFile, fps, crf) {
38
+ const proc = spawn(
39
+ ffmpegPath,
40
+ [
41
+ '-y',
42
+ '-f', 'image2pipe',
43
+ '-framerate', String(fps),
44
+ '-i', '-',
45
+ '-c:v', 'libx264',
46
+ '-preset', 'veryfast',
47
+ '-crf', String(crf),
48
+ '-pix_fmt', 'yuv420p',
49
+ '-movflags', '+faststart',
50
+ outFile
51
+ ],
52
+ { stdio: ['pipe', 'ignore', 'pipe'] }
53
+ );
54
+ let stderr = '';
55
+ proc.stderr.on('data', (d) => {
56
+ stderr += d.toString();
57
+ if (stderr.length > 20000) stderr = stderr.slice(-20000);
58
+ });
59
+ const exited = new Promise((resolve, reject) => {
60
+ proc.on('error', reject);
61
+ proc.on('close', (code) =>
62
+ code === 0 ? resolve() : reject(new Error(`FFmpeg keluar dengan kode ${code}\n${stderr}`))
63
+ );
64
+ });
65
+ const write = (buf) =>
66
+ new Promise((resolve, reject) => {
67
+ if (proc.stdin.destroyed) return reject(new Error('FFmpeg pipe tertutup'));
68
+ if (proc.stdin.write(buf)) return resolve();
69
+ const onDrain = () => {
70
+ proc.stdin.off('error', onError);
71
+ resolve();
72
+ };
73
+ const onError = (err) => {
74
+ proc.stdin.off('drain', onDrain);
75
+ reject(err);
76
+ };
77
+ proc.stdin.once('drain', onDrain);
78
+ proc.stdin.once('error', onError);
79
+ });
80
+ return { proc, write, exited };
81
+ }
82
+
83
+ export async function renderProject(project, { baseUrl, outDir, onProgress, onLog, signal }) {
84
+ const { projectName = 'output', scenes = [], assets = [] } = project;
85
+ const fps = Number(project.fps) || 30;
86
+ const width = Number(project.resolution?.width) || 1920;
87
+ const height = Number(project.resolution?.height) || 1080;
88
+
89
+ if (!scenes.length) throw new Error('Proyek tidak punya scene untuk dirender.');
90
+
91
+ fs.mkdirSync(outDir, { recursive: true });
92
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
93
+ const fileName = `${sanitize(projectName)}_${stamp}.mp4`;
94
+ const outFile = path.join(outDir, fileName);
95
+
96
+ const frameCounts = scenes.map((s) => Math.max(1, Math.round((s.duration || 1) * fps)));
97
+ const totalFrames = frameCounts.reduce((a, b) => a + b, 0);
98
+
99
+ const crf = width >= 3000 ? 20 : 18;
100
+ onLog?.({ level: 'info', message: `Menyiapkan FFmpeg (H.264, CRF ${crf}, ${width}x${height} @ ${fps}fps)` });
101
+ const ffmpeg = spawnFfmpeg(outFile, fps, crf);
102
+
103
+ onLog?.({ level: 'info', message: 'Membuka headless Chromium (Puppeteer)...' });
104
+ const browser = await puppeteer.launch({
105
+ headless: true,
106
+ args: ['--hide-scrollbars', '--font-render-hinting=none', '--disable-lcd-text']
107
+ });
108
+
109
+ let rendered = 0;
110
+ try {
111
+ for (let si = 0; si < scenes.length; si++) {
112
+ const scene = scenes[si];
113
+ onLog?.({ level: 'info', message: `Memuat scene ${si + 1}/${scenes.length}: ${scene.name} (${frameCounts[si]} frames)` });
114
+ const page = await browser.newPage();
115
+ page.on('pageerror', (err) => {
116
+ onLog?.({ level: 'error', message: `[${scene.name}] Page Error: ${err?.message || err}` });
117
+ });
118
+ page.on('console', (msg) => {
119
+ if (msg.type() === 'error') {
120
+ onLog?.({ level: 'error', message: `[${scene.name}] Console Error: ${msg.text()}` });
121
+ }
122
+ });
123
+ await page.setViewport({ width, height, deviceScaleFactor: 1 });
124
+ const doc = buildSceneDocument(scene, {
125
+ width,
126
+ height,
127
+ fps,
128
+ assets,
129
+ mode: 'render',
130
+ baseUrl
131
+ });
132
+ await page.setContent(doc, { waitUntil: 'load', timeout: 60000 });
133
+ await page.waitForFunction('window.__FC_READY === true', { timeout: 30000 });
134
+ await page.evaluate(() => (document.fonts ? document.fonts.ready : Promise.resolve()));
135
+
136
+ for (let f = 0; f < frameCounts[si]; f++) {
137
+ if (signal?.aborted) throw new Error('Render dibatalkan.');
138
+ const localTime = f / fps;
139
+ const progress = f / frameCounts[si];
140
+ const transitionStyle = transitionAt(scene, localTime);
141
+
142
+ await page.evaluate(
143
+ (time, prog, frame, transition) => {
144
+ window.__FC_setFrame(time, prog, frame, transition);
145
+ return new Promise((resolve) =>
146
+ requestAnimationFrame(() => requestAnimationFrame(resolve))
147
+ );
148
+ },
149
+ localTime,
150
+ progress,
151
+ f,
152
+ transitionStyle
153
+ );
154
+
155
+ const shot = await page.screenshot({ type: 'png' });
156
+ await ffmpeg.write(shot);
157
+ rendered++;
158
+ onProgress?.({
159
+ frame: rendered,
160
+ total: totalFrames,
161
+ scene: scene.name,
162
+ sceneIndex: si + 1,
163
+ sceneCount: scenes.length
164
+ });
165
+ }
166
+ await page.close();
167
+ }
168
+
169
+ onLog?.({ level: 'info', message: `Menyelesaikan encoding MP4 (${totalFrames} frames)...` });
170
+ ffmpeg.proc.stdin.end();
171
+ await ffmpeg.exited;
172
+ } catch (err) {
173
+ ffmpeg.proc.kill('SIGKILL');
174
+ throw err;
175
+ } finally {
176
+ await browser.close().catch(() => {});
177
+ }
178
+
179
+ return { file: fileName, path: outFile, totalFrames, width, height, fps };
180
+ }
@@ -0,0 +1,23 @@
1
+ export const RESOLUTIONS = {
2
+ '1280x720': { width: 1280, height: 720, label: '720p' },
3
+ '1920x1080': { width: 1920, height: 1080, label: '1080p' },
4
+ '3840x2160': { width: 3840, height: 2160, label: '4K' },
5
+ '1080x1920': { width: 1080, height: 1920, label: '1080p Vertical' },
6
+ '1080x1080': { width: 1080, height: 1080, label: '1:1' }
7
+ };
8
+
9
+ export const RENDER_RESOLUTIONS = {
10
+ '720p': { width: 1280, height: 720 },
11
+ '1080p': { width: 1920, height: 1080 },
12
+ '4K': { width: 3840, height: 2160 }
13
+ };
14
+
15
+ export const formatTimecode = (sec, fps) => {
16
+ const safe = Number.isFinite(sec) ? Math.max(0, sec) : 0;
17
+ const mins = Math.floor(safe / 60);
18
+ const secs = Math.floor(safe % 60);
19
+ const frames = Math.floor((safe % 1) * fps);
20
+ return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}:${String(
21
+ frames
22
+ ).padStart(2, '0')}`;
23
+ };
@@ -0,0 +1,52 @@
1
+ export async function pingRenderer() {
2
+ try {
3
+ const res = await fetch('/health', { cache: 'no-store' });
4
+ return res.ok;
5
+ } catch {
6
+ return false;
7
+ }
8
+ }
9
+
10
+ async function readNdjson(res, onMessage) {
11
+ const reader = res.body.getReader();
12
+ const decoder = new TextDecoder();
13
+ let buffer = '';
14
+ let result = null;
15
+ while (true) {
16
+ const { value, done } = await reader.read();
17
+ if (done) break;
18
+ buffer += decoder.decode(value, { stream: true });
19
+ let idx;
20
+ while ((idx = buffer.indexOf('\n')) >= 0) {
21
+ const line = buffer.slice(0, idx).trim();
22
+ buffer = buffer.slice(idx + 1);
23
+ if (!line) continue;
24
+ const msg = JSON.parse(line);
25
+ if (msg.type === 'error') throw new Error(msg.message);
26
+ if (msg.type === 'done') result = msg;
27
+ onMessage?.(msg);
28
+ }
29
+ }
30
+ if (!result) throw new Error('Render stream berakhir tanpa hasil.');
31
+ return result;
32
+ }
33
+
34
+ export async function renderProject(payload, { onProgress, onLog, signal } = {}) {
35
+ const res = await fetch('/api/render', {
36
+ method: 'POST',
37
+ headers: { 'Content-Type': 'application/json' },
38
+ body: JSON.stringify(payload),
39
+ signal
40
+ });
41
+ if (!res.ok || !res.body) {
42
+ let detail = `HTTP ${res.status}`;
43
+ try {
44
+ detail = (await res.json()).error || detail;
45
+ } catch {}
46
+ throw new Error(detail);
47
+ }
48
+ return readNdjson(res, (msg) => {
49
+ if (msg.type === 'progress') onProgress?.(msg);
50
+ if (msg.type === 'log') onLog?.(msg);
51
+ });
52
+ }