-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1624 lines (1519 loc) · 69 KB
/
Copy pathserver.js
File metadata and controls
1624 lines (1519 loc) · 69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* VisttaPro HyperFrames Render Worker
*
* Receives render jobs via HTTP, runs the HyperFrames pipeline headless,
* and uploads results to Supabase Storage. Designed for Coolify deployment.
*
* Endpoints:
* GET /health — health check
* GET /healthz — liveness probe (uptime + active jobs, V4-04D)
* POST /job — submit a render job
* GET /job/:id/status — poll job status
* POST /patch/:id — apply click-to-edit patches (linkedom,
* persisted, V4-04C — replaces the old
* text-only /job/:id/patch PoC)
* POST /restructure/:id — rewrite the timeline from editor scenes
* (durations/starts/removals, V4-04C)
* GET /preview/:id — serve hyperframes preview for a project
* POST /supervise — regista um projeto no supervisor durável da
* pipeline V4 (V5.14 F7; auth worker-secret)
* GET /supervision — projetos supervisionados (diagnóstico de deploy)
*/
import express from "express";
import { execSync, spawn } from "child_process";
import { createClient } from "@supabase/supabase-js";
import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, copyFileSync } from "fs";
import { join, basename, dirname } from "path";
import { randomUUID } from "crypto";
import { pathToFileURL, fileURLToPath } from "url";
import { injectPreviewHelper, injectPreviewRuntime } from "./preview-helper.js";
import { verifyPreviewToken } from "./preview-token.js";
import { applyPatchesLinkedom, applyTimelineRestructure, normalizeClipWindows } from "./patch-engine.js";
import { sanitizeCompositionTweens, sanitizeTimelineRegistry, extractLintFindings } from "./composition-sanitizer.js";
import { lintClipWindows, lintGsapTargets } from "./window-lint.js";
import {
classifyCheckEnvelope,
extractCheckJson,
loadVendoredRuntimeBundles,
prepareOfflineFonts,
sanitizeCompositionForOffline,
VENDORED_GSAP_ASSET_PATH,
} from "./runtime-vendor.js";
import { prestageExternalMedia } from "./media-preloader.js";
import { compositionStoragePath, persistCompositionArtifact } from "./composition-persist.js";
import { captureThumbnails, computeArtifactHash, parseScenePostEntranceTimes, buildRenderSnapshotArgs, renderSnapshotsLegacyFrames } from "./thumbnails.js";
import { deriveElements, persistElementsArtifact } from "./elements-registry.js";
import { persistRenderSnapshots } from "./snapshots-upload.js";
import {
createSupervisionRegistry,
normalizeDriver,
startSupervision,
supervisorEnabled,
} from "./pipeline-runner.js";
const app = express();
app.use(express.json({ limit: "200mb" }));
// ── Config ──────────────────────────────────────────────────────────
const PORT = process.env.PORT || 8787;
const WORK_DIR = process.env.WORK_DIR || "/tmp/hyperframes-worker";
const SUPABASE_URL = process.env.SUPABASE_URL || "";
const SUPABASE_KEY = process.env.SUPABASE_KEY || process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SERVICE_KEY || process.env.SUPABASE_ANON_KEY || "";
const ORCHESTRATOR_PROJECT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const CHROME_PATH = process.env.CHROME_PATH || "/usr/bin/chromium";
// V4-3g.5 (R5): quando definido, GET /preview/:id exige ?token= HMAC válido
// (mesmo segredo que VIDEO_V4_PREVIEW_SECRET no orchestrator edge).
const PREVIEW_SECRET = process.env.PREVIEW_SECRET || "";
// V4-04C: server-to-server auth para /patch/:id + /restructure/:id — a rota
// Vercel envia o secret de serviço (VIDEO_V4_CALLBACK_SECRET no lado Vercel,
// partilhado aqui como WORKER_SECRET). Sem nenhum dos dois secrets, as rotas
// de escrita recusam-se (503) em vez de ficarem abertas.
const WORKER_SECRET = process.env.WORKER_SECRET || "";
const runtimeBundles = loadVendoredRuntimeBundles();
export function createSupabaseStorageClient(url, key, factory = createClient, warn = console.warn) {
if (!url || !key) {
const missing = [!url ? "SUPABASE_URL" : null, !key ? "SUPABASE_KEY" : null].filter(Boolean).join(", ");
const error = `missing ${missing}`;
warn(`SUPABASE_CLIENT_UNAVAILABLE: ${error}`);
return { client: null, error };
}
try {
return { client: factory(url, key), error: null };
} catch (err) {
const error = err?.message ?? String(err);
warn(`SUPABASE_CLIENT_UNAVAILABLE: ${error}`);
return { client: null, error };
}
}
const supabaseConfig = createSupabaseStorageClient(SUPABASE_URL, SUPABASE_KEY);
const supabase = supabaseConfig.client;
export function recordUploadFailure(uploadErrors, channel, error, warn = console.warn) {
const message = error?.message ?? String(error);
if (!(channel in uploadErrors)) uploadErrors[channel] = message;
warn(`SUPABASE_UPLOAD_FAILED ${channel}: ${message}`);
}
export function buildDoneCallbackPayload(job, timings, uploaded, uploadErrors) {
const payload = {
job_id: job.id,
project_id: job.project_id,
step: job.step,
status: "done",
timings,
uploaded,
total_ms: job.total_ms,
};
if (Object.keys(uploadErrors).length > 0) payload.upload_errors = uploadErrors;
if (job.window_normalization_warning) {
payload.window_normalization_warning = job.window_normalization_warning;
}
return payload;
}
/**
* V5_32 Fase C (C2 — D2): entrega do callback ao orquestrador com leitura de
* `res.ok`, retry com backoff curto e estado visível em `job.callback_status`
* (exposto no `/job/:id/status`). Antes o `await fetch(...)` era cego: um 400 da
* edge (ex.: schema do callback) passava por enviado, o job ficava `dispatched`
* e a UI mostrava loading eterno até ao teto do watchdog.
*/
export async function postCallback(url, secret, payload, options = {}) {
const {
fetchImpl = fetch,
attempts = 3,
baseDelayMs = 500,
log = console,
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
} = options;
const label = payload?.status ?? "?";
let last = { ok: false, attempts: 0 };
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
const res = await fetchImpl(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Worker-Secret": secret || "",
},
body: JSON.stringify(payload),
});
if (res.ok) {
return { ok: true, status: res.status, attempts: attempt, at: new Date().toISOString() };
}
const bodyText = await res.text().catch(() => "");
last = {
ok: false,
status: res.status,
attempts: attempt,
error: `HTTP ${res.status}${bodyText ? `: ${bodyText.slice(0, 500)}` : ""}`,
at: new Date().toISOString(),
};
log.error(
`[callback] ${label} rejected by orchestrator (attempt ${attempt}/${attempts}): HTTP ${res.status}${bodyText ? ` ${bodyText.slice(0, 500)}` : ""}`
);
} catch (err) {
last = {
ok: false,
attempts: attempt,
error: err?.message ?? String(err),
at: new Date().toISOString(),
};
log.error(`[callback] ${label} transport error (attempt ${attempt}/${attempts}): ${last.error}`);
}
if (attempt < attempts) await sleep(baseDelayMs * attempt);
}
log.error(`[callback] giving up after ${attempts} attempt(s): ${last.error}`);
return last;
}
export async function awaitStagedUploads(job, uploaded = job.uploaded || {}) {
if (job.compositionUploadPromise) {
uploaded.composition_html = await job.compositionUploadPromise;
}
if (job.elementsUploadPromise) {
uploaded.composition_elements = await job.elementsUploadPromise;
}
job.uploaded = uploaded;
return uploaded;
}
// ── V5.14 F7: supervisor durável da pipeline V4 ─────────────────────
// As edge functions têm teto de wall-clock; este contentor não. Ao ser
// registado pelo orquestrador (`POST /supervise`), o projeto passa a ser
// "pressionado" a cada 15-60s até o orquestrador dizer que não há nada a fazer
// — o worker NÃO interpreta o manifesto, só obedece ao `action` do /status
// (invariante P13). Falhar isto nunca custa a pipeline: o self-chain edge e o
// watchdog pg_cron (1min) continuam a fazer o seu trabalho.
export const supervision = createSupervisionRegistry();
// Ritmo de polling (teste/ajuste operacional; default = plano §3 F7).
const SUPERVISOR_TICK_MS = Number(process.env.PIPELINE_SUPERVISOR_TICK_MS) || 15_000;
/**
* Regista um projeto para supervisão.
*
* @param {string} projectId
* @param {{ driver?: object } | null} body corpo do /supervise (contrato do
* orquestrador); `null` ⇒ deriva de SUPABASE_URL + WORKER_SECRET (boot).
* @returns {{ supervised: boolean, reason?: string, status?: number }}
*/
export function superviseProject(projectId, body) {
if (!supervisorEnabled(process.env)) return { supervised: false, reason: "disabled" };
const resolved = normalizeDriver(body, process.env, projectId);
if (!resolved.ok) return { supervised: false, reason: resolved.error, status: 400 };
const started = startSupervision(
supervision,
{
fetchImpl: (url, init) => fetch(url, init),
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
log: (msg) => console.log(msg),
},
projectId,
resolved.driver,
{ tickMs: SUPERVISOR_TICK_MS },
);
return started.started ? { supervised: true } : { supervised: false, reason: started.reason };
}
// ─ In-memory job store (prototype; use DB in production) ───────────
const jobs = new Map();
// Map project_id → job_id for preview lookup
const projectJobs = new Map();
// ── Job persistence (V4-3g.3, B6) ──────────────────────────────────
// POST /job grava um marcador job.json no dir do job; no boot, o scan de
// WORK_DIR repovoa jobs/projectJobs — os previews sobrevivem a restarts
// (o volume worker-data já persiste os ficheiros entre deploys).
function writeJobMarker(jobDir, marker) {
try {
writeFileSync(join(jobDir, "job.json"), JSON.stringify(marker));
} catch (err) {
console.warn(`[worker] failed to write job.json in ${jobDir}: ${err.message}`);
}
}
export function rehydrateJobs() {
let entries;
try {
entries = readdirSync(WORK_DIR, { withFileTypes: true });
} catch {
return; // WORK_DIR inexistente — primeiro boot
}
const found = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const jobDir = join(WORK_DIR, entry.name);
try {
const markerPath = join(jobDir, "job.json");
if (!existsSync(markerPath)) continue;
const marker = JSON.parse(readFileSync(markerPath, "utf-8"));
if (!marker?.job_id || !marker?.project_id) continue;
// Sem index.html não há nada servível — skip tolerante.
if (!existsSync(join(jobDir, "index.html"))) continue;
found.push({ marker, jobDir });
} catch (err) {
console.warn(`[worker] rehydrate: skipping ${entry.name}: ${err.message}`);
}
}
// O job MAIS RECENTE por projeto ganha o mapping (o build faz overwrite
// do placeholder staged no /start).
found.sort((a, b) => String(a.marker.created_at ?? "").localeCompare(String(b.marker.created_at ?? "")));
for (const { marker, jobDir } of found) {
jobs.set(marker.job_id, {
id: marker.job_id,
project_id: marker.project_id,
step: marker.step || "render",
status: "staged",
created_at: marker.created_at || new Date().toISOString(),
job_dir: jobDir,
});
projectJobs.set(marker.project_id, marker.job_id);
}
if (found.length) console.log(`[worker] rehydrated ${found.length} job(s) from ${WORK_DIR}`);
// V5.14 F7: um contentor que reinicia a meio de um render perde o callback — o
// projeto ficaria pendurado até ao watchdog. Re-registrar a supervisão dos
// renders recentes fecha esse buraco. Só markers dentro do teto de vida do
// job (25min): um render mais velho já foi tratado pela retoma do orquestrador,
// e um projeto já terminado sai logo no primeiro tick (`action: idle`).
const SUPERVISE_REHYDRATE_MAX_AGE_MS = 25 * 60 * 1000;
for (const [projectId, jobId] of projectJobs) {
const job = jobs.get(jobId);
if (!job || job.step === "preview") continue;
const created = Date.parse(job.created_at ?? "");
if (Number.isNaN(created) || Date.now() - created > SUPERVISE_REHYDRATE_MAX_AGE_MS) continue;
const out = superviseProject(projectId, null);
if (out.supervised) console.log(`[worker] supervisão re-registrada no boot para ${projectId}`);
}
}
rehydrateJobs();
/**
* V4-3f.7: execSync failures carry stdout/stderr Buffers on the error
* object. Surface them in the job error so the orchestrator (and the
* Studio UI) shows actionable lint findings instead of the opaque
* "Command failed: npx hyperframes lint ..." message.
*
* V4-3f.11: keep BOTH ends when truncating. The head of CLI output is
* progress chatter; the actionable failure line sits at the tail — the
* old head-keep truncation was hiding the actual render error.
*/
export function formatExecError(err, { limit = 4000 } = {}) {
const base = err?.message ?? String(err);
const detail = [err?.stderr, err?.stdout]
.map((b) => (b ? b.toString() : ""))
.filter((s) => s.trim())
.join("\n")
.trim();
if (!detail) return base;
const full = `${base}\n${detail}`;
if (full.length <= limit) return full;
const marker = "\n[…truncated…]\n";
const headSize = Math.floor(limit * 0.25);
const tailSize = limit - headSize - marker.length;
return `${full.slice(0, headSize)}${marker}${full.slice(-tailSize)}`;
}
/** Upload an artifact using the signed PUT URL supplied by the orchestrator. */
export async function uploadToSignedUrl(url, body, contentType) {
const response = await fetch(url, {
method: "PUT",
headers: { "Content-Type": contentType },
body,
});
if (!response.ok) {
const detail = (await response.text().catch(() => "")).trim();
throw new Error(`signed upload failed (${response.status})${detail ? `: ${detail.slice(0, 400)}` : ""}`);
}
}
/** Run a command while retaining stdout/stderr even when it exits non-zero. */
export function spawnCommand(command, args, { timeout = 60000, env = process.env } = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { env });
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
}, timeout);
child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
child.once("error", (error) => {
clearTimeout(timer);
reject(Object.assign(error, { stdout, stderr }));
});
child.once("close", (code, signal) => {
clearTimeout(timer);
resolve({ code, signal, stdout, stderr, timedOut });
});
});
}
export function formatCheckFailure(classified) {
const findingText = classified.fatal
.map((finding) => `${finding.code ?? "runtime_error"}: ${finding.message ?? "unknown error"}`)
.join("\n");
return `HyperFrames check failed (CLI ${classified.version})\n${findingText || "unknown check failure"}`;
}
export async function runCheck(jobDir) {
const command = process.env.HYPERFRAMES_BIN || "npx";
const args = process.env.HYPERFRAMES_BIN
? ["check", "--json", jobDir]
: ["hyperframes", "check", "--json", jobDir];
const result = await spawnCommand(command, args, {
timeout: 60000,
env: { ...process.env, CHROME_PATH },
});
if (result.timedOut) {
const error = new Error(`Command timed out: ${command} ${args.join(" ")}`);
error.stdout = result.stdout;
error.stderr = result.stderr;
throw error;
}
const envelope = extractCheckJson(result.stdout) ?? extractCheckJson(result.stderr);
if (!envelope) {
const error = new Error(`Command failed: ${command} ${args.join(" ")}`);
error.stdout = result.stdout;
error.stderr = result.stderr;
error.code = result.code;
throw error;
}
const classified = classifyCheckEnvelope(envelope);
if (!classified.ok) {
const error = new Error(formatCheckFailure(classified));
error.stdout = result.stdout;
error.stderr = result.stderr;
error.code = result.code;
throw error;
}
if (classified.unknown.length) {
const codes = classified.unknown.map((finding) => finding.code ?? "unknown").join(",");
console.warn(`[worker] hyperframes check returned ok=false without a known failure (CLI ${classified.version}; ${codes}); continuing with structured warning`);
}
if (classified.warnings.length || result.code !== 0) {
console.warn(`[worker] hyperframes check continued with ${classified.warnings.length} warning(s) (CLI ${classified.version})`);
}
return { envelope, classified, result };
}
// ── Health ──────────────────────────────────────────────────────────
app.get("/health", (_req, res) => {
res.json({ ok: true, ts: Date.now(), chrome: CHROME_PATH });
});
// V4-04D §2.5: liveness probe — lets the Studio poll distinguish
// "worker down" from "composition not staged yet".
app.get("/healthz", (_req, res) => {
res.json({
ok: true,
uptime_s: Math.round(process.uptime()),
active_jobs: jobs.size,
});
});
// Vendored browser dependencies are also exposed for local compositions that
// refer to the worker runtime by URL. Normal build output is inline, but these
// routes make the worker useful for previews and provide a deterministic
// fallback without reaching a public CDN.
function runtimeCors(_req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
if (_req.method === "OPTIONS") return res.sendStatus(204);
next();
}
app.options("/runtime/hyperframes.min.js", runtimeCors);
app.options("/runtime/gsap.min.js", runtimeCors);
app.get("/runtime/hyperframes.min.js", runtimeCors, (_req, res) => {
if (!runtimeBundles.hyperframes) return res.status(404).json({ error: "hyperframes runtime unavailable" });
res.type("application/javascript").send(runtimeBundles.hyperframes);
});
app.get("/runtime/gsap.min.js", runtimeCors, (_req, res) => {
if (!runtimeBundles.gsap) return res.status(404).json({ error: "gsap runtime unavailable" });
res.type("application/javascript").send(runtimeBundles.gsap);
});
// V5-P5B §2.1: biblioteca BGM curated vendida no container (assets públicos
// de biblioteca — mesmo regime CORS das rotas /runtime). catalog.json é a
// mesma tabela partilhada com o passo de áudio (fonte única: o gerador).
const ROOT_DIR = dirname(fileURLToPath(import.meta.url));
const BGM_DIR = join(ROOT_DIR, "bgm");
const bgmCache = new Map();
function loadBgmAsset(name) {
if (bgmCache.has(name)) return { ok: true, data: bgmCache.get(name) };
const path = join(BGM_DIR, name);
try {
const data = readFileSync(path);
bgmCache.set(name, data);
return { ok: true, data };
} catch {
return { ok: false };
}
}
app.options("/bgm/catalog.json", runtimeCors);
app.options("/bgm/:file", runtimeCors);
app.get("/bgm/catalog.json", runtimeCors, (_req, res) => {
const asset = loadBgmAsset("catalog.json");
if (!asset.ok) return res.status(404).json({ error: "bgm catalog unavailable" });
res.type("application/json").set("Cache-Control", "public, max-age=300").send(asset.data);
});
app.get("/bgm/:file", runtimeCors, (req, res) => {
const file = String(req.params.file ?? "");
// basename-guard + whitelist de extensão (biblioteca é só mp3).
if (!file || file !== basename(file) || !/\.mp3$/i.test(file)) {
return res.status(404).json({ error: "invalid bgm file" });
}
const asset = loadBgmAsset(file);
if (!asset.ok) return res.status(404).json({ error: "bgm file not found" });
res
.type("audio/mpeg")
.set("Cache-Control", "public, max-age=86400")
.send(asset.data);
});
// ── Submit job ──────────────────────────────────────────────────────
app.post("/job", async (req, res) => {
const body = req.body;
const project_id = body.project_id;
const step = body.step;
// Accept both formats: direct index_html OR nested in inputs (orchestrator format)
let index_html = body.index_html || body.inputs?.index_html || body.inputs?.index_html_url;
const callback = body.callback;
const outputs = body.outputs;
const artifact_paths = body.artifact_paths;
if (!project_id) {
return res.status(400).json({ error: "project_id required" });
}
// Finalize intentionally reuses the composition that just completed the
// build step. The orchestrator only sends upload URLs for this follow-up
// job, so recover the latest staged build HTML from the project mapping.
// This also works after a worker restart because rehydrateJobs restores the
// project → job index from the persistent volume.
// V5.24: track the previous job dir — when the reused HTML already carries
// worker-local `assets/vp-media-*` references (post-prestage), the new
// jobDir starts empty and prestage skips (it only downloads https://).
// Copying the previous job's assets/ heals the reuse instead of failing
// lint with audio_src_not_found / missing_local_asset.
let reusedPreviousJobDir = "";
if (!index_html && step === "finalize") {
const previousJobId = projectJobs.get(project_id);
const previousJob = previousJobId ? jobs.get(previousJobId) : null;
const previousHtml = previousJob?.job_dir ? join(previousJob.job_dir, "index.html") : "";
if (previousHtml && existsSync(previousHtml)) {
index_html = readFileSync(previousHtml, "utf-8");
reusedPreviousJobDir = previousJob.job_dir;
console.log(`[worker] finalize reused staged build composition for project ${project_id}`);
}
}
if (!index_html) {
return res.status(400).json({ error: "index_html or inputs.index_html required" });
}
// V4-debug3: LLM may return JSON wrapper {title, duration, html} instead of
// raw HTML. Extract the html field if so.
if (typeof index_html === 'string' && index_html.trim().startsWith('{')) {
try {
const parsed = JSON.parse(index_html);
if (parsed.html) {
index_html = parsed.html;
}
} catch {
// Not valid JSON — use as-is (it's HTML)
}
}
const jobId = body.job_id || randomUUID();
const jobDir = join(WORK_DIR, jobId);
mkdirSync(join(jobDir, "assets"), { recursive: true });
// V5.24: heal worker-local asset reuse. `assets/vp-media-*` paths are only
// valid inside the jobDir that prestaged them (sha1(url) → local file).
// When the incoming HTML already carries such references — finalize reuse
// above, or a re-dispatch of previously staged HTML persisted to storage —
// prestage skips (it only downloads https://) and lint would fail with
// audio_src_not_found / missing_local_asset. Copy the previous job's
// assets/ for the same project so the new jobDir resolves them.
try {
let donorDir = reusedPreviousJobDir;
if (!donorDir && typeof index_html === "string" && /src\s*=\s*["']assets\/vp-media-/i.test(index_html)) {
const prevId = projectJobs.get(project_id);
const prevJob = prevId ? jobs.get(prevId) : null;
if (prevJob?.job_dir && prevJob.job_dir !== jobDir) donorDir = prevJob.job_dir;
}
if (donorDir) {
const srcAssets = join(donorDir, "assets");
const dstAssets = join(jobDir, "assets");
if (existsSync(srcAssets)) {
let copied = 0;
for (const name of readdirSync(srcAssets)) {
if (name === "__vp_gsap.min.js") continue;
const src = join(srcAssets, name);
const dst = join(dstAssets, name);
if (!existsSync(dst)) {
try {
copyFileSync(src, dst);
copied += 1;
} catch {
// best-effort — a missing file surfaces as lint error below
}
}
}
if (copied > 0) console.log(`[worker] copied ${copied} staged asset(s) from previous job for project ${project_id}`);
}
}
} catch {
// best-effort healing — never blocks staging
}
// Post-process generated HTML before it enters the offline render pipeline.
// The CLI launches Chromium inside this container, so public CDN references
// are both unnecessary and a source of fatal ERR_BLOCKED_BY_ORB failures.
if (typeof index_html === 'string') {
// V4-3f.17 (Fase 5): mechanical tween sanitization BEFORE lint — the
// worker's last line of defense against the gsap_non_transform_motion
// error class (left/top tweens) that hard-failed the V4-3f.16 build.
// Mirrors the edge-side repair; every conversion is logged.
const tweenFix = sanitizeCompositionTweens(index_html);
if (tweenFix.repairs.length > 0) {
console.warn(
`[worker] sanitized ${tweenFix.repairs.length} layout-prop tween(s) before lint: ${tweenFix.repairs.join("; ")}`
);
index_html = tweenFix.html;
}
// V5.27 Fase D: timeline-registry repair BEFORE lint — the worker's last
// line of defense against the gsap_timeline_not_registered error class
// (job 1700b4f4) that hard-failed the build on the worker. Mirrors the
// edge-side intra-script repair (Fase A); each insertion is logged like
// the tween-fixes above. Runs on the exact bytes the CLI will see, so it
// also covers re-dispatched Studio HTML and worker-materialized blocks
// that never pass through the edge.
try {
const compositionId =
index_html.match(/data-composition-id\s*=\s*["']([^"']+)["']/i)?.[1] ?? "main";
const registryFix = sanitizeTimelineRegistry(index_html, compositionId);
if (registryFix.repairs.length > 0) {
console.warn(
`[worker] registered ${registryFix.repairs.length} timeline(s) before lint: ${registryFix.repairs.join("; ")}`
);
index_html = registryFix.html;
}
} catch (err) {
console.warn(`[worker] timeline registry repair skipped: ${err?.message ?? err}`);
}
// V4-3f.10: resolve Google Fonts into local woff2 assets BEFORE the
// sanitizer strips the references — lint's font_family_without_font_face
// rule needs an @font-face declaration for every brand family.
let fontFaceStyle = "";
try {
const fonts = await prepareOfflineFonts(index_html, {
jobDir,
cacheDir: join(WORK_DIR, "__vp-font-cache"),
log: console.log,
});
fontFaceStyle = fonts.style;
} catch (err) {
console.warn(`[worker] font preparation failed: ${err?.message ?? err}`);
}
index_html = sanitizeCompositionForOffline(index_html, {
gsapRuntime: runtimeBundles.gsap,
fontFaceStyle,
});
}
let jobMediaValidation = null;
// V5.24: canonical HTML for storage/registry. prestage rewrites https://
// srcs to job-local `assets/vp-media-*` paths (sha1(url) → jobDir/assets).
// Persisting the rewritten HTML poisoned `compositions/index.html`: the
// next job starts with an empty jobDir, prestage skips (only https:// is
// downloaded) and lint fails with audio_src_not_found / missing_local_asset
// for exactly those vp-media-* files. The canonical (pre-prestage,
// post-sanitize) HTML keeps the original https:// URLs and stays valid
// across jobs — disk keeps the rewritten form, storage keeps canonical.
let canonicalHtml = index_html;
// V4-3f.12: pre-stage external videos/audio locally. The HyperFrames CLI
// downloads remote URLs itself, but if the URL returns an HTML page, a 403,
// or a truncated response, ffprobe fails with "moov atom not found". We
// fetch + validate + rewrite here so the error is surfaced early and the
// render pipeline only sees valid local MP4 files.
if (typeof index_html === "string") {
const mediaResult = await prestageExternalMedia(index_html, jobDir, {
fetchImpl: fetch,
ffprobePath: "ffprobe",
timeoutMs: 60_000,
log: console.log,
});
if (!mediaResult.ok) {
const summary = mediaResult.failures
.map((f) => `${f.url} -> ${f.reason}: ${f.detail}`)
.join("; ");
const error = new Error(`MEDIA_VALIDATION_FAILED: ${summary}`);
jobs.set(jobId, {
id: jobId,
project_id,
step: step || "render",
status: "failed",
created_at: new Date().toISOString(),
job_dir: jobDir,
callback,
outputs,
artifact_paths,
error: formatExecError(error),
media_validation: { urls_found: mediaResult.failures.length, urls_failed: mediaResult.failures },
});
writeJobMarker(jobDir, {
job_id: jobId,
project_id,
step: step || "render",
mode: body.mode === "preview" ? "preview" : "render",
created_at: new Date().toISOString(),
});
return res.status(422).json({
job_id: jobId,
status: "failed",
error: "MEDIA_VALIDATION_FAILED",
failures: mediaResult.failures,
});
}
if (!mediaResult.skipped) {
console.log(`[worker] pre-staged ${mediaResult.downloaded.length} external media file(s)`);
index_html = mediaResult.html;
} else if (typeof index_html === "string" && /src\s*=\s*["']assets\/vp-media-/i.test(index_html)) {
// V5.24: poisoned re-dispatch signature — HTML already carries job-local
// `assets/vp-media-*` paths but prestage found no https:// to download.
// Donor copy above heals the same-worker case; cross-worker/restart or
// poisoned storage still lands here and lint will fail below. Log the
// exact missing files so Coolify post-mortem points at the storage copy,
// not at the CLI rule.
const missing = [...index_html.matchAll(/src\s*=\s*["'](assets\/vp-media-[^"']+)["']/gi)]
.map((mm) => mm[1])
.filter((src, idx, arr) => arr.indexOf(src) === idx);
console.warn(
`[worker] pre-staged 0 files but HTML references ${missing.length} worker-local asset(s) (poisoned re-dispatch?): ${missing.slice(0, 8).join(", ")}`
);
}
// Persist validation metadata for diagnostics in callbacks.
jobMediaValidation = {
urls_found: mediaResult.downloaded.length,
urls_downloaded: mediaResult.downloaded,
};
}
// Write the composition HTML
writeFileSync(join(jobDir, "index.html"), index_html);
// V5-P0C §2.1 + V5_16.2 B1: quantize rounding drift onto the fps grid before
// consumers run, but preserve a builder-declared gap across the whole root
// composition. Timeline intent is never silently collapsed.
let windowLintFindings = [];
let windowNormalizationWarning = null;
if (typeof index_html === "string") {
try {
const stagingFps = Number.isFinite(Number(body.fps)) && Number(body.fps) > 0 ? Number(body.fps) : 30;
const norm = normalizeClipWindows(index_html, stagingFps);
if (norm.warning) {
windowNormalizationWarning = norm.warning;
console.warn(
`CLIP_WINDOWS_NON_CONTIGUOUS previous=${norm.warning.previous_id ?? "?"} next=${norm.warning.next_id ?? "?"} declared_start=${norm.warning.declared_start} expected_start=${norm.warning.expected_start}`
);
} else if (norm.adjusted.length > 0) {
console.log(
`[worker] window normalization: ${norm.adjusted.length} clip window(s) quantized to the ${stagingFps}fps grid`
);
index_html = norm.html;
writeFileSync(join(jobDir, "index.html"), index_html);
}
windowLintFindings = lintClipWindows(index_html, { fps: stagingFps });
if (windowLintFindings.length > 0) {
console.warn(
`[worker] clip window lint: ${windowLintFindings.map((f) => `[${f.code}] ${f.selector ?? ""}`).join(", ")}`
);
}
// V5.21 Fase H: orphan-tween scan — report-only (warn log, never fails
// staging; the edge-side mirror in edgeLint.ts surfaces it to the LLM).
try {
const gsapTargetFindings = lintGsapTargets(index_html);
if (gsapTargetFindings.length > 0) {
console.warn(
`[worker] gsap target lint: ${gsapTargetFindings.map((f) => `[${f.code}] ${f.selector ?? ""}`).join(", ")}`
);
}
} catch (err) {
console.warn(`[worker] gsap target lint skipped: ${err?.message ?? err}`);
}
} catch (err) {
console.warn(`[worker] window normalization skipped: ${err?.message ?? err}`);
}
}
const uploadErrors = {};
const directUploadFailure = (channel) => (message) =>
recordUploadFailure(uploadErrors, channel, message);
if (step !== "preview" && ORCHESTRATOR_PROJECT_ID_RE.test(project_id) && !supabase) {
recordUploadFailure(uploadErrors, "composition_html", supabaseConfig.error);
recordUploadFailure(uploadErrors, "composition_elements", supabaseConfig.error);
}
// V4_04 fix: persistir a composição staged no storage — o editor usa
// `projects/{id}/compositions/index.html` como fonte primária pós-build
// (reconciliação de durações) e como alvo das edições. Fire-and-forget no
// staging; a promessa fica no job para o callback reportar o resultado.
// step:'preview' é o placeholder inicial — não pode competir com o HTML real.
// V5.24: persist canonicalHtml (pré-prestage) — o index_html reescrito contém
// `assets/vp-media-*` válidos só dentro deste jobDir; gravá-lo no storage
// envenenava o próximo job (prestage skipped → lint HYPERFRAMES_LINT_FAILED).
const compositionUploadPromise = step !== "preview"
? persistCompositionArtifact(
supabase,
project_id,
canonicalHtml,
console.log,
directUploadFailure("composition_html"),
)
: null;
// V5-P3A (AD-5): derivar e publicar o registry de elementos ao lado da
// composição — canonicalHtml aqui é o HTML CANÓNICO (pós-sanitize,
// pré-prestage, com URLs https:// originais), logo o inventário reflete o
// que o editor deve editar. O preview serve o HTML reescrito por jobDir.
// Mesmo fire-and-forget; o resultado viaja no callback (composition_elements).
const elementsUploadPromise = step !== "preview"
? persistElementsArtifact(
supabase,
project_id,
deriveElements(canonicalHtml),
console.log,
directUploadFailure("composition_elements"),
)
: null;
// V4-3g.3 (B6): marcador para reidratação do registry no boot.
writeJobMarker(jobDir, {
job_id: jobId,
project_id,
step: step || "render",
mode: body.mode === "preview" ? "preview" : "render",
created_at: new Date().toISOString(),
});
// Write assets if provided
if (body.assets) {
for (const [name, data] of Object.entries(body.assets)) {
const buf = Buffer.from(data, "base64");
const assetPath = join(jobDir, "assets", name);
mkdirSync(dirname(assetPath), { recursive: true });
writeFileSync(assetPath, buf);
}
}
if (runtimeBundles.gsap) {
writeFileSync(join(jobDir, VENDORED_GSAP_ASSET_PATH), runtimeBundles.gsap);
}
jobs.set(jobId, {
id: jobId,
project_id,
step: step || "render",
status: "queued",
created_at: new Date().toISOString(),
job_dir: jobDir,
callback,
outputs,
artifact_paths,
media_validation: jobMediaValidation,
window_lint_findings: windowLintFindings,
window_normalization_warning: windowNormalizationWarning,
upload_errors: uploadErrors,
compositionUploadPromise,
elementsUploadPromise,
});
// Track by project_id for preview lookup
projectJobs.set(project_id, jobId);
// mode:'preview' stages the composition only (no HyperFrames CLI run) —
// used for editor previews and contract tests (V4-3f.3).
if (body.mode !== "preview") {
// Run render asynchronously
runRender(jobId, jobDir).catch((err) => {
const job = jobs.get(jobId);
if (job) {
job.status = "failed";
job.error = formatExecError(err);
}
});
} else {
jobs.get(jobId).status = "staged";
}
res.json({ job_id: jobId, status: "queued" });
});
// ── Poll status ─────────────────────────────────────────────────────
// Status is an internal reconciliation endpoint. Even authorized callers do
// not need callback secrets or signed upload URLs to identify a terminal job.
export function redactJobStatus(value) {
if (Array.isArray(value)) return value.map((item) => redactJobStatus(item));
if (!value || typeof value !== "object") return value;
const out = {};
for (const [key, child] of Object.entries(value)) {
if (key === "secret" && typeof child === "string") {
out[key] = "[redacted]";
} else if (key.endsWith("_upload_url") && typeof child === "string") {
out[key] = "[redacted]";
} else {
out[key] = redactJobStatus(child);
}
}
return out;
}
app.get("/job/:id/status", (req, res) => {
const auth = authorizedWorkerService(req);
if (!auth.ok) return res.status(auth.status).json({ error: auth.error });
const job = jobs.get(req.params.id);
if (!job) return res.status(404).json({ error: "not found" });
res.json(redactJobStatus(job));
});
// ── V5.14 F7: supervisão da pipeline ──────────────────────────────
// Auth: mesmo padrão das rotas de escrita server-to-server (WORKER_SECRET, que
// é o VIDEO_V4_CALLBACK_SECRET do orquestrador). O /supervise não tem segredos
// próprios: o contrato (rotas da edge + secret) chega no corpo, porque o worker
// é burro também na configuração.
function authorizedWorkerService(req) {
if (!WORKER_SECRET) return { ok: false, status: 503, error: "auth_not_configured" };
if ((req.get("x-worker-secret") || "") !== WORKER_SECRET) return { ok: false, status: 401, error: "invalid_secret" };
return { ok: true };
}
app.post("/supervise", (req, res) => {
const auth = authorizedWorkerService(req);
if (!auth.ok) return res.status(auth.status).json({ error: auth.error });
const projectId = req.body?.project_id;
if (!projectId) return res.status(400).json({ error: "project_id required" });
const out = superviseProject(projectId, req.body);
// 400 só por contrato inválido: um corpo sem URLs/secret não pode arrancar
// um loop cego (e o orquestrador fica com a pista no log do pedido).
if (out.status) return res.status(out.status).json({ error: out.reason });
res.status(202).json(out);
});
app.get("/supervision", (req, res) => {
const auth = authorizedWorkerService(req);
if (!auth.ok) return res.status(auth.status).json({ error: auth.error });
res.json({ projects: supervision.list(), tick_ms: SUPERVISOR_TICK_MS, enabled: supervisorEnabled(process.env) });
});
// ── V4-04C: project-scoped write endpoints (patch / restructure) ────
// Auth: server-to-server secret (X-Worker-Secret === WORKER_SECRET) or the
// same preview HMAC token as GET /preview/:id. Without either secret the
// routes refuse to open (503) — the preview is never publicly writable.
function authorizeProjectWrite(req, projectId) {
const hasService = Boolean(WORKER_SECRET);
const hasPreview = Boolean(PREVIEW_SECRET);
if (!hasService && !hasPreview) {
return { ok: false, status: 503, error: "auth_not_configured" };
}
if (hasService && (req.get("x-worker-secret") || "") === WORKER_SECRET) {
return { ok: true };
}
if (hasPreview) {
const token = typeof req.query.token === "string" ? req.query.token : "";
if (verifyPreviewToken(token, projectId, PREVIEW_SECRET)) return { ok: true };
return { ok: false, status: 401, error: "invalid_token" };
}
return { ok: false, status: 401, error: "invalid_secret" };
}
/** Resolve a job by project_id (orchestrator format) or internal job_id. */
function resolveJobById(id) {
const internalJobId = projectJobs.get(id);
if (internalJobId) {
const job = jobs.get(internalJobId);
if (job) return job;
}
return jobs.get(id) ?? null;
}
app.options("/patch/:id", previewCors);
app.post("/patch/:id", previewCors, (req, res) => {
const projectId = req.params.id;
const auth = authorizeProjectWrite(req, projectId);
if (!auth.ok) return res.status(auth.status).json({ error: auth.error });
const job = resolveJobById(projectId);
if (!job) return res.status(404).json({ error: "not found" });
const { patches } = req.body ?? {};
if (!Array.isArray(patches) || patches.length === 0) {
return res.status(400).json({ error: "patches must be a non-empty array" });
}
for (const p of patches) {
if (!p || typeof p.selector !== "string" || typeof p.property !== "string" || typeof p.value !== "string") {
return res.status(400).json({ error: "each patch must have {selector, property, value} strings" });
}
}
const indexPath = join(job.job_dir, "index.html");
if (!existsSync(indexPath)) return res.status(404).json({ error: "index.html not found" });
const html = readFileSync(indexPath, "utf-8");
let result;
try {
result = applyPatchesLinkedom(html, patches);
} catch (err) {
const status = err?.status ?? 500;
return res.status(status).json({ error: err?.message ?? "patch failed" });
}
writeFileSync(indexPath, result.html);
console.log(`[worker] /patch ${projectId}: ${result.applied}/${patches.length} patch(es) applied`);
// V4-04C §2.1: the PATCHED HTML rides on the response — the caller
// (Vercel route) persists it to Supabase storage; the worker stays
// Supabase-free.
// V5-P1E: `created` lista ids criados por operações de nó (duplicate).
// V5-P3A: `elements` é o registry derivado do HTML FINAL — o caller
// publica-o como projects/{id}/compositions/elements.json na mesma escrita.
res.json({
ok: true,
applied: result.applied,
created: result.created ?? [],
html: result.html,
elements: deriveElements(result.html),
});
});
app.options("/restructure/:id", previewCors);
app.post("/restructure/:id", previewCors, (req, res) => {