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,210 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import type { FormatId, GifOptions, RenderEvent, RenderMedia, SpeechEvent, SpeechJobRequest } from '@beatsheet/core';
|
|
3
|
+
import { errorMessage } from '../project';
|
|
4
|
+
import { isSpeechTerminal, isTerminal } from './sse';
|
|
5
|
+
|
|
6
|
+
/** What a job writes besides the formats: the MP4 (default) and/or a GIF with these options. */
|
|
7
|
+
export interface RenderJobOptions {
|
|
8
|
+
mp4: boolean;
|
|
9
|
+
gif?: GifOptions;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Does the actual render; emits RenderEvents. Resolves when every format is written. */
|
|
13
|
+
export type RenderRunner = (
|
|
14
|
+
file: string,
|
|
15
|
+
formats: FormatId[] | undefined,
|
|
16
|
+
emit: (e: RenderEvent) => void,
|
|
17
|
+
opts?: RenderJobOptions,
|
|
18
|
+
) => Promise<void>;
|
|
19
|
+
|
|
20
|
+
/** The outputs of a job's options. */
|
|
21
|
+
export function jobMedia(opts?: RenderJobOptions): RenderMedia[] {
|
|
22
|
+
return [...(opts?.mp4 !== false ? (['mp4'] as const) : []), ...(opts?.gif ? (['gif'] as const) : [])];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type RenderJobState = 'running' | 'done' | 'error';
|
|
26
|
+
|
|
27
|
+
export interface RenderJob {
|
|
28
|
+
id: string;
|
|
29
|
+
file: string;
|
|
30
|
+
/** Requested formats, else the doc's own (empty when the doc could not be read). */
|
|
31
|
+
formats: FormatId[];
|
|
32
|
+
media: RenderMedia[];
|
|
33
|
+
events: RenderEvent[];
|
|
34
|
+
finished: boolean;
|
|
35
|
+
state: RenderJobState;
|
|
36
|
+
/** Listener gets every new event; returns an unsubscribe fn. */
|
|
37
|
+
subscribe(listener: (e: RenderEvent) => void): () => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Entry of GET /api/render/jobs. */
|
|
41
|
+
export interface RenderJobSummary {
|
|
42
|
+
jobId: string;
|
|
43
|
+
file: string;
|
|
44
|
+
formats: FormatId[];
|
|
45
|
+
media: RenderMedia[];
|
|
46
|
+
state: RenderJobState;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Render jobs of the studio server. Every job keeps its full event log, so an SSE client that
|
|
51
|
+
* connects late still gets everything. The last event is always { phase: 'done' } (no format)
|
|
52
|
+
* or { type: 'error' }. At most one job runs per file: starting another while it runs returns
|
|
53
|
+
* the running job with existing: true (two renders would write the same output files).
|
|
54
|
+
*/
|
|
55
|
+
export class RenderJobs {
|
|
56
|
+
private readonly jobs = new Map<string, RenderJob>();
|
|
57
|
+
/** file -> its running job. */
|
|
58
|
+
private readonly running = new Map<string, RenderJob>();
|
|
59
|
+
|
|
60
|
+
constructor(private readonly runner: RenderRunner) {}
|
|
61
|
+
|
|
62
|
+
start(file: string, formats?: FormatId[], opts?: RenderJobOptions): { job: RenderJob; existing: boolean } {
|
|
63
|
+
const active = this.running.get(file);
|
|
64
|
+
if (active && !active.finished) return { job: active, existing: true };
|
|
65
|
+
const id = randomUUID().slice(0, 8);
|
|
66
|
+
const listeners = new Set<(e: RenderEvent) => void>();
|
|
67
|
+
const job: RenderJob = {
|
|
68
|
+
id,
|
|
69
|
+
file,
|
|
70
|
+
formats: formats ? [...formats] : [],
|
|
71
|
+
media: jobMedia(opts),
|
|
72
|
+
events: [],
|
|
73
|
+
finished: false,
|
|
74
|
+
state: 'running',
|
|
75
|
+
subscribe(listener) {
|
|
76
|
+
listeners.add(listener);
|
|
77
|
+
return () => listeners.delete(listener);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
const emit = (e: RenderEvent): void => {
|
|
81
|
+
if (job.finished) return;
|
|
82
|
+
job.events.push(e);
|
|
83
|
+
if (isTerminal(e)) {
|
|
84
|
+
job.finished = true;
|
|
85
|
+
job.state = e.type === 'error' ? 'error' : 'done';
|
|
86
|
+
if (this.running.get(file) === job) this.running.delete(file);
|
|
87
|
+
}
|
|
88
|
+
for (const l of [...listeners]) l(e);
|
|
89
|
+
};
|
|
90
|
+
this.jobs.set(id, job);
|
|
91
|
+
this.running.set(file, job);
|
|
92
|
+
// Start on the next tick so the caller can answer { jobId } first.
|
|
93
|
+
setImmediate(() => {
|
|
94
|
+
this.runner(file, formats, emit, opts).then(
|
|
95
|
+
() => emit({ type: 'phase', phase: 'done' }),
|
|
96
|
+
(err: unknown) => emit({ type: 'error', message: errorMessage(err) }),
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
return { job, existing: false };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
get(id: string): RenderJob | undefined {
|
|
103
|
+
return this.jobs.get(id);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Every job of this server, oldest first. */
|
|
107
|
+
list(): RenderJobSummary[] {
|
|
108
|
+
return [...this.jobs.values()].map((j) => ({ jobId: j.id, file: j.file, formats: [...j.formats], media: [...j.media], state: j.state }));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Resolves when every running job has finished. */
|
|
112
|
+
async idle(): Promise<void> {
|
|
113
|
+
const running = [...this.jobs.values()].filter((j) => !j.finished);
|
|
114
|
+
await Promise.all(
|
|
115
|
+
running.map(
|
|
116
|
+
(j) =>
|
|
117
|
+
new Promise<void>((resolve) => {
|
|
118
|
+
const off = j.subscribe((e) => {
|
|
119
|
+
if (isTerminal(e)) {
|
|
120
|
+
off();
|
|
121
|
+
resolve();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
if (j.finished) resolve();
|
|
125
|
+
}),
|
|
126
|
+
),
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
/** Speaks a video's narration (speakVideo), emitting SpeechEvents; resolves when every clip is written. */
|
|
134
|
+
export type SpeechRunner = (file: string, req: SpeechJobRequest, emit: (e: SpeechEvent) => void) => Promise<void>;
|
|
135
|
+
|
|
136
|
+
export interface SpeechJob {
|
|
137
|
+
id: string;
|
|
138
|
+
file: string;
|
|
139
|
+
request: SpeechJobRequest;
|
|
140
|
+
events: SpeechEvent[];
|
|
141
|
+
finished: boolean;
|
|
142
|
+
state: RenderJobState;
|
|
143
|
+
subscribe(listener: (e: SpeechEvent) => void): () => void;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Speech jobs of the server (POST /api/speech/:file), like render jobs: a full event log per job
|
|
148
|
+
* (late SSE clients get everything), the last event { type: 'done' } or { type: 'error' }, at most
|
|
149
|
+
* one job per file (another request while it runs gets it back with existing: true). Jobs of
|
|
150
|
+
* different files run one after another: they share one engine, and speaking is CPU-bound.
|
|
151
|
+
*/
|
|
152
|
+
export class SpeechJobs {
|
|
153
|
+
private readonly jobs = new Map<string, SpeechJob>();
|
|
154
|
+
private readonly running = new Map<string, SpeechJob>();
|
|
155
|
+
private queue: Promise<void> = Promise.resolve();
|
|
156
|
+
|
|
157
|
+
constructor(private readonly runner: SpeechRunner) {}
|
|
158
|
+
|
|
159
|
+
start(file: string, request: SpeechJobRequest = {}): { job: SpeechJob; existing: boolean } {
|
|
160
|
+
const active = this.running.get(file);
|
|
161
|
+
if (active && !active.finished) return { job: active, existing: true };
|
|
162
|
+
const listeners = new Set<(e: SpeechEvent) => void>();
|
|
163
|
+
const job: SpeechJob = {
|
|
164
|
+
id: randomUUID().slice(0, 8),
|
|
165
|
+
file,
|
|
166
|
+
request,
|
|
167
|
+
events: [],
|
|
168
|
+
finished: false,
|
|
169
|
+
state: 'running',
|
|
170
|
+
subscribe(listener) {
|
|
171
|
+
listeners.add(listener);
|
|
172
|
+
return () => listeners.delete(listener);
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
const emit = (e: SpeechEvent): void => {
|
|
176
|
+
if (job.finished) return;
|
|
177
|
+
job.events.push(e);
|
|
178
|
+
if (isSpeechTerminal(e)) {
|
|
179
|
+
job.finished = true;
|
|
180
|
+
job.state = e.type === 'error' ? 'error' : 'done';
|
|
181
|
+
if (this.running.get(file) === job) this.running.delete(file);
|
|
182
|
+
}
|
|
183
|
+
for (const l of [...listeners]) l(e);
|
|
184
|
+
};
|
|
185
|
+
this.jobs.set(job.id, job);
|
|
186
|
+
this.running.set(file, job);
|
|
187
|
+
// After the jobs before it, and never before the caller has answered { jobId }.
|
|
188
|
+
this.queue = this.queue.then(
|
|
189
|
+
() =>
|
|
190
|
+
new Promise<void>((resolve) => {
|
|
191
|
+
setImmediate(() => {
|
|
192
|
+
Promise.resolve().then(() => this.runner(file, request, emit)).then(
|
|
193
|
+
() => emit({ type: 'done' }),
|
|
194
|
+
(err: unknown) => emit({ type: 'error', message: errorMessage(err) }),
|
|
195
|
+
).finally(resolve);
|
|
196
|
+
});
|
|
197
|
+
}),
|
|
198
|
+
);
|
|
199
|
+
return { job, existing: false };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
get(id: string): SpeechJob | undefined {
|
|
203
|
+
return this.jobs.get(id);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Resolves when every job has finished. */
|
|
207
|
+
async idle(): Promise<void> {
|
|
208
|
+
await this.queue;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http';
|
|
2
|
+
|
|
3
|
+
/** Host names the server answers to (with its own port). Anything else is refused (DNS rebinding). */
|
|
4
|
+
export const LOOPBACK_HOSTS: readonly string[] = ['localhost', '127.0.0.1', '[::1]'];
|
|
5
|
+
|
|
6
|
+
/** True when the Host header is localhost / 127.0.0.1 / [::1] with exactly this port. */
|
|
7
|
+
export function isAllowedHost(hostHeader: string | undefined, port: number): boolean {
|
|
8
|
+
if (!hostHeader) return false;
|
|
9
|
+
const host = hostHeader.trim().toLowerCase();
|
|
10
|
+
return LOOPBACK_HOSTS.some((h) => host === `${h}:${port}`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The server's own origins: http://<loopback host>:<port>. */
|
|
14
|
+
export function ownOrigins(port: number): string[] {
|
|
15
|
+
return LOOPBACK_HOSTS.map((h) => `http://${h}:${port}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Refusal {
|
|
19
|
+
status: 403 | 415;
|
|
20
|
+
message: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The server's request guard (see the REST block in @beatsheet/core types.ts):
|
|
25
|
+
* - 403 when the Host header is not a loopback name with the server's port (DNS rebinding);
|
|
26
|
+
* - non-GET/HEAD requests need Content-Type application/json (415 otherwise), so a cross-site
|
|
27
|
+
* form or text/plain fetch can't reach a handler without a CORS preflight;
|
|
28
|
+
* - non-GET/HEAD requests with an Origin header need the server's own origin (403, CSRF).
|
|
29
|
+
* Returns null when the request may proceed.
|
|
30
|
+
*/
|
|
31
|
+
export function checkRequest(req: IncomingMessage, port: number): Refusal | null {
|
|
32
|
+
const host = req.headers.host;
|
|
33
|
+
if (!isAllowedHost(host, port)) {
|
|
34
|
+
return { status: 403, message: `Blocked request. This host (${JSON.stringify(host ?? '')}) is not allowed.` };
|
|
35
|
+
}
|
|
36
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
37
|
+
if (method === 'GET' || method === 'HEAD') return null;
|
|
38
|
+
const origin = req.headers.origin;
|
|
39
|
+
if (origin !== undefined && !ownOrigins(port).includes(origin.toLowerCase())) {
|
|
40
|
+
return { status: 403, message: `Blocked request. Cross-origin ${method} from ${JSON.stringify(origin)} is not allowed.` };
|
|
41
|
+
}
|
|
42
|
+
const type = ((req.headers['content-type'] ?? '').split(';')[0] ?? '').trim().toLowerCase();
|
|
43
|
+
if (type !== 'application/json') {
|
|
44
|
+
return { status: 415, message: `${method} requests need Content-Type: application/json` };
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import http, { type IncomingMessage, type ServerResponse } from 'node:http';
|
|
3
|
+
import type { AddressInfo } from 'node:net';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import type { ViteDevServer } from 'vite';
|
|
6
|
+
import { ASSET_PREFIX, PLAYER_BASE, SPEECH_PREFIX } from '../paths';
|
|
7
|
+
import { projectReloader, type ProjectContext } from '../project';
|
|
8
|
+
import { libraryTourSource } from '../skill';
|
|
9
|
+
import { projectSpeechPlugins, speakVideo, SPEECH_DIR, SPEECH_FILE, type SpeechPlugins } from '../speech';
|
|
10
|
+
import { checkDoc, handleApi, type ApiContext } from './api';
|
|
11
|
+
import { RenderJobs, SpeechJobs, type RenderRunner, type SpeechRunner } from './jobs';
|
|
12
|
+
import { checkRequest } from './security';
|
|
13
|
+
import { notFound, sendFile, serveDir, serveStudio, studioDistDir } from './static';
|
|
14
|
+
import { createPlayerVite } from './vite';
|
|
15
|
+
|
|
16
|
+
export interface ServerOptions {
|
|
17
|
+
project: ProjectContext;
|
|
18
|
+
/** 'studio': HMR, studio app, render jobs. 'render': no HMR, internal use by render/stills/check. */
|
|
19
|
+
mode: 'studio' | 'render';
|
|
20
|
+
/** Overrides project.videosDir (render commands serve the folder of the given file). */
|
|
21
|
+
videosDir?: string;
|
|
22
|
+
/** Default 0 (any free port). */
|
|
23
|
+
port?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Default 127.0.0.1. Whatever the bind address, requests are only answered with a Host header of
|
|
26
|
+
* localhost / 127.0.0.1 / [::1] and this port (see ./security), so other addresses need a tunnel.
|
|
27
|
+
*/
|
|
28
|
+
host?: string;
|
|
29
|
+
/** Runs POST /api/render jobs; it gets the server's base URL. Studio mode only. */
|
|
30
|
+
renderRunner?: (baseUrl: string) => RenderRunner;
|
|
31
|
+
/** Called with the absolute path of every project asset file the server sends (`check` reads the SVGs among them). */
|
|
32
|
+
onAsset?: (file: string) => void;
|
|
33
|
+
/** Skip Vite (API + static only), for tests. */
|
|
34
|
+
noVite?: boolean;
|
|
35
|
+
/** Default: the @beatsheet/studio build folder. */
|
|
36
|
+
studioDir?: string;
|
|
37
|
+
/** Speech engine plugins (POST /api/speech). Default: the project's @beatsheet/voice-* packages, kept for the server's lifetime. */
|
|
38
|
+
speechPlugins?: SpeechPlugins;
|
|
39
|
+
/**
|
|
40
|
+
* The project as beatsheet.config.ts is now, for the speech status and speech jobs. Default:
|
|
41
|
+
* projectReloader(project) (the config imported again after an edit).
|
|
42
|
+
*/
|
|
43
|
+
currentProject?: () => Promise<ProjectContext>;
|
|
44
|
+
/** Lines about speech jobs (the studio prints them). */
|
|
45
|
+
log?: (line: string) => void;
|
|
46
|
+
/** The library tour POST /api/library-tour copies into the project. Default: libraryTourSource(); null: none (404). */
|
|
47
|
+
libraryTour?: { video: string; assets: string } | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface RunningServer {
|
|
51
|
+
url: string;
|
|
52
|
+
port: number;
|
|
53
|
+
vite: ViteDevServer | null;
|
|
54
|
+
jobs: RenderJobs | undefined;
|
|
55
|
+
speechJobs: SpeechJobs;
|
|
56
|
+
close(): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** node:http server: REST API, /project-assets/, the Vite player page at /player/, the studio app at /. */
|
|
60
|
+
export async function startServer(o: ServerOptions): Promise<RunningServer> {
|
|
61
|
+
const host = o.host ?? '127.0.0.1';
|
|
62
|
+
let baseUrl = '';
|
|
63
|
+
const jobs = o.mode === 'studio' && o.renderRunner ? new RenderJobs((file, formats, emit, opts) => o.renderRunner!(baseUrl)(file, formats, emit, opts)) : undefined;
|
|
64
|
+
const videosDir = o.videosDir ?? o.project.videosDir;
|
|
65
|
+
const speechPlugins = o.speechPlugins ?? projectSpeechPlugins(o.project.root);
|
|
66
|
+
const currentProject = o.currentProject ?? projectReloader(o.project, (message) => o.log?.(message));
|
|
67
|
+
const speechJobs = new SpeechJobs(speechRunner(currentProject, videosDir, speechPlugins, o.log));
|
|
68
|
+
const api: ApiContext = {
|
|
69
|
+
name: o.project.name,
|
|
70
|
+
videosDir,
|
|
71
|
+
assetsDir: o.project.assetsDir,
|
|
72
|
+
outDir: o.project.outDir,
|
|
73
|
+
libraryTour: (o.libraryTour === undefined ? libraryTourSource() : o.libraryTour) ?? undefined,
|
|
74
|
+
jobs,
|
|
75
|
+
speech: { project: currentProject, plugins: speechPlugins, jobs: speechJobs },
|
|
76
|
+
};
|
|
77
|
+
const studioDir = o.studioDir ?? studioDistDir();
|
|
78
|
+
let vite: ViteDevServer | null = null;
|
|
79
|
+
let port = 0;
|
|
80
|
+
|
|
81
|
+
const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
|
82
|
+
// Every route (API, project assets, player, studio): loopback Host with our port only, and
|
|
83
|
+
// JSON + our own Origin for writes. Vite's own host check on /player/ and the HMR socket stays.
|
|
84
|
+
const refusal = checkRequest(req, port);
|
|
85
|
+
if (refusal) {
|
|
86
|
+
res.writeHead(refusal.status, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
87
|
+
res.end(refusal.message);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const url = req.url ?? '/';
|
|
91
|
+
const pathname = url.split('?')[0] as string;
|
|
92
|
+
if (pathname === '/api' || pathname.startsWith('/api/')) {
|
|
93
|
+
await handleApi(req, res, api);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (pathname.startsWith(ASSET_PREFIX)) {
|
|
97
|
+
const sent = serveDir(req, res, o.project.assetsDir, ASSET_PREFIX);
|
|
98
|
+
if (sent) o.onAsset?.(sent);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (pathname.startsWith(SPEECH_PREFIX)) {
|
|
102
|
+
serveSpeech(req, res, videosDir, pathname.slice(SPEECH_PREFIX.length));
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (pathname === PLAYER_BASE.slice(0, -1)) {
|
|
106
|
+
res.writeHead(302, { Location: PLAYER_BASE + url.slice(pathname.length) });
|
|
107
|
+
res.end();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (pathname.startsWith(PLAYER_BASE)) {
|
|
111
|
+
if (!vite) return notFound(res, 'Player page disabled');
|
|
112
|
+
vite.middlewares(req, res, () => notFound(res));
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (o.mode === 'studio' && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
116
|
+
serveStudio(req, res, studioDir);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
notFound(res);
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const server = http.createServer((req, res) => {
|
|
123
|
+
handle(req, res).catch((err: unknown) => {
|
|
124
|
+
if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
125
|
+
res.end(err instanceof Error ? err.message : String(err));
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
if (!o.noVite) {
|
|
130
|
+
vite = await createPlayerVite({
|
|
131
|
+
configPath: o.project.configPath,
|
|
132
|
+
root: o.project.root,
|
|
133
|
+
name: o.project.name,
|
|
134
|
+
httpServer: o.mode === 'studio' ? server : null,
|
|
135
|
+
logLevel: o.mode === 'studio' ? 'info' : 'warn',
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
await new Promise<void>((resolve, reject) => {
|
|
140
|
+
server.once('error', reject);
|
|
141
|
+
server.listen(o.port ?? 0, host, () => {
|
|
142
|
+
server.off('error', reject);
|
|
143
|
+
resolve();
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
port = (server.address() as AddressInfo).port;
|
|
147
|
+
const shownHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host.includes(':') ? `[${host}]` : host;
|
|
148
|
+
baseUrl = `http://${shownHost}:${port}`;
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
url: baseUrl,
|
|
152
|
+
port,
|
|
153
|
+
vite,
|
|
154
|
+
jobs,
|
|
155
|
+
speechJobs,
|
|
156
|
+
async close(): Promise<void> {
|
|
157
|
+
if (vite) await vite.close();
|
|
158
|
+
server.closeAllConnections();
|
|
159
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* GET /speech/<name>: <videosDir>/speech/<name> for clip names only (<16 hex>.wav, .words.json);
|
|
166
|
+
* 404 for anything else, so no other file of the folder (or outside it) is reachable here.
|
|
167
|
+
*/
|
|
168
|
+
export function serveSpeech(req: IncomingMessage, res: ServerResponse, videosDir: string, name: string): void {
|
|
169
|
+
const readable = req.method === 'GET' || req.method === 'HEAD';
|
|
170
|
+
if (!readable || !SPEECH_FILE.test(name) || !sendFile(req, res, path.join(videosDir, SPEECH_DIR, name))) notFound(res);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** POST /api/speech jobs: speakVideo on the file as saved, with the project's config as it is now and the server's plugins. */
|
|
174
|
+
function speechRunner(currentProject: () => Promise<ProjectContext>, videosDir: string, plugins: SpeechPlugins, log?: (line: string) => void): SpeechRunner {
|
|
175
|
+
return async (file, request, emit) => {
|
|
176
|
+
const project = await currentProject();
|
|
177
|
+
const abs = path.join(videosDir, file);
|
|
178
|
+
const checked = checkDoc(JSON.parse(await fs.readFile(abs, 'utf8')));
|
|
179
|
+
if (!checked.ok) throw new Error(`${file} is not a valid video: ${checked.issues.map((i) => i.message).join('; ')}`);
|
|
180
|
+
const named = path.relative(project.root, abs) || file;
|
|
181
|
+
log?.(`speak ${named}`);
|
|
182
|
+
await speakVideo({ path: abs, doc: checked.doc, project }, { ...request, file: named }, {
|
|
183
|
+
plugins,
|
|
184
|
+
emit: (e) => {
|
|
185
|
+
if (e.type === 'loading') log?.(' loading the speech engine…');
|
|
186
|
+
emit(e);
|
|
187
|
+
},
|
|
188
|
+
log,
|
|
189
|
+
});
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { RenderEvent, SpeechEvent } from '@beatsheet/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One Server-Sent Event. Uses the default `message` event type (no `event:` line), so an
|
|
6
|
+
* EventSource gets every RenderEvent (SpeechEvent) in onmessage with its JSON as data.
|
|
7
|
+
*/
|
|
8
|
+
export function formatSse(event: RenderEvent | SpeechEvent, id?: number): string {
|
|
9
|
+
const lines: string[] = [];
|
|
10
|
+
if (id !== undefined) lines.push(`id: ${id}`);
|
|
11
|
+
for (const line of JSON.stringify(event).split('\n')) lines.push(`data: ${line}`);
|
|
12
|
+
return lines.join('\n') + '\n\n';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A comment line that keeps proxies from closing an idle stream. */
|
|
16
|
+
export const SSE_HEARTBEAT = ': ping\n\n';
|
|
17
|
+
|
|
18
|
+
export function startSse(res: ServerResponse, what: 'render' | 'speech' = 'render'): void {
|
|
19
|
+
res.writeHead(200, {
|
|
20
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
21
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
22
|
+
Connection: 'keep-alive',
|
|
23
|
+
'X-Accel-Buffering': 'no',
|
|
24
|
+
});
|
|
25
|
+
res.write(`: beatsheet ${what} events\n\n`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** True for the event that ends a job's stream: the final 'done' (no format) or an error. */
|
|
29
|
+
export function isTerminal(event: RenderEvent): boolean {
|
|
30
|
+
return event.type === 'error' || (event.type === 'phase' && event.phase === 'done' && event.format === undefined);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** True for the event that ends a speech job's stream: 'done' or 'error'. */
|
|
34
|
+
export function isSpeechTerminal(event: SpeechEvent): boolean {
|
|
35
|
+
return event.type === 'done' || event.type === 'error';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A job's event log as the SSE endpoints stream it. */
|
|
39
|
+
export interface EventLog<E> {
|
|
40
|
+
events: E[];
|
|
41
|
+
finished: boolean;
|
|
42
|
+
subscribe(listener: (e: E) => void): () => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Streams a job's events: the whole log so far (a late client gets everything), then each new one
|
|
47
|
+
* until the terminal event; a heartbeat comment every 15 s keeps idle proxies from closing it.
|
|
48
|
+
*/
|
|
49
|
+
export function streamEvents<E extends RenderEvent | SpeechEvent>(
|
|
50
|
+
req: IncomingMessage,
|
|
51
|
+
res: ServerResponse,
|
|
52
|
+
job: EventLog<E>,
|
|
53
|
+
terminal: (e: E) => boolean,
|
|
54
|
+
what: 'render' | 'speech',
|
|
55
|
+
): void {
|
|
56
|
+
startSse(res, what);
|
|
57
|
+
let id = 0;
|
|
58
|
+
for (const e of job.events) res.write(formatSse(e, id++));
|
|
59
|
+
if (job.finished) {
|
|
60
|
+
res.end();
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const heartbeat = setInterval(() => res.write(SSE_HEARTBEAT), 15000);
|
|
64
|
+
const close = (): void => {
|
|
65
|
+
clearInterval(heartbeat);
|
|
66
|
+
off();
|
|
67
|
+
};
|
|
68
|
+
const off = job.subscribe((e) => {
|
|
69
|
+
res.write(formatSse(e, id++));
|
|
70
|
+
if (terminal(e)) {
|
|
71
|
+
close();
|
|
72
|
+
res.end();
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
req.on('close', close);
|
|
76
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
|
+
import { CLI_DIR } from '../paths';
|
|
6
|
+
|
|
7
|
+
const MIME: Record<string, string> = {
|
|
8
|
+
'.html': 'text/html; charset=utf-8',
|
|
9
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
10
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
11
|
+
'.css': 'text/css; charset=utf-8',
|
|
12
|
+
'.json': 'application/json; charset=utf-8',
|
|
13
|
+
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
14
|
+
'.map': 'application/json; charset=utf-8',
|
|
15
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
16
|
+
'.svg': 'image/svg+xml',
|
|
17
|
+
'.png': 'image/png',
|
|
18
|
+
'.jpg': 'image/jpeg',
|
|
19
|
+
'.jpeg': 'image/jpeg',
|
|
20
|
+
'.gif': 'image/gif',
|
|
21
|
+
'.webp': 'image/webp',
|
|
22
|
+
'.avif': 'image/avif',
|
|
23
|
+
'.ico': 'image/x-icon',
|
|
24
|
+
'.woff': 'font/woff',
|
|
25
|
+
'.woff2': 'font/woff2',
|
|
26
|
+
'.ttf': 'font/ttf',
|
|
27
|
+
'.otf': 'font/otf',
|
|
28
|
+
'.mp3': 'audio/mpeg',
|
|
29
|
+
'.wav': 'audio/wav',
|
|
30
|
+
'.ogg': 'audio/ogg',
|
|
31
|
+
'.m4a': 'audio/mp4',
|
|
32
|
+
'.mp4': 'video/mp4',
|
|
33
|
+
'.webm': 'video/webm',
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export function mimeType(file: string): string {
|
|
37
|
+
return MIME[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Resolves a URL path inside root; null when it escapes root. */
|
|
41
|
+
export function safeJoin(root: string, urlPath: string): string | null {
|
|
42
|
+
let decoded: string;
|
|
43
|
+
try {
|
|
44
|
+
decoded = decodeURIComponent(urlPath);
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
if (decoded.includes('\0')) return null;
|
|
49
|
+
const base = path.resolve(root);
|
|
50
|
+
const resolved = path.resolve(base, '.' + path.posix.normalize('/' + decoded));
|
|
51
|
+
return resolved === base || resolved.startsWith(base + path.sep) ? resolved : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Streams a file; returns false when it does not exist (or is a folder). */
|
|
55
|
+
export function sendFile(req: IncomingMessage, res: ServerResponse, file: string, cache = 'no-cache'): boolean {
|
|
56
|
+
let stat: fs.Stats;
|
|
57
|
+
try {
|
|
58
|
+
stat = fs.statSync(file);
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
if (!stat.isFile()) return false;
|
|
63
|
+
res.writeHead(200, { 'Content-Type': mimeType(file), 'Content-Length': stat.size, 'Cache-Control': cache });
|
|
64
|
+
if (req.method === 'HEAD') res.end();
|
|
65
|
+
else fs.createReadStream(file).pipe(res);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function notFound(res: ServerResponse, message = 'Not found'): void {
|
|
70
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
71
|
+
res.end(message);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Serves `<prefix>...` from `dir` (project assets). Returns the file it sent, null for a 404. */
|
|
75
|
+
export function serveDir(req: IncomingMessage, res: ServerResponse, dir: string, prefix: string): string | null {
|
|
76
|
+
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
|
|
77
|
+
const file = safeJoin(dir, pathname.slice(prefix.length));
|
|
78
|
+
if (file && sendFile(req, res, file)) return file;
|
|
79
|
+
notFound(res);
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The built studio: the package's own studio/ (the published package, copied there by scripts/prepack.mjs),
|
|
85
|
+
* else packages/studio/dist/studio/browser (a checkout, resolved through the @beatsheet/studio package).
|
|
86
|
+
*/
|
|
87
|
+
export function studioDistDir(cliDir: string = CLI_DIR): string {
|
|
88
|
+
const packaged = path.join(cliDir, 'studio');
|
|
89
|
+
if (fs.existsSync(path.join(packaged, 'index.html'))) return packaged;
|
|
90
|
+
let pkgDir: string;
|
|
91
|
+
try {
|
|
92
|
+
pkgDir = path.dirname(createRequire(path.join(cliDir, 'package.json')).resolve('@beatsheet/studio/package.json'));
|
|
93
|
+
} catch {
|
|
94
|
+
pkgDir = path.resolve(cliDir, '../studio');
|
|
95
|
+
}
|
|
96
|
+
return path.join(pkgDir, 'dist', 'studio', 'browser');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export const STUDIO_MISSING_HTML = `<!doctype html>
|
|
100
|
+
<html><head><meta charset="utf-8"><title>beatsheet studio</title>
|
|
101
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;margin:4rem auto;max-width:40rem;padding:0 1rem;color:#222}code{background:#f2f2f2;padding:.1em .35em;border-radius:4px}</style>
|
|
102
|
+
</head><body>
|
|
103
|
+
<h1>beatsheet studio is not built yet</h1>
|
|
104
|
+
<p>The editor app has no build output. Build it once, then reload this page:</p>
|
|
105
|
+
<p><code>npm run build -w @beatsheet/studio</code></p>
|
|
106
|
+
<p>The REST API (<code>/api/project</code>) and the player page (<code>/player/</code>) work without it.</p>
|
|
107
|
+
</body></html>
|
|
108
|
+
`;
|
|
109
|
+
|
|
110
|
+
/** Static Angular build with SPA fallback to index.html; a hint page when the build is missing. */
|
|
111
|
+
export function serveStudio(req: IncomingMessage, res: ServerResponse, distDir: string): void {
|
|
112
|
+
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
|
|
113
|
+
const index = path.join(distDir, 'index.html');
|
|
114
|
+
if (!fs.existsSync(index)) {
|
|
115
|
+
res.writeHead(pathname === '/' ? 200 : 404, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
116
|
+
res.end(STUDIO_MISSING_HTML);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const file = safeJoin(distDir, pathname);
|
|
120
|
+
if (file && pathname !== '/' && sendFile(req, res, file, /\.[0-9a-z]{8,}\.(js|css)$/i.test(file) ? 'public, max-age=31536000, immutable' : 'no-cache')) return;
|
|
121
|
+
// SPA fallback: routes without a file extension get index.html.
|
|
122
|
+
if (pathname === '/' || !path.extname(pathname)) {
|
|
123
|
+
sendFile(req, res, index);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
notFound(res);
|
|
127
|
+
}
|