beatsheet 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +63 -2
- package/bin/beatsheet.js +14 -0
- package/bin/register-fallback.mjs +23 -0
- package/bin/resolve-fallback.mjs +83 -0
- package/package.json +45 -4
- package/player/env.d.ts +5 -0
- package/player/gallery-audio.ts +147 -0
- package/player/gallery-css.ts +144 -0
- package/player/gallery-detail.ts +385 -0
- package/player/gallery-music.ts +257 -0
- package/player/gallery-pick-state.ts +167 -0
- package/player/gallery-pick.ts +749 -0
- package/player/gallery-sounds.ts +137 -0
- package/player/gallery-state.ts +457 -0
- package/player/gallery.ts +612 -0
- package/player/index.html +49 -0
- package/player/main.ts +83 -0
- package/skill/SKILL.md +658 -0
- package/skill/examples/library/assets/tour/avatar-mk.svg +1 -0
- package/skill/examples/library/assets/tour/dashboard-insights.svg +1 -0
- package/skill/examples/library/assets/tour/dashboard.svg +1 -0
- package/skill/examples/library/assets/tour/settings.svg +1 -0
- package/skill/examples/library/library-tour.plan.md +32 -0
- package/skill/examples/library/library-tour.video.json +268 -0
- package/skill/reference/scene-techniques.md +306 -0
- package/skill/scripts/beats.ts +34 -0
- package/skill/scripts/catalogue.ts +120 -0
- package/skill/scripts/frames.ts +105 -0
- package/src/args.ts +344 -0
- package/src/cli.ts +95 -0
- package/src/commands.ts +812 -0
- package/src/default-project.config.ts +9 -0
- package/src/index.ts +47 -0
- package/src/packages.ts +17 -0
- package/src/paths.ts +32 -0
- package/src/project.ts +200 -0
- package/src/render/browser.ts +185 -0
- package/src/render/capture.ts +320 -0
- package/src/render/ffmpeg.ts +229 -0
- package/src/render/gif-info.ts +61 -0
- package/src/render/render.ts +220 -0
- package/src/samples.ts +557 -0
- package/src/server/api.ts +494 -0
- package/src/server/jobs.ts +210 -0
- package/src/server/security.ts +47 -0
- package/src/server/server.ts +191 -0
- package/src/server/sse.ts +76 -0
- package/src/server/static.ts +127 -0
- package/src/server/vite.ts +100 -0
- package/src/skill.ts +111 -0
- package/src/snap.ts +212 -0
- package/src/speech.ts +689 -0
- package/src/svg-text.ts +136 -0
- package/src/voicefx.ts +311 -0
- package/studio/3rdpartylicenses.txt +287 -0
- package/studio/favicon.ico +0 -0
- package/studio/icons/apple-touch-icon.png +0 -0
- package/studio/icons/icon-192.png +0 -0
- package/studio/icons/icon-512.png +0 -0
- package/studio/icons/icon.svg +1 -0
- package/studio/icons/maskable-512.png +0 -0
- package/studio/index.html +18 -0
- package/studio/main-KMYDBWZH.js +15 -0
- package/studio/manifest.webmanifest +17 -0
- package/studio/offline.html +92 -0
- package/studio/styles-NJ2CULOW.css +1 -0
- package/studio/sw.js +71 -0
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants as fsConstants, cpSync } from 'node:fs';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
6
|
+
import {
|
|
7
|
+
gifSettingsIssues,
|
|
8
|
+
parseDoc,
|
|
9
|
+
resolveGifRender,
|
|
10
|
+
videoDocSchema,
|
|
11
|
+
type FormatId,
|
|
12
|
+
type GifOptions,
|
|
13
|
+
type SpeechJobRequest,
|
|
14
|
+
type ValidationIssue,
|
|
15
|
+
type VideoDoc,
|
|
16
|
+
} from '@beatsheet/core';
|
|
17
|
+
import { FORMAT_IDS } from '../args';
|
|
18
|
+
import { canonicalPath, errorMessage, VIDEO_SUFFIX, type ProjectContext } from '../project';
|
|
19
|
+
import { planSpeech, pluginMissingMessage, SpeechPlanError, speechStatus, type SpeechPlugins } from '../speech';
|
|
20
|
+
import type { RenderJobs, SpeechJobs } from './jobs';
|
|
21
|
+
import { isSpeechTerminal, isTerminal, streamEvents } from './sse';
|
|
22
|
+
|
|
23
|
+
export interface ApiContext {
|
|
24
|
+
name: string;
|
|
25
|
+
/** Folder of the *.video.json files; nothing outside it is read or written. */
|
|
26
|
+
videosDir: string;
|
|
27
|
+
/** Folder of the project's images (/project-assets/); POST /api/library-tour copies the tour's images here. */
|
|
28
|
+
assetsDir: string;
|
|
29
|
+
outDir: string;
|
|
30
|
+
/** The library tour to copy into the project (libraryTourSource()); absent: POST /api/library-tour answers 404. */
|
|
31
|
+
libraryTour?: { video: string; assets: string };
|
|
32
|
+
/** Absent: POST /api/render answers 501. */
|
|
33
|
+
jobs?: RenderJobs;
|
|
34
|
+
/** Voice-over (/api/speech/*); absent: 501. */
|
|
35
|
+
speech?: SpeechApiContext;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface SpeechApiContext {
|
|
39
|
+
/** The project as beatsheet.config.ts is now (projectReloader): a changed project voice applies at once. */
|
|
40
|
+
project: () => Promise<Pick<ProjectContext, 'config' | 'configPath' | 'root'>>;
|
|
41
|
+
/** The project's engine plugins, kept for the server's lifetime (one model load). */
|
|
42
|
+
plugins: SpeechPlugins;
|
|
43
|
+
jobs: SpeechJobs;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const MAX_BODY = 10 * 1024 * 1024;
|
|
47
|
+
|
|
48
|
+
/** Handles /api/* requests. Returns false when the URL is not an API route. */
|
|
49
|
+
export async function handleApi(req: IncomingMessage, res: ServerResponse, ctx: ApiContext): Promise<boolean> {
|
|
50
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
51
|
+
const parts = url.pathname.split('/').filter(Boolean);
|
|
52
|
+
if (parts[0] !== 'api') return false;
|
|
53
|
+
const method = req.method ?? 'GET';
|
|
54
|
+
try {
|
|
55
|
+
if (parts.length === 2 && parts[1] === 'project' && method === 'GET') {
|
|
56
|
+
sendJson(res, 200, await projectListing(ctx));
|
|
57
|
+
} else if (parts.length === 3 && parts[1] === 'videos' && (method === 'GET' || method === 'PUT')) {
|
|
58
|
+
const file = videoPath(ctx, parts[2] as string);
|
|
59
|
+
if (!file.ok) return sendJson(res, file.status, { ok: false, issues: [issue(file.message)] }), true;
|
|
60
|
+
// One spelling per file, so the write queue holds on case-insensitive file systems too.
|
|
61
|
+
const onDisk = await canonicalPath(file.path);
|
|
62
|
+
if (method === 'GET') await getVideo(res, onDisk);
|
|
63
|
+
else await putVideo(req, res, onDisk);
|
|
64
|
+
} else if (parts.length === 2 && parts[1] === 'videos' && method === 'POST') {
|
|
65
|
+
await postVideo(req, res, ctx);
|
|
66
|
+
} else if (parts.length === 2 && parts[1] === 'library-tour' && method === 'POST') {
|
|
67
|
+
await postLibraryTour(res, ctx);
|
|
68
|
+
} else if (parts.length === 2 && parts[1] === 'render' && method === 'POST') {
|
|
69
|
+
await postRender(req, res, ctx);
|
|
70
|
+
} else if (parts.length === 3 && parts[1] === 'render' && parts[2] === 'jobs' && method === 'GET') {
|
|
71
|
+
sendJson(res, 200, ctx.jobs?.list() ?? []);
|
|
72
|
+
} else if (parts.length === 4 && parts[1] === 'render' && parts[3] === 'events' && method === 'GET') {
|
|
73
|
+
renderEvents(req, res, ctx, parts[2] as string);
|
|
74
|
+
} else if (parts.length === 5 && parts[1] === 'speech' && parts[2] === 'jobs' && parts[4] === 'events' && method === 'GET') {
|
|
75
|
+
speechEvents(req, res, ctx, parts[3] as string);
|
|
76
|
+
} else if (parts.length === 3 && parts[1] === 'speech' && (method === 'GET' || method === 'POST')) {
|
|
77
|
+
if (!ctx.speech) return sendJson(res, 501, { ok: false, issues: [issue('Voice-over is not available on this server')] }), true;
|
|
78
|
+
if (method === 'GET') await getSpeech(res, ctx, ctx.speech, parts[2] as string);
|
|
79
|
+
else await postSpeech(req, res, ctx, ctx.speech, parts[2] as string);
|
|
80
|
+
} else {
|
|
81
|
+
sendJson(res, 404, { ok: false, issues: [issue(`No route ${method} ${url.pathname}`)] });
|
|
82
|
+
}
|
|
83
|
+
} catch (err) {
|
|
84
|
+
if (!res.headersSent) sendJson(res, 500, { ok: false, issues: [issue(errorMessage(err))] });
|
|
85
|
+
else res.end();
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function projectListing(ctx: ApiContext): Promise<{ name: string; videos: { file: string; title: string }[]; outDir: string }> {
|
|
91
|
+
let entries: string[] = [];
|
|
92
|
+
try {
|
|
93
|
+
entries = await fs.readdir(ctx.videosDir);
|
|
94
|
+
} catch {
|
|
95
|
+
entries = [];
|
|
96
|
+
}
|
|
97
|
+
const files = entries.filter((f) => f.endsWith(VIDEO_SUFFIX)).sort();
|
|
98
|
+
const videos = await Promise.all(
|
|
99
|
+
files.map(async (file) => {
|
|
100
|
+
let title = file.slice(0, -VIDEO_SUFFIX.length);
|
|
101
|
+
try {
|
|
102
|
+
const json = JSON.parse(await fs.readFile(path.join(ctx.videosDir, file), 'utf8')) as { title?: unknown };
|
|
103
|
+
if (typeof json.title === 'string' && json.title) title = json.title;
|
|
104
|
+
} catch {
|
|
105
|
+
// unreadable files are still listed, under their file name
|
|
106
|
+
}
|
|
107
|
+
return { file, title };
|
|
108
|
+
}),
|
|
109
|
+
);
|
|
110
|
+
return { name: ctx.name, videos, outDir: ctx.outDir };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
type PathResult = { ok: true; path: string } | { ok: false; status: number; message: string };
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Resolves a video file name inside videosDir. Only plain `<name>.video.json` names directly in
|
|
117
|
+
* videosDir are accepted; anything that resolves elsewhere (.., slashes, absolute) is refused.
|
|
118
|
+
*/
|
|
119
|
+
export function videoPath(ctx: Pick<ApiContext, 'videosDir'>, raw: string): PathResult {
|
|
120
|
+
let name: string;
|
|
121
|
+
try {
|
|
122
|
+
name = decodeURIComponent(raw);
|
|
123
|
+
} catch {
|
|
124
|
+
return { ok: false, status: 400, message: `Invalid file name "${raw}"` };
|
|
125
|
+
}
|
|
126
|
+
const dir = path.resolve(ctx.videosDir);
|
|
127
|
+
const resolved = path.resolve(dir, name);
|
|
128
|
+
if (path.dirname(resolved) !== dir || name.includes('/') || name.includes('\\') || name.includes('\0')) {
|
|
129
|
+
return { ok: false, status: 403, message: `"${name}" is outside the videos folder` };
|
|
130
|
+
}
|
|
131
|
+
if (!name.endsWith(VIDEO_SUFFIX) || name.length === VIDEO_SUFFIX.length) {
|
|
132
|
+
return { ok: false, status: 400, message: `"${name}" must be named <name>${VIDEO_SUFFIX}` };
|
|
133
|
+
}
|
|
134
|
+
return { ok: true, path: resolved };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** ETag of a video file: the quoted sha1 (hex) of its bytes. */
|
|
138
|
+
export function etagOf(bytes: Buffer | string): string {
|
|
139
|
+
return `"${createHash('sha1').update(bytes).digest('hex')}"`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The file's bytes and ETag; null when it can't be read. */
|
|
143
|
+
async function readWithEtag(file: string): Promise<{ text: string; etag: string } | null> {
|
|
144
|
+
try {
|
|
145
|
+
const bytes = await fs.readFile(file);
|
|
146
|
+
return { text: bytes.toString('utf8'), etag: etagOf(bytes) };
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** True when an If-Match header (one or more entity tags, quoted or not, W/ ignored) names etag. */
|
|
153
|
+
export function ifMatchMatches(header: string, etag: string): boolean {
|
|
154
|
+
const bare = (t: string): string => t.trim().replace(/^W\//, '').replace(/^"(.*)"$/, '$1');
|
|
155
|
+
return header.split(',').some((t) => bare(t) !== '' && bare(t) === bare(etag));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function getVideo(res: ServerResponse, file: string): Promise<void> {
|
|
159
|
+
const current = await readWithEtag(file);
|
|
160
|
+
if (!current) {
|
|
161
|
+
sendJson(res, 404, { ok: false, issues: [issue(`${path.basename(file)} not found`)] });
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
// The ETag also goes out with 422, so the editor can overwrite a broken file deliberately.
|
|
165
|
+
const headers = { ETag: current.etag };
|
|
166
|
+
let json: unknown;
|
|
167
|
+
try {
|
|
168
|
+
json = JSON.parse(current.text);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
sendJson(res, 422, { ok: false, issues: [issue(`Invalid JSON: ${errorMessage(err)}`)] }, headers);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const checked = checkDoc(json);
|
|
174
|
+
if (checked.ok) sendJson(res, 200, checked.doc, headers);
|
|
175
|
+
else sendJson(res, 422, { ok: false, issues: checked.issues, doc: json }, headers);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Per-file write queue: the If-Match check and the write of one PUT never interleave with another's. */
|
|
179
|
+
const writeQueues = new Map<string, Promise<void>>();
|
|
180
|
+
|
|
181
|
+
async function serialized(file: string, fn: () => Promise<void>): Promise<void> {
|
|
182
|
+
const prev = writeQueues.get(file) ?? Promise.resolve();
|
|
183
|
+
const run = prev.then(fn, fn);
|
|
184
|
+
const tail = run.then(
|
|
185
|
+
() => undefined,
|
|
186
|
+
() => undefined,
|
|
187
|
+
);
|
|
188
|
+
writeQueues.set(file, tail);
|
|
189
|
+
try {
|
|
190
|
+
await run;
|
|
191
|
+
} finally {
|
|
192
|
+
if (writeQueues.get(file) === tail) writeQueues.delete(file);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function putVideo(req: IncomingMessage, res: ServerResponse, file: string): Promise<void> {
|
|
197
|
+
if (!(await exists(file))) return sendJson(res, 404, { ok: false, issues: [issue(`${path.basename(file)} not found (create it with POST /api/videos)`)] });
|
|
198
|
+
const ifMatch = req.headers['if-match'];
|
|
199
|
+
if (typeof ifMatch !== 'string' || ifMatch.trim() === '') {
|
|
200
|
+
req.resume();
|
|
201
|
+
return sendJson(res, 428, { ok: false, issues: [issue('If-Match header required: send the ETag of the last GET/PUT')] });
|
|
202
|
+
}
|
|
203
|
+
const body = await readJson(req);
|
|
204
|
+
if (!body.ok) return sendJson(res, 400, { ok: false, issues: [issue(body.message)] });
|
|
205
|
+
const checked = checkDoc(body.value);
|
|
206
|
+
if (!checked.ok) return sendJson(res, 400, { ok: false, issues: checked.issues });
|
|
207
|
+
await serialized(file, async () => {
|
|
208
|
+
const current = await readWithEtag(file);
|
|
209
|
+
if (!current) return sendJson(res, 404, { ok: false, issues: [issue(`${path.basename(file)} not found (create it with POST /api/videos)`)] });
|
|
210
|
+
if (!ifMatchMatches(ifMatch, current.etag)) {
|
|
211
|
+
let doc: unknown = null;
|
|
212
|
+
try {
|
|
213
|
+
const json: unknown = JSON.parse(current.text);
|
|
214
|
+
const parsed = checkDoc(json);
|
|
215
|
+
doc = parsed.ok ? parsed.doc : json;
|
|
216
|
+
} catch {
|
|
217
|
+
doc = null;
|
|
218
|
+
}
|
|
219
|
+
return sendJson(
|
|
220
|
+
res,
|
|
221
|
+
409,
|
|
222
|
+
{ ok: false, reason: 'stale', etag: current.etag, doc, issues: [issue(`${path.basename(file)} changed on disk since that ETag`)] },
|
|
223
|
+
{ ETag: current.etag },
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
const etag = await writeJsonAtomic(file, body.value);
|
|
227
|
+
sendJson(res, 200, { ok: true, etag }, { ETag: etag });
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function postVideo(req: IncomingMessage, res: ServerResponse, ctx: ApiContext): Promise<void> {
|
|
232
|
+
const body = await readJson(req);
|
|
233
|
+
if (!body.ok) return sendJson(res, 400, { ok: false, issues: [issue(body.message)] });
|
|
234
|
+
const { file, doc } = (body.value ?? {}) as { file?: unknown; doc?: unknown };
|
|
235
|
+
if (typeof file !== 'string') return sendJson(res, 400, { ok: false, issues: [issue('body.file must be a string', ['file'])] });
|
|
236
|
+
const target = videoPath(ctx, encodeURIComponent(file));
|
|
237
|
+
if (!target.ok) return sendJson(res, target.status, { ok: false, issues: [issue(target.message, ['file'])] });
|
|
238
|
+
const checked = checkDoc(doc);
|
|
239
|
+
if (!checked.ok) return sendJson(res, 400, { ok: false, issues: checked.issues.map((i) => ({ ...i, path: ['doc', ...i.path] })) });
|
|
240
|
+
if (await exists(target.path)) return sendJson(res, 409, { ok: false, issues: [issue(`${file} already exists`, ['file'])] });
|
|
241
|
+
await fs.mkdir(path.dirname(target.path), { recursive: true });
|
|
242
|
+
const etag = await writeJsonAtomic(target.path, doc);
|
|
243
|
+
sendJson(res, 200, { ok: true, etag }, { ETag: etag });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The file name the library tour gets in videosDir. */
|
|
247
|
+
const LIBRARY_TOUR_FILE = 'library-tour.video.json';
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* POST /api/library-tour: copies the tour's images into assetsDir and the tour video into videosDir, never
|
|
251
|
+
* overwriting a file that is already there. `created` is false when the video was there already.
|
|
252
|
+
*/
|
|
253
|
+
async function postLibraryTour(res: ServerResponse, ctx: ApiContext): Promise<void> {
|
|
254
|
+
const tour = ctx.libraryTour;
|
|
255
|
+
if (!tour) return sendJson(res, 404, { ok: false, issues: [issue('The library tour is not part of this beatsheet')] });
|
|
256
|
+
// Images first, so the video never shows up before the images it uses.
|
|
257
|
+
await fs.mkdir(ctx.assetsDir, { recursive: true });
|
|
258
|
+
cpSync(tour.assets, ctx.assetsDir, { recursive: true, force: false, errorOnExist: false });
|
|
259
|
+
await fs.mkdir(ctx.videosDir, { recursive: true });
|
|
260
|
+
let created = true;
|
|
261
|
+
try {
|
|
262
|
+
await fs.copyFile(tour.video, path.join(ctx.videosDir, LIBRARY_TOUR_FILE), fsConstants.COPYFILE_EXCL);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;
|
|
265
|
+
created = false;
|
|
266
|
+
}
|
|
267
|
+
sendJson(res, 200, { file: LIBRARY_TOUR_FILE, created });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function postRender(req: IncomingMessage, res: ServerResponse, ctx: ApiContext): Promise<void> {
|
|
271
|
+
if (!ctx.jobs) return sendJson(res, 501, { ok: false, issues: [issue('Rendering is not available on this server')] });
|
|
272
|
+
const body = await readJson(req);
|
|
273
|
+
if (!body.ok) return sendJson(res, 400, { ok: false, issues: [issue(body.message)] });
|
|
274
|
+
const { file, formats, mp4, gif } = (body.value ?? {}) as { file?: unknown; formats?: unknown; mp4?: unknown; gif?: unknown };
|
|
275
|
+
if (typeof file !== 'string') return sendJson(res, 400, { ok: false, issues: [issue('body.file must be a string', ['file'])] });
|
|
276
|
+
const target = videoPath(ctx, encodeURIComponent(file));
|
|
277
|
+
if (!target.ok) return sendJson(res, target.status, { ok: false, issues: [issue(target.message, ['file'])] });
|
|
278
|
+
if (!(await exists(target.path))) return sendJson(res, 404, { ok: false, issues: [issue(`${file} not found`, ['file'])] });
|
|
279
|
+
// Jobs and output names use the on-disk spelling: on macOS OCTOBER.video.json is october.video.json.
|
|
280
|
+
const onDisk = await canonicalPath(target.path);
|
|
281
|
+
if (formats !== undefined) {
|
|
282
|
+
if (!Array.isArray(formats) || formats.length === 0 || formats.some((f) => !FORMAT_IDS.includes(f as FormatId))) {
|
|
283
|
+
return sendJson(res, 400, { ok: false, issues: [issue(`formats must be a non-empty list of ${FORMAT_IDS.join(', ')}`, ['formats'])] });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const gifIssue = renderGifIssue(mp4, gif);
|
|
287
|
+
if (gifIssue) return sendJson(res, 400, { ok: false, issues: [gifIssue] });
|
|
288
|
+
if (gif !== undefined) {
|
|
289
|
+
// Scene ids and time ranges are checked against the file as saved, before a job starts.
|
|
290
|
+
const doc = await readDoc(onDisk);
|
|
291
|
+
if (doc) {
|
|
292
|
+
const r = resolveGifRender(doc, gif as GifOptions);
|
|
293
|
+
if (!r.ok) {
|
|
294
|
+
return sendJson(res, 400, { ok: false, issues: [issue(r.message, r.stored ? ['doc', 'export', 'gif', r.field] : ['gif', r.field])] });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// One job per file: a second request while one runs gets that job back (existing: true).
|
|
299
|
+
const { job, existing } = ctx.jobs.start(
|
|
300
|
+
path.basename(onDisk),
|
|
301
|
+
(formats as FormatId[] | undefined) ?? (await docFormats(onDisk)),
|
|
302
|
+
{ mp4: mp4 !== false, ...(gif !== undefined ? { gif: gif as GifOptions } : {}) },
|
|
303
|
+
);
|
|
304
|
+
sendJson(res, 200, { jobId: job.id, existing });
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** The doc's own formats (for the job list); undefined when the file doesn't parse (the job then reports the error). */
|
|
308
|
+
async function docFormats(file: string): Promise<FormatId[] | undefined> {
|
|
309
|
+
return (await readDoc(file))?.formats;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function readDoc(file: string): Promise<VideoDoc | undefined> {
|
|
313
|
+
try {
|
|
314
|
+
const checked = checkDoc(JSON.parse(await fs.readFile(file, 'utf8')));
|
|
315
|
+
return checked.ok ? checked.doc : undefined;
|
|
316
|
+
} catch {
|
|
317
|
+
return undefined;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const GIF_OPTION_KEYS = new Set(['preset', 'fps', 'width', 'range', 'loop']);
|
|
322
|
+
|
|
323
|
+
/** Shape of the render body's mp4 and gif (GifOptions); null when fine. */
|
|
324
|
+
export function renderGifIssue(mp4: unknown, gif: unknown): ValidationIssue | null {
|
|
325
|
+
if (mp4 !== undefined && typeof mp4 !== 'boolean') return issue('mp4 must be true or false', ['mp4']);
|
|
326
|
+
if (gif !== undefined) {
|
|
327
|
+
if (typeof gif !== 'object' || gif === null || Array.isArray(gif)) return issue('gif must be an object of GIF options', ['gif']);
|
|
328
|
+
const unknown = Object.keys(gif).find((k) => !GIF_OPTION_KEYS.has(k));
|
|
329
|
+
if (unknown) return issue(`unknown GIF option "${unknown}" (known: ${[...GIF_OPTION_KEYS].join(', ')})`, ['gif', unknown]);
|
|
330
|
+
const found = gifSettingsIssues(gif as GifOptions)[0];
|
|
331
|
+
if (found) return issue(found.message, ['gif', found.field]);
|
|
332
|
+
}
|
|
333
|
+
if (mp4 === false && gif === undefined) return issue('Nothing to render: mp4 is false and there is no gif', ['mp4']);
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function renderEvents(req: IncomingMessage, res: ServerResponse, ctx: ApiContext, jobId: string): void {
|
|
338
|
+
const job = ctx.jobs?.get(jobId);
|
|
339
|
+
if (!job) return sendJson(res, 404, { ok: false, issues: [issue(`No render job "${jobId}"`)] });
|
|
340
|
+
streamEvents(req, res, job, isTerminal, 'render');
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
// Voice-over
|
|
345
|
+
|
|
346
|
+
/** A video of the speech routes: its on-disk path and doc, or the answer that was sent instead. */
|
|
347
|
+
async function speechVideo(res: ServerResponse, ctx: ApiContext, raw: string): Promise<{ path: string; doc: VideoDoc } | null> {
|
|
348
|
+
const file = videoPath(ctx, raw);
|
|
349
|
+
if (!file.ok) return sendJson(res, file.status, { ok: false, issues: [issue(file.message)] }), null;
|
|
350
|
+
const onDisk = await canonicalPath(file.path);
|
|
351
|
+
let text: string;
|
|
352
|
+
try {
|
|
353
|
+
text = await fs.readFile(onDisk, 'utf8');
|
|
354
|
+
} catch {
|
|
355
|
+
return sendJson(res, 404, { ok: false, issues: [issue(`${path.basename(onDisk)} not found`)] }), null;
|
|
356
|
+
}
|
|
357
|
+
let json: unknown;
|
|
358
|
+
try {
|
|
359
|
+
json = JSON.parse(text);
|
|
360
|
+
} catch (err) {
|
|
361
|
+
return sendJson(res, 422, { ok: false, issues: [issue(`Invalid JSON: ${errorMessage(err)}`)] }), null;
|
|
362
|
+
}
|
|
363
|
+
const checked = checkDoc(json);
|
|
364
|
+
if (!checked.ok) return sendJson(res, 422, { ok: false, issues: checked.issues }), null;
|
|
365
|
+
return { path: onDisk, doc: checked.doc };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function getSpeech(res: ServerResponse, ctx: ApiContext, speech: SpeechApiContext, raw: string): Promise<void> {
|
|
369
|
+
const v = await speechVideo(res, ctx, raw);
|
|
370
|
+
if (v) sendJson(res, 200, await speechStatus({ ...v, project: await speech.project() }, speech.plugins));
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const SPEECH_REQUEST_KEYS = new Set(['scenes', 'force']);
|
|
374
|
+
|
|
375
|
+
/** Shape of a SpeechJobRequest body; null when fine. */
|
|
376
|
+
export function speechRequestIssue(body: unknown): ValidationIssue | null {
|
|
377
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) return issue('the body must be an object: { scenes?: string[]; force?: boolean }');
|
|
378
|
+
const unknown = Object.keys(body).find((k) => !SPEECH_REQUEST_KEYS.has(k));
|
|
379
|
+
if (unknown) return issue(`unknown option "${unknown}" (known: ${[...SPEECH_REQUEST_KEYS].join(', ')})`, [unknown]);
|
|
380
|
+
const { scenes, force } = body as { scenes?: unknown; force?: unknown };
|
|
381
|
+
if (scenes !== undefined && (!Array.isArray(scenes) || scenes.length === 0 || scenes.some((s) => typeof s !== 'string' || s === ''))) {
|
|
382
|
+
return issue('scenes must be a non-empty list of scene ids', ['scenes']);
|
|
383
|
+
}
|
|
384
|
+
if (force !== undefined && typeof force !== 'boolean') return issue('force must be true or false', ['force']);
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Starts a speech job (one per file). What the video or the request gets wrong (no voice, unknown
|
|
390
|
+
* engine or scene, the engine's plugin not installed) answers 400 before a job starts; the engine's
|
|
391
|
+
* own errors (a model mismatch, a failed load) end the job with an 'error' event.
|
|
392
|
+
*/
|
|
393
|
+
async function postSpeech(req: IncomingMessage, res: ServerResponse, ctx: ApiContext, speech: SpeechApiContext, raw: string): Promise<void> {
|
|
394
|
+
const body = await readJson(req);
|
|
395
|
+
if (!body.ok) return sendJson(res, 400, { ok: false, issues: [issue(body.message)] });
|
|
396
|
+
const bad = speechRequestIssue(body.value);
|
|
397
|
+
if (bad) return sendJson(res, 400, { ok: false, issues: [bad] });
|
|
398
|
+
const request = body.value as SpeechJobRequest;
|
|
399
|
+
const v = await speechVideo(res, ctx, raw);
|
|
400
|
+
if (!v) return;
|
|
401
|
+
const project = await speech.project();
|
|
402
|
+
try {
|
|
403
|
+
const plan = planSpeech({ ...v, project }, request);
|
|
404
|
+
if (plan.todo.length > 0 && plan.engine && !speech.plugins.installed(plan.engine)) {
|
|
405
|
+
return sendJson(res, 400, { ok: false, issues: [issue(pluginMissingMessage(plan.engine, project.root), ['voice'])] });
|
|
406
|
+
}
|
|
407
|
+
} catch (err) {
|
|
408
|
+
if (err instanceof SpeechPlanError) return sendJson(res, 400, { ok: false, issues: [issue(err.message, err.path)] });
|
|
409
|
+
throw err;
|
|
410
|
+
}
|
|
411
|
+
const { job, existing } = speech.jobs.start(path.basename(v.path), request);
|
|
412
|
+
sendJson(res, 200, { jobId: job.id, existing });
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function speechEvents(req: IncomingMessage, res: ServerResponse, ctx: ApiContext, jobId: string): void {
|
|
416
|
+
const job = ctx.speech?.jobs.get(jobId);
|
|
417
|
+
if (!job) return sendJson(res, 404, { ok: false, issues: [issue(`No speech job "${jobId}"`)] });
|
|
418
|
+
streamEvents(req, res, job, isSpeechTerminal, 'speech');
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ---------------------------------------------------------------------------
|
|
422
|
+
|
|
423
|
+
/** Structure check with core's parseDoc; issues carry JSON paths when the zod schema is available. */
|
|
424
|
+
export function checkDoc(json: unknown): { ok: true; doc: VideoDoc } | { ok: false; issues: ValidationIssue[] } {
|
|
425
|
+
try {
|
|
426
|
+
return { ok: true, doc: parseDoc(json) };
|
|
427
|
+
} catch (err) {
|
|
428
|
+
return { ok: false, issues: schemaIssues(json) ?? [issue(errorMessage(err))] };
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function schemaIssues(json: unknown): ValidationIssue[] | null {
|
|
433
|
+
const schema = videoDocSchema as unknown as { safeParse?: (v: unknown) => { success: boolean; error?: { issues: { path: PropertyKey[]; message: string }[] } } } | null;
|
|
434
|
+
if (!schema || typeof schema.safeParse !== 'function') return null;
|
|
435
|
+
try {
|
|
436
|
+
const result = schema.safeParse(json);
|
|
437
|
+
if (result.success || !result.error) return null;
|
|
438
|
+
return result.error.issues.map((i) => ({
|
|
439
|
+
path: i.path.map((p) => (typeof p === 'number' ? p : String(p))),
|
|
440
|
+
message: i.message,
|
|
441
|
+
severity: 'error' as const,
|
|
442
|
+
}));
|
|
443
|
+
} catch {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function issue(message: string, p: (string | number)[] = []): ValidationIssue {
|
|
449
|
+
return { path: p, message, severity: 'error' };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export function sendJson(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
|
|
453
|
+
const text = JSON.stringify(body);
|
|
454
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...headers });
|
|
455
|
+
res.end(text);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function readJson(req: IncomingMessage): Promise<{ ok: true; value: unknown } | { ok: false; message: string }> {
|
|
459
|
+
const chunks: Buffer[] = [];
|
|
460
|
+
let size = 0;
|
|
461
|
+
for await (const chunk of req) {
|
|
462
|
+
size += (chunk as Buffer).length;
|
|
463
|
+
if (size > MAX_BODY) return { ok: false, message: 'Body too large' };
|
|
464
|
+
chunks.push(chunk as Buffer);
|
|
465
|
+
}
|
|
466
|
+
try {
|
|
467
|
+
return { ok: true, value: JSON.parse(Buffer.concat(chunks).toString('utf8')) };
|
|
468
|
+
} catch (err) {
|
|
469
|
+
return { ok: false, message: `Invalid JSON: ${errorMessage(err)}` };
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Pretty JSON, 2-space indent, trailing newline; written to a temp file and renamed. Returns the new ETag. */
|
|
474
|
+
export async function writeJsonAtomic(file: string, value: unknown): Promise<string> {
|
|
475
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
476
|
+
const bytes = Buffer.from(JSON.stringify(value, null, 2) + '\n', 'utf8');
|
|
477
|
+
try {
|
|
478
|
+
await fs.writeFile(tmp, bytes);
|
|
479
|
+
await fs.rename(tmp, file);
|
|
480
|
+
} catch (err) {
|
|
481
|
+
await fs.rm(tmp, { force: true });
|
|
482
|
+
throw err;
|
|
483
|
+
}
|
|
484
|
+
return etagOf(bytes);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
async function exists(file: string): Promise<boolean> {
|
|
488
|
+
try {
|
|
489
|
+
await fs.access(file);
|
|
490
|
+
return true;
|
|
491
|
+
} catch {
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
494
|
+
}
|