rushes 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.
Files changed (77) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +10 -0
  3. package/.mcp.json +8 -0
  4. package/AGENTS.md +110 -0
  5. package/LICENSE +21 -0
  6. package/README.md +204 -0
  7. package/dist/cli/demo.js +339 -0
  8. package/dist/cli/doctor.js +307 -0
  9. package/dist/cli/index.js +11 -0
  10. package/dist/cli/main.js +469 -0
  11. package/dist/core/batches.js +58 -0
  12. package/dist/core/errors.js +37 -0
  13. package/dist/core/exportNotes.js +132 -0
  14. package/dist/core/ids.js +42 -0
  15. package/dist/core/media.js +128 -0
  16. package/dist/core/notes.js +117 -0
  17. package/dist/core/paths.js +17 -0
  18. package/dist/core/project.js +200 -0
  19. package/dist/core/schema.js +220 -0
  20. package/dist/core/script.js +113 -0
  21. package/dist/core/store.js +132 -0
  22. package/dist/core/tabs.js +24 -0
  23. package/dist/mcp/client.js +50 -0
  24. package/dist/mcp/ensure.js +69 -0
  25. package/dist/mcp/stdio.js +47 -0
  26. package/dist/mcp/tools.js +191 -0
  27. package/dist/server/app.js +710 -0
  28. package/dist/server/assets.js +234 -0
  29. package/dist/server/files.js +170 -0
  30. package/dist/server/lock.js +148 -0
  31. package/dist/server/loudness.js +331 -0
  32. package/dist/server/proxy.js +575 -0
  33. package/dist/server/reveal.js +71 -0
  34. package/dist/server/start.js +125 -0
  35. package/dist/server/watch.js +133 -0
  36. package/dist/setup/env.js +42 -0
  37. package/dist/setup/harnesses.js +93 -0
  38. package/dist/setup/setup.js +92 -0
  39. package/package.json +54 -0
  40. package/skills/rushes/SKILL.md +30 -0
  41. package/web-dist/assets/figtree-latin-400-normal-BD4aNku5.woff +0 -0
  42. package/web-dist/assets/figtree-latin-400-normal-g7Dtegnw.woff2 +0 -0
  43. package/web-dist/assets/figtree-latin-500-normal-BWnGEVsr.woff2 +0 -0
  44. package/web-dist/assets/figtree-latin-500-normal-B_yy1phn.woff +0 -0
  45. package/web-dist/assets/figtree-latin-600-normal-BM_oTo4n.woff +0 -0
  46. package/web-dist/assets/figtree-latin-600-normal-Cv_xCTDl.woff2 +0 -0
  47. package/web-dist/assets/figtree-latin-700-normal-BCCt2T1q.woff +0 -0
  48. package/web-dist/assets/figtree-latin-700-normal-th6qEP7c.woff2 +0 -0
  49. package/web-dist/assets/figtree-latin-ext-400-normal-CXAzuTZb.woff2 +0 -0
  50. package/web-dist/assets/figtree-latin-ext-400-normal-Gbh-3PTk.woff +0 -0
  51. package/web-dist/assets/figtree-latin-ext-500-normal-BOEJvrb_.woff +0 -0
  52. package/web-dist/assets/figtree-latin-ext-500-normal-Du0rIuHj.woff2 +0 -0
  53. package/web-dist/assets/figtree-latin-ext-600-normal-CQqsimlV.woff +0 -0
  54. package/web-dist/assets/figtree-latin-ext-600-normal-DJlfifZj.woff2 +0 -0
  55. package/web-dist/assets/figtree-latin-ext-700-normal-BoDi4KL2.woff +0 -0
  56. package/web-dist/assets/figtree-latin-ext-700-normal-CS4sQkGV.woff2 +0 -0
  57. package/web-dist/assets/index-BjDIT_wL.css +1 -0
  58. package/web-dist/assets/index-DF6Rl-Ac.js +3 -0
  59. package/web-dist/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  60. package/web-dist/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  61. package/web-dist/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  62. package/web-dist/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  63. package/web-dist/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  64. package/web-dist/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  65. package/web-dist/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  66. package/web-dist/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  67. package/web-dist/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  68. package/web-dist/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  69. package/web-dist/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  70. package/web-dist/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  71. package/web-dist/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  72. package/web-dist/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  73. package/web-dist/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  74. package/web-dist/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  75. package/web-dist/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  76. package/web-dist/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  77. package/web-dist/index.html +14 -0
@@ -0,0 +1,710 @@
1
+ import { Hono } from "hono";
2
+ import { streamSSE } from "hono/streaming";
3
+ import { z } from "zod";
4
+ import { RushesError, InvalidError, NotFoundError } from "../core/errors.js";
5
+ import { addFile, addVariant, addVersion, ensureProjectIdOnce, lockPicture, resolveVideo, setShots, shotAt } from "../core/project.js";
6
+ import { addTake, editSection, setSections } from "../core/script.js";
7
+ import { addNote, applyReply, applyUserEdit, filterNotes } from "../core/notes.js";
8
+ import { createBatch, latestBatch } from "../core/batches.js";
9
+ import { exportFileName, notesMarkdown } from "../core/exportNotes.js";
10
+ import { tabStates } from "../core/tabs.js";
11
+ import { fromManifestPath, toManifestPath } from "../core/paths.js";
12
+ import { probe } from "../core/media.js";
13
+ import { PROXY_PATH, ProxyJobs } from "./proxy.js";
14
+ import { lstat, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
15
+ import { randomUUID } from "node:crypto";
16
+ import { existsSync } from "node:fs";
17
+ import { basename, extname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { GRAB_PATH, SCREENSHOT_PATH, contentDisposition, contentType, inside, isInlineSafeType, mediaSecurityHeaders, registeredMedia, sendFile } from "./files.js";
20
+ import { candidatePaths, listAssets, fpsFor, screenshotName } from "./assets.js";
21
+ import { osRevealer, osOpener, OPEN_SAFE_EXT } from "./reveal.js";
22
+ import { LaneStageSchema, SectionStatusSchema, StageSchema, BoxSchema, FileKindSchema, MarkSchema, ProjectIdSchema, ShotSchema, LEVEL_MIN, LEVEL_MAX, LEVEL_STEP } from "../core/schema.js";
23
+ import { defaultRunner, measureMix } from "./loudness.js";
24
+ export const VERSION = "0.2.0";
25
+ async function body(c, schema) {
26
+ let json;
27
+ try {
28
+ json = await c.req.json();
29
+ }
30
+ catch {
31
+ throw new InvalidError("Request body must be JSON");
32
+ }
33
+ const parsed = schema.safeParse(json);
34
+ if (!parsed.success)
35
+ throw new InvalidError("Request body is invalid", parsed.error.issues);
36
+ return parsed.data;
37
+ }
38
+ const t = z.number().nonnegative();
39
+ const NewNoteBody = z.object({
40
+ stage: StageSchema,
41
+ video: z.string().nullish(),
42
+ version: z.string().nullish(),
43
+ on: z.string().nullish(),
44
+ scope: z.enum(["point", "range", "whole"]),
45
+ t: t.nullish(),
46
+ tOut: t.nullish(),
47
+ frame: z.number().int().nonnegative().nullish(),
48
+ text: z.string(),
49
+ box: BoxSchema.nullish(),
50
+ grab: z.string().nullish(),
51
+ marks: z.array(MarkSchema).max(4).optional(),
52
+ });
53
+ const UserEditBody = z.object({
54
+ text: z.string().optional(),
55
+ box: BoxSchema.nullable().optional(),
56
+ grab: z.string().nullable().optional(),
57
+ scope: z.enum(["point", "range", "whole"]).optional(),
58
+ t: t.nullable().optional(),
59
+ tOut: t.nullable().optional(),
60
+ marks: z.array(MarkSchema).max(4).optional(),
61
+ status: z.enum(["todo", "done"]).optional(),
62
+ });
63
+ const RepliesBody = z.object({
64
+ replies: z
65
+ .array(z.object({
66
+ id: z.string(),
67
+ reply: z.string().optional(),
68
+ status: z.enum(["todo", "done"]).optional(),
69
+ fixT: t.nullable().optional(),
70
+ fixVersion: z.string().nullable().optional(),
71
+ }))
72
+ .min(1),
73
+ });
74
+ const VersionBody = z.object({ video: z.string().min(1), file: z.string().min(1), note: z.string().optional() });
75
+ const VariantBody = z.object({
76
+ stage: LaneStageSchema,
77
+ lane: z.string().optional(),
78
+ round: z.string().min(1).max(64).optional(),
79
+ name: z.string().min(1),
80
+ file: z.string().min(1),
81
+ meta: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
82
+ description: z.string().min(1).max(200).optional(),
83
+ cues: z.array(z.object({ name: z.string().min(1), t })).optional(),
84
+ });
85
+ const ScriptBody = z.object({
86
+ wordsPerSecond: z.number().positive().optional(),
87
+ replace: z.boolean().optional(),
88
+ sections: z.array(z.object({ id: z.string().min(1).optional(), start: t, end: t, current: z.string() })),
89
+ });
90
+ const SectionEditBody = z.object({
91
+ proposed: z.string().nullable().optional(),
92
+ direction: z.string().optional(),
93
+ status: SectionStatusSchema.optional(),
94
+ });
95
+ const TakeBody = z.object({ file: z.string().min(1) });
96
+ // A pick is a variant or take id; null clears it. picks.json itself only ever holds strings.
97
+ const PickMap = z.record(z.string(), z.string().nullable());
98
+ // §19.6: a level is −24..6 dB in 0.5 dB steps; null resets it to 0 (removes the key).
99
+ const LevelValue = z.number().min(LEVEL_MIN).max(LEVEL_MAX).multipleOf(LEVEL_STEP);
100
+ const LevelsBody = z.object({ voice: LevelValue.nullable(), music: LevelValue.nullable(), sfx: LevelValue.nullable() }).partial();
101
+ const PicksBody = z.object({ lanes: PickMap.optional(), sections: PickMap.optional(), levels: LevelsBody.optional() });
102
+ const BatchBody = z.object({ stage: StageSchema });
103
+ const NoteQuery = z.object({
104
+ stage: StageSchema.optional(),
105
+ status: z.enum(["todo", "done"]).optional(),
106
+ batch: z.string().optional(),
107
+ version: z.string().optional(),
108
+ });
109
+ // ShotSchema's own limits (name trimmed 1-80 chars, tag at most 24) apply at the boundary; `n` is server-assigned.
110
+ const ShotsBody = z.object({
111
+ version: z.string().optional(),
112
+ shots: z.array(ShotSchema.omit({ n: true })).max(200),
113
+ });
114
+ const LockBody = z.object({ version: z.string().nullable() });
115
+ const MixLoudnessBody = z.object({ lanes: z.array(LaneStageSchema).min(1) });
116
+ const SettingsBody = z.object({ autoProxy: z.boolean() }).strict();
117
+ // A time in seconds, 0 to 24 h: an empty value, NaN, Infinity or anything huge is a 400.
118
+ const FrameQuery = z.object({ t: z.string().min(1).pipe(z.coerce.number().finite().min(0).max(86400)) });
119
+ const GrabBody = z.object({
120
+ video: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),
121
+ version: z.string().regex(/^v\d+$/),
122
+ // Capped well short of where it would print in exponent form in the grab's filename.
123
+ frame: z.number().int().nonnegative().max(10_000_000),
124
+ /** PNG bytes, base64, with or without a data: prefix. */
125
+ png: z.string().min(1),
126
+ });
127
+ const RevealBody = z.union([z.object({ path: z.string().min(1) }), z.object({ project: z.literal(true) })]);
128
+ const OpenBody = z.object({ path: z.string().min(1) });
129
+ const AddFileBody = z.object({
130
+ kind: FileKindSchema,
131
+ file: z.string().min(1),
132
+ name: z.string().min(1).max(120).optional(),
133
+ note: z.string().max(500).optional(),
134
+ video: z.string().optional(),
135
+ });
136
+ // Big enough for a full-quality frame of a 4K original from the frame endpoint (§19.5), which
137
+ // Picture posts here as the grab: 3840×2160 RGB is 24.9 MB before PNG compression.
138
+ const MAX_GRAB_BYTES = 64 * 1024 * 1024;
139
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
140
+ /** Where the built dashboard lives: <package>/web-dist, next to dist/ and src/. */
141
+ export const DEFAULT_WEB_DIR = fileURLToPath(new URL("../../web-dist/", import.meta.url));
142
+ const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost"]);
143
+ /** Hostname of "host[:port]" or a full origin URL, lowercased, or null when it doesn't parse. */
144
+ function hostnameOf(value, isUrl) {
145
+ try {
146
+ return new URL(isUrl ? value : `http://${value}`).hostname.toLowerCase();
147
+ }
148
+ catch {
149
+ return null;
150
+ }
151
+ }
152
+ const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
153
+ export function createApp(store, opts = {}) {
154
+ const webDir = opts.webDir ?? DEFAULT_WEB_DIR;
155
+ const reveal = opts.reveal ?? osRevealer;
156
+ const open = opts.open ?? osOpener;
157
+ const jobs = opts.proxyJobs ?? new ProxyJobs(store);
158
+ const app = new Hono();
159
+ // Every SSE client adds a change listener, so lift Node's default limit of ten.
160
+ store.setMaxListeners(0);
161
+ // The project's id never changes once set. When startServer has already ensured and passed
162
+ // it in, this is immediate; otherwise it shares project.ts's one in-flight ensure (see M3).
163
+ async function getProjectId() {
164
+ return opts.projectId ?? ensureProjectIdOnce(store);
165
+ }
166
+ async function dashboardHtml() {
167
+ const index = join(webDir, "index.html");
168
+ if (existsSync(index))
169
+ return readFile(index, "utf8");
170
+ return `<!doctype html><title>Rushes</title><p>Rushes is running for <code>${escapeHtml(store.root)}</code>. The dashboard isn't built: run <code>npm run build</code>.</p>`;
171
+ }
172
+ /** The "this address belongs to a project not running here" page: always 404, id always escaped. */
173
+ function wrongProjectPage(c, id) {
174
+ return c.html(`<!doctype html><title>Rushes</title><p>The Rushes project this address belongs to isn't running on this port. Ask your agent to open it again.</p><p><code>${escapeHtml(id)}</code></p>`, 404);
175
+ }
176
+ app.onError((err, c) => {
177
+ if (err instanceof RushesError)
178
+ return c.json({ error: err.code, message: err.message, ...err.detail }, err.status);
179
+ console.error(err);
180
+ return c.json({ error: "internal", message: err.message }, 500);
181
+ });
182
+ // The server is for this machine only. Checking Host stops DNS rebinding;
183
+ // requiring JSON and a local Origin on writes stops other websites posting
184
+ // to it from the user's browser (a JSON content type forces a CORS preflight,
185
+ // which this server never answers).
186
+ app.use("*", async (c, next) => {
187
+ const host = c.req.header("host") ?? new URL(c.req.url).host;
188
+ const hostname = hostnameOf(host, false);
189
+ if (!hostname || !LOCAL_HOSTS.has(hostname)) {
190
+ return c.json({ error: "forbidden_host", message: `Rushes only answers requests to 127.0.0.1 or localhost, not "${host}"` }, 403);
191
+ }
192
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") {
193
+ const type = (c.req.header("content-type") ?? "").split(";")[0].trim().toLowerCase();
194
+ if (type !== "application/json") {
195
+ return c.json({ error: "unsupported_media_type", message: "Requests that change data must send Content-Type: application/json" }, 415);
196
+ }
197
+ const origin = c.req.header("origin");
198
+ if (origin !== undefined) {
199
+ const from = hostnameOf(origin, true);
200
+ if (!from || !LOCAL_HOSTS.has(from)) {
201
+ return c.json({ error: "forbidden_origin", message: `Rushes doesn't accept changes from pages on "${origin}"` }, 403);
202
+ }
203
+ }
204
+ }
205
+ await next();
206
+ });
207
+ // Each dashboard tab carries this project's id (header on fetches, query param
208
+ // where headers can't be set, e.g. SSE and <img>/<video> src). A request naming
209
+ // a different project is refused; one with no id (MCP, CLI, curl) is unaffected.
210
+ app.use("*", async (c, next) => {
211
+ const given = c.req.header("x-rushes-project") ?? c.req.query("project");
212
+ if (given !== undefined && given !== (await getProjectId())) {
213
+ return c.json({ error: "wrong_project", message: "This page is for a different Rushes project" }, 409);
214
+ }
215
+ await next();
216
+ });
217
+ // ---- dashboard ----
218
+ app.get("/", async (c) => c.redirect(`/p/${await getProjectId()}/`, 302));
219
+ // No trailing slash: just add it, once the id's shape is valid. The id is never
220
+ // substituted for this server's own (a stale tab from a different project must
221
+ // still land on /p/:id/ and see the "isn't running here" page there, never be
222
+ // silently carried over to this project), and an invalid id is never reflected
223
+ // into a Location header — it gets the same 404 page the slash route would give it.
224
+ app.get("/p/:id", (c) => {
225
+ const id = c.req.param("id");
226
+ const parsed = ProjectIdSchema.safeParse(id);
227
+ if (!parsed.success)
228
+ return wrongProjectPage(c, id);
229
+ return c.redirect(`/p/${parsed.data}/`, 302);
230
+ });
231
+ app.get("/p/:id/", async (c) => {
232
+ const id = c.req.param("id");
233
+ if (id !== (await getProjectId()))
234
+ return wrongProjectPage(c, id);
235
+ return c.html(await dashboardHtml());
236
+ });
237
+ app.get("/assets/*", async (c) => {
238
+ const raw = new URL(c.req.url).pathname.slice(1);
239
+ let rel;
240
+ try {
241
+ rel = decodeURIComponent(raw);
242
+ }
243
+ catch {
244
+ throw new NotFoundError("asset", raw);
245
+ }
246
+ const file = inside(webDir, rel);
247
+ if (!file)
248
+ throw new NotFoundError("asset", rel);
249
+ const res = await sendFile(file, undefined, contentType(file));
250
+ if (res.status === 404)
251
+ throw new NotFoundError("asset", rel);
252
+ res.headers.set("cache-control", "public, max-age=31536000, immutable");
253
+ return res;
254
+ });
255
+ // ---- media: only files the project registered, plus its own screenshots and grabs ----
256
+ app.get("/media", async (c) => {
257
+ const path = c.req.query("path") ?? "";
258
+ const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
259
+ // Fast path (no filesystem reads beyond the file itself): registeredMedia is a project.json
260
+ // lookup, and GRAB_PATH/SCREENSHOT_PATH are plain regexes. This covers every cut, take,
261
+ // variant and registered library file, and every screenshot/grab -- by far the common case,
262
+ // and the one a byte-range video seek hits over and over. Only a path that misses all three
263
+ // falls through to candidatePaths, which does the readdir-backed discovery (§16.2's
264
+ // auto-discovered docs/captions/exports) that a registered path never needs.
265
+ const known = registeredMedia(project, script).has(path) || GRAB_PATH.test(path) || SCREENSHOT_PATH.test(path);
266
+ if (!known) {
267
+ const candidates = await candidatePaths(store, project, script);
268
+ if (!candidates.has(path))
269
+ throw new NotFoundError("media", path);
270
+ }
271
+ // C1: a type a browser could render as a document (HTML, XML, SVG -- an SVG can carry
272
+ // script -- or anything this server doesn't otherwise recognise) is never served inline,
273
+ // whatever asked for it: exports/ in particular takes any file with no extension filter, so
274
+ // without this an exports/x.html would be served as text/html on the dashboard's own origin,
275
+ // free to call its API. Forced to a generic download instead, regardless of ?download=1.
276
+ // §19.5: a proxy is a file this server wrote into proxies/. A symlink planted at that name
277
+ // (or anything that isn't a plain file) is never followed.
278
+ if (PROXY_PATH.test(path)) {
279
+ const info = await lstat(fromManifestPath(store.root, path)).catch(() => null);
280
+ if (!info || !info.isFile() || info.isSymbolicLink())
281
+ throw new NotFoundError("media", path);
282
+ }
283
+ const type = contentType(path);
284
+ const inlineSafe = isInlineSafeType(type);
285
+ const res = await sendFile(fromManifestPath(store.root, path), c.req.header("range"), inlineSafe ? type : "application/octet-stream");
286
+ res.headers.set("cross-origin-resource-policy", "same-origin");
287
+ for (const [name, value] of Object.entries(mediaSecurityHeaders()))
288
+ res.headers.set(name, value);
289
+ if (res.status !== 404 && (!inlineSafe || c.req.query("download") === "1")) {
290
+ res.headers.set("content-disposition", contentDisposition(basename(path)));
291
+ }
292
+ return res;
293
+ });
294
+ app.post("/api/grabs", async (c) => {
295
+ const b = await body(c, GrabBody);
296
+ const bytes = Buffer.from(b.png.replace(/^data:image\/png;base64,/, ""), "base64");
297
+ if (bytes.length > MAX_GRAB_BYTES)
298
+ throw new InvalidError(`Frame grab is over ${MAX_GRAB_BYTES / 1024 / 1024} MB`);
299
+ if (!bytes.subarray(0, 8).equals(PNG_MAGIC))
300
+ throw new InvalidError("Frame grab must be a PNG");
301
+ const project = await store.read("project");
302
+ const fps = fpsFor(project, b.video, b.version);
303
+ const name = screenshotName(b.video, b.version, b.frame, fps);
304
+ const grab = `screenshots/${name}`;
305
+ await mkdir(join(store.root, "screenshots"), { recursive: true });
306
+ // Written to a temp name in the same directory, then renamed into place. Writing the
307
+ // final name directly would follow a symlink planted there (by a hand edit, say) and land
308
+ // the bytes wherever it points; rename() replaces the directory entry itself rather than
309
+ // the symlink's target, so the write can never escape screenshots/ that way. It also means
310
+ // nothing ever lists a half-written PNG. The temp name starts with "." and ends in ".tmp",
311
+ // which SCREENSHOT_PATH (the safe-name filter) already excludes from both /media and the
312
+ // Assets listing.
313
+ const tmp = join(store.root, "screenshots", `.${name}.${process.pid}.tmp`);
314
+ await writeFile(tmp, bytes);
315
+ await rename(tmp, fromManifestPath(store.root, grab));
316
+ return c.json({ grab }, 201);
317
+ });
318
+ // ---- assets: the Assets tab and rushes_list_assets ----
319
+ app.get("/api/assets", async (c) => {
320
+ const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
321
+ let assets = await listAssets(store, project, script);
322
+ const kind = c.req.query("kind");
323
+ if (kind)
324
+ assets = assets.filter((a) => a.kind === kind);
325
+ return c.json({ assets });
326
+ });
327
+ app.post("/api/reveal", async (c) => {
328
+ const b = await body(c, RevealBody);
329
+ // §16.5: { project: true } reveals the project root itself, with no asset-list check --
330
+ // it's always the folder this server is running for, never user-supplied.
331
+ if ("project" in b) {
332
+ await reveal(store.root);
333
+ return c.json({ ok: true });
334
+ }
335
+ const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
336
+ // Exact string equality against a path /api/assets would list: no path logic beyond this is
337
+ // needed to reject traversal, absolute paths and anything unregistered. candidatePaths is
338
+ // cheap (no stat calls), so a request for an unlisted path never touches the filesystem at
339
+ // all; only the one path that matches gets stat'ed, instead of rebuilding the whole index.
340
+ const candidates = await candidatePaths(store, project, script);
341
+ if (!candidates.has(b.path))
342
+ throw new NotFoundError("asset", b.path);
343
+ const abs = fromManifestPath(store.root, b.path);
344
+ const exists = await stat(abs).then(() => true, () => false);
345
+ if (!exists)
346
+ throw new NotFoundError("asset", b.path);
347
+ await reveal(abs);
348
+ return c.json({ ok: true });
349
+ });
350
+ // §16.3: open a listed asset in its default app. The listed-path check and the safe-extension
351
+ // check both happen before any stat or spawn, so an unsafe or unlisted path never touches disk.
352
+ app.post("/api/open", async (c) => {
353
+ const b = await body(c, OpenBody);
354
+ const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
355
+ const candidates = await candidatePaths(store, project, script);
356
+ if (!candidates.has(b.path))
357
+ throw new NotFoundError("asset", b.path);
358
+ const ext = extname(b.path).toLowerCase().replace(/^\./, "");
359
+ if (!OPEN_SAFE_EXT.has(ext))
360
+ throw new RushesError(`Rushes won't open "${b.path}": unsafe file type`, 415, "unsafe_type", { path: b.path });
361
+ const abs = fromManifestPath(store.root, b.path);
362
+ // lstat, not stat: a symlink must never be followed here, whatever its own extension says --
363
+ // a "brief.md" that's really a link to an .app (or to any directory or executable) must be
364
+ // refused, not opened through to its target. Refused the same way an unsafe extension is
365
+ // (415 unsafe_type), so a bad target can't be told apart from a merely unsafe type; a file
366
+ // that simply isn't there any more stays 404.
367
+ let info;
368
+ try {
369
+ info = await lstat(abs);
370
+ }
371
+ catch {
372
+ throw new NotFoundError("asset", b.path);
373
+ }
374
+ if (!info.isFile() || info.isSymbolicLink()) {
375
+ throw new RushesError(`Rushes won't open "${b.path}": unsafe file type`, 415, "unsafe_type", { path: b.path });
376
+ }
377
+ // Refuse anything with an execute bit set (M6): a safe extension can still be a script
378
+ // someone chmod +x'd by hand, and Windows has no execute bit to check (file associations
379
+ // there run off the extension alone, already covered above), so this only applies elsewhere.
380
+ if (process.platform !== "win32" && (info.mode & 0o111) !== 0) {
381
+ throw new RushesError(`Rushes won't open "${b.path}": unsafe file type`, 415, "unsafe_type", { path: b.path });
382
+ }
383
+ await open(abs);
384
+ return c.json({ ok: true });
385
+ });
386
+ // ---- library: §16.2 registered files, and §16.4 notes export ----
387
+ app.post("/api/files", async (c) => {
388
+ const b = await body(c, AddFileBody);
389
+ const file = toManifestPath(store.root, b.file);
390
+ const { result } = await store.update("project", (p) => addFile(p, { ...b, file }));
391
+ return c.json(result, 201);
392
+ });
393
+ app.post("/api/exports/notes", async (c) => {
394
+ const [project, notesFile, script, picks] = await Promise.all([
395
+ store.read("project"), store.read("notes"), store.read("script"), store.read("picks"),
396
+ ]);
397
+ const now = new Date();
398
+ const md = notesMarkdown(project, notesFile.notes, now, script, picks);
399
+ const name = exportFileName(project.name, now);
400
+ const dir = join(store.root, "exports");
401
+ await mkdir(dir, { recursive: true });
402
+ // Written to a temp name in the same directory, then renamed into place -- same atomic
403
+ // write the grabs route uses, so exporting again the same day cleanly replaces the file. A
404
+ // process id alone isn't unique enough here (M1): two concurrent exports in the same process
405
+ // -- two agents calling rushes_export_notes back to back, say -- would share one temp name
406
+ // and race each other's write. randomUUID() makes every export's temp name its own.
407
+ const tmp = join(dir, `.${name}.${process.pid}.${randomUUID()}.tmp`);
408
+ await writeFile(tmp, md, "utf8");
409
+ await rename(tmp, join(dir, name));
410
+ return c.json({ path: `exports/${name}` }, 201);
411
+ });
412
+ app.post("/api/shutdown", (c) => {
413
+ if (opts.onShutdown)
414
+ setImmediate(opts.onShutdown);
415
+ return c.json({ ok: true, stopping: !!opts.onShutdown });
416
+ });
417
+ // Event streams open now. Only `?test=1` shows it, so the e2e suite can check that a browser's
418
+ // tabs share one stream (§19.8).
419
+ let streams = 0;
420
+ app.get("/api/health", async (c) => {
421
+ const [project, id] = await Promise.all([store.read("project"), getProjectId()]);
422
+ const health = { ok: true, app: "rushes", version: VERSION, root: store.root, id, name: project.name };
423
+ return c.json(c.req.query("test") === "1" ? { ...health, sse: streams } : health);
424
+ });
425
+ app.get("/api/state", async (c) => {
426
+ const [project, script, notes, picks, batches, ffmpeg] = await Promise.all([
427
+ store.read("project"), store.read("script"), store.read("notes"), store.read("picks"), store.read("batches"), jobs.available(),
428
+ ]);
429
+ const tabs = tabStates(project, script, notes);
430
+ // §19.5: why each cut may play badly (or null). Never waits on a probe: an unprobed cut is
431
+ // null until its background probe lands, which then announces a change (ruling B).
432
+ const videos = await Promise.all(project.videos.map(async (v) => ({
433
+ ...v,
434
+ versions: await Promise.all(v.versions.map(async (ver) => ({ ...ver, proxyNeed: await jobs.needNow(fromManifestPath(store.root, ver.file)) }))),
435
+ })));
436
+ return c.json({ project: { ...project, videos }, script, notes, picks, batches, tabs, proxies: { ffmpeg, jobs: jobs.list() } });
437
+ });
438
+ app.get("/api/tabs", async (c) => {
439
+ const [project, script, notes] = await Promise.all([store.read("project"), store.read("script"), store.read("notes")]);
440
+ return c.json({ tabs: tabStates(project, script, notes) });
441
+ });
442
+ // ---- notes ----
443
+ app.get("/api/notes", async (c) => {
444
+ const q = NoteQuery.safeParse(c.req.query());
445
+ if (!q.success)
446
+ throw new InvalidError("Query is invalid", q.error.issues);
447
+ const { notes } = await store.read("notes");
448
+ return c.json({ notes: filterNotes(notes, q.data) });
449
+ });
450
+ app.post("/api/notes", async (c) => {
451
+ const b = await body(c, NewNoteBody);
452
+ // The client never sends shot; the server stamps it from the version's shots.
453
+ let shot = null;
454
+ if (b.stage === "picture" && b.video && b.version && b.t != null) {
455
+ const project = await store.read("project");
456
+ const version = project.videos.find((v) => v.id === b.video)?.versions.find((v) => v.id === b.version);
457
+ if (version)
458
+ shot = shotAt(version.shots, b.t);
459
+ }
460
+ const { result } = await store.update("notes", (f) => addNote(f, { ...b, shot, by: "user" }));
461
+ return c.json({ note: result }, 201);
462
+ });
463
+ app.patch("/api/notes/:id", async (c) => {
464
+ const b = await body(c, UserEditBody);
465
+ const { result } = await store.update("notes", (f) => applyUserEdit(f, { id: c.req.param("id"), ...b }));
466
+ return c.json({ note: result });
467
+ });
468
+ app.post("/api/replies", async (c) => {
469
+ const b = await body(c, RepliesBody);
470
+ const { result } = await store.update("notes", (f) => b.replies.map((r) => applyReply(f, r)));
471
+ return c.json({ notes: result });
472
+ });
473
+ // ---- media ----
474
+ app.post("/api/versions", async (c) => {
475
+ const b = await body(c, VersionBody);
476
+ const file = toManifestPath(store.root, b.file);
477
+ const abs = fromManifestPath(store.root, file);
478
+ // The proxy jobs' probe is ffprobe (tests inject a fake), so the cut's need is read from the same answer.
479
+ const info = await jobs.probe(abs);
480
+ let lockedVersion = null;
481
+ let autoProxy = false;
482
+ const { result } = await store.update("project", (p) => {
483
+ const out = addVersion(p, { video: b.video, file, note: b.note, duration: info.duration, fps: info.fps });
484
+ lockedVersion = out.video.lockedVersion;
485
+ autoProxy = p.autoProxy;
486
+ if (info.fps && p.videos.length === 1 && p.videos[0].versions.length === 1)
487
+ p.fps = info.fps;
488
+ return out;
489
+ });
490
+ // §19.5: say when the cut is likely to play badly, and start its proxy straight away when the
491
+ // project asks for that. Without ffmpeg, nothing is offered (needFor is null).
492
+ const reason = await jobs.needFrom(abs, info);
493
+ const proxy = {};
494
+ if (reason) {
495
+ proxy.proxySuggested = true;
496
+ proxy.proxyReason = reason;
497
+ if (autoProxy && !jobs.isClosing)
498
+ proxy.proxyJob = jobs.start(result.video.id, result.version.id);
499
+ }
500
+ if (lockedVersion)
501
+ return c.json({ ...result, ...proxy, warning: `Picture is locked at ${lockedVersion}` }, 201);
502
+ return c.json({ ...result, ...proxy }, 201);
503
+ });
504
+ // ---- proxies (§19.5) ----
505
+ /** The cut a proxy or frame route names, or a 404. The video may be given by id, slug or name. */
506
+ async function cutOf(videoRef, versionId) {
507
+ const project = await store.read("project");
508
+ const video = resolveVideo(project, videoRef);
509
+ const version = video.versions.find((v) => v.id === versionId);
510
+ if (!version)
511
+ throw new NotFoundError("version", versionId);
512
+ return { project, video, version };
513
+ }
514
+ app.post("/api/videos/:video/versions/:version/proxy", async (c) => {
515
+ await jobs.requireFfmpeg();
516
+ const { video, version } = await cutOf(c.req.param("video"), c.req.param("version"));
517
+ // One job per cut (Review Focus 2): a second press, from this tab or another, joins the first.
518
+ const joined = jobs.find(video.id, version.id) !== undefined;
519
+ const job = jobs.start(video.id, version.id);
520
+ return c.json({ job }, joined ? 200 : 202);
521
+ });
522
+ app.delete("/api/proxy-jobs/:job", async (c) => {
523
+ const job = await jobs.cancel(c.req.param("job"));
524
+ return c.json({ job });
525
+ });
526
+ app.delete("/api/videos/:video/versions/:version/proxy", async (c) => {
527
+ const { video, version } = await cutOf(c.req.param("video"), c.req.param("version"));
528
+ const running = jobs.find(video.id, version.id);
529
+ if (running)
530
+ await jobs.cancel(running.id);
531
+ // Checked before writing, so a delete of nothing never bumps project.json's rev. (A job that
532
+ // finished just as it was cancelled has recorded its proxy by now, and is deleted below.)
533
+ const fresh = await cutOf(video.id, version.id);
534
+ if (!fresh.version.proxy) {
535
+ if (running)
536
+ return c.json({ version: fresh.version });
537
+ throw new NotFoundError("proxy", `${video.id} ${version.id}`);
538
+ }
539
+ let removed = null;
540
+ const { result } = await store.update("project", (p) => {
541
+ const v = p.videos.find((x) => x.id === video.id)?.versions.find((x) => x.id === version.id);
542
+ if (!v?.proxy)
543
+ return undefined;
544
+ removed = v.proxy.file;
545
+ v.proxy = null;
546
+ return v;
547
+ });
548
+ if (!result)
549
+ throw new NotFoundError("proxy", `${video.id} ${version.id}`);
550
+ // Only ever a file this server wrote into proxies/: the original is never touched, even if
551
+ // project.json was hand-edited to point the record somewhere else.
552
+ if (removed && PROXY_PATH.test(removed))
553
+ await rm(fromManifestPath(store.root, removed), { force: true });
554
+ return c.json({ version: result });
555
+ });
556
+ app.put("/api/project/settings", async (c) => {
557
+ const b = await body(c, SettingsBody);
558
+ const { data } = await store.update("project", (p) => {
559
+ p.autoProxy = b.autoProxy;
560
+ });
561
+ return c.json({ autoProxy: data.autoProxy });
562
+ });
563
+ // Grab Frame's still, always from the original at full quality: the exact frame round(t*fps),
564
+ // whichever file is playing. Returns the PNG only; Picture posts it to /api/grabs to save it.
565
+ app.get("/api/videos/:video/versions/:version/frame", async (c) => {
566
+ const q = FrameQuery.safeParse(c.req.query());
567
+ if (!q.success)
568
+ throw new InvalidError("Query is invalid: t must be a time in seconds", q.error.issues);
569
+ await jobs.requireFfmpeg();
570
+ const { project, version } = await cutOf(c.req.param("video"), c.req.param("version"));
571
+ const orig = fromManifestPath(store.root, version.file);
572
+ const exists = await stat(orig).then((s) => s.isFile(), () => false);
573
+ if (!exists)
574
+ throw new RushesError("The original file is missing", 404, "missing_file", { path: version.file });
575
+ const fps = version.fps ?? project.fps;
576
+ let frame = Math.round(q.data.t * fps);
577
+ // A time at or past the end lands on the last frame rather than on nothing.
578
+ if (version.duration !== null)
579
+ frame = Math.min(frame, Math.max(0, Math.ceil(version.duration * fps - 1e-6) - 1));
580
+ const png = await jobs.frame(orig, frame / fps);
581
+ if (!png)
582
+ throw new RushesError(`ffmpeg couldn't read frame ${frame}`, 422, "no_frame", { frame });
583
+ return new Response(new Uint8Array(png), {
584
+ status: 200,
585
+ headers: { "content-type": "image/png", "cache-control": "no-store", "x-rushes-frame": String(frame), "content-length": String(png.length) },
586
+ });
587
+ });
588
+ app.put("/api/videos/:video/shots", async (c) => {
589
+ const b = await body(c, ShotsBody);
590
+ const { result } = await store.update("project", (p) => setShots(p, c.req.param("video"), b.version, b.shots));
591
+ return c.json({ version: result });
592
+ });
593
+ app.put("/api/videos/:video/lock", async (c) => {
594
+ const b = await body(c, LockBody);
595
+ const { result } = await store.update("project", (p) => lockPicture(p, c.req.param("video"), b.version));
596
+ return c.json({ video: result });
597
+ });
598
+ app.post("/api/variants", async (c) => {
599
+ const b = await body(c, VariantBody);
600
+ const { result } = await store.update("project", (p) => addVariant(p, { ...b, file: toManifestPath(store.root, b.file) }));
601
+ return c.json(result, 201);
602
+ });
603
+ // ---- script ----
604
+ app.get("/api/script", async (c) => c.json({ script: await store.read("script") }));
605
+ app.put("/api/script", async (c) => {
606
+ const b = await body(c, ScriptBody);
607
+ const { result } = await store.update("script", (s) => {
608
+ if (b.wordsPerSecond)
609
+ s.wordsPerSecond = b.wordsPerSecond;
610
+ return setSections(s, b.sections, { replace: b.replace });
611
+ });
612
+ return c.json({ sections: result });
613
+ });
614
+ app.patch("/api/script/:id", async (c) => {
615
+ const b = await body(c, SectionEditBody);
616
+ const { result } = await store.update("script", (s) => editSection(s, c.req.param("id"), b));
617
+ return c.json({ section: result });
618
+ });
619
+ app.post("/api/script/:id/takes", async (c) => {
620
+ const b = await body(c, TakeBody);
621
+ const file = toManifestPath(store.root, b.file);
622
+ const info = await probe(fromManifestPath(store.root, file));
623
+ const { result } = await store.update("script", (s) => addTake(s, c.req.param("id"), { file, duration: info.duration }));
624
+ return c.json({ take: result }, 201);
625
+ });
626
+ // ---- picks ----
627
+ app.get("/api/picks", async (c) => c.json(await store.read("picks")));
628
+ app.put("/api/picks", async (c) => {
629
+ const b = await body(c, PicksBody);
630
+ // Merged key by key: a string sets that pick, null removes it, anything not named is kept.
631
+ const merge = (into, from = {}) => {
632
+ for (const [k, v] of Object.entries(from)) {
633
+ if (v === null)
634
+ delete into[k];
635
+ else
636
+ into[k] = v;
637
+ }
638
+ };
639
+ const { data } = await store.update("picks", (p) => {
640
+ merge(p.lanes, b.lanes);
641
+ merge(p.sections, b.sections);
642
+ // §19.6: same merge rule as lanes/sections -- a number sets the level, null resets it to 0
643
+ // (deletes the key), anything not named is kept.
644
+ for (const stage of ["voice", "music", "sfx"]) {
645
+ const v = b.levels?.[stage];
646
+ if (v === undefined)
647
+ continue;
648
+ if (v === null)
649
+ delete p.levels[stage];
650
+ else
651
+ p.levels[stage] = v;
652
+ }
653
+ });
654
+ return c.json(data);
655
+ });
656
+ // ---- mix loudness (§17.6) ----
657
+ app.post("/api/mix/loudness", async (c) => {
658
+ const b = await body(c, MixLoudnessBody);
659
+ const [project, picks] = await Promise.all([store.read("project"), store.read("picks")]);
660
+ const run = opts.loudnessRunner ?? defaultRunner;
661
+ const result = await measureMix(project, picks, b.lanes, store.root, run, opts.loudnessTimeoutMs);
662
+ return c.json(result);
663
+ });
664
+ // ---- batches ----
665
+ // A batch touches two files (notes and batches), so batch creation runs one at a time.
666
+ let batchQueue = Promise.resolve();
667
+ app.post("/api/batches", async (c) => {
668
+ const { stage } = await body(c, BatchBody);
669
+ const run = batchQueue.catch(() => undefined).then(async () => {
670
+ const [project, script, batches] = await Promise.all([store.read("project"), store.read("script"), store.read("batches")]);
671
+ const { result } = await store.update("notes", (notes) => createBatch({ project, script, notes, batches }, stage));
672
+ await store.update("batches", (f) => { f.batches.push(result); });
673
+ return result;
674
+ });
675
+ batchQueue = run;
676
+ return c.json({ batch: await run }, 201);
677
+ });
678
+ app.get("/api/batches/:id", async (c) => {
679
+ const [batches, notes, script] = await Promise.all([store.read("batches"), store.read("notes"), store.read("script")]);
680
+ const id = c.req.param("id");
681
+ const batch = id === "latest" ? latestBatch(batches) : batches.batches.find((b) => b.id === id);
682
+ if (!batch)
683
+ throw new NotFoundError("batch", id);
684
+ return c.json({
685
+ batch,
686
+ notes: notes.notes.filter((n) => batch.noteIds.includes(n.id)),
687
+ sections: script.sections.filter((s) => batch.sectionIds.includes(s.id)),
688
+ });
689
+ });
690
+ // ---- live updates ----
691
+ app.get("/api/events", (c) => streamSSE(c, async (stream) => {
692
+ const send = (e) => void stream.writeSSE({ event: "change", data: JSON.stringify(e) });
693
+ const corrupt = (e) => void stream.writeSSE({ event: "corrupt", data: JSON.stringify(e) });
694
+ const proxy = (e) => void stream.writeSSE({ event: "proxy", data: JSON.stringify(e) });
695
+ store.on("change", send);
696
+ store.on("corrupt", corrupt);
697
+ store.on("proxy", proxy);
698
+ streams++;
699
+ stream.onAbort(() => {
700
+ streams--;
701
+ store.off("change", send);
702
+ store.off("corrupt", corrupt);
703
+ store.off("proxy", proxy);
704
+ });
705
+ await stream.writeSSE({ event: "hello", data: JSON.stringify({ root: store.root }) });
706
+ while (!stream.aborted)
707
+ await stream.sleep(15000).then(() => stream.writeSSE({ event: "ping", data: "" }));
708
+ }));
709
+ return app;
710
+ }