beatsheet 0.1.0 → 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/src/commands.ts CHANGED
@@ -42,12 +42,12 @@ import {
42
42
  import type { Command, GifFlags } from './args';
43
43
  import { checkDoc } from './server/api';
44
44
  import { startServer, type RunningServer } from './server/server';
45
- import { canonicalPath, discoverProject, errorMessage, projectReloader, videoName, type ProjectContext } from './project';
45
+ import { canonicalPath, describeProject, discoverProject, errorMessage, projectReloader, videoName, type ProjectContext } from './project';
46
46
  import { launchBrowser } from './render/browser';
47
47
  import { captureStills, collectCaptionIssues, collectLayoutIssues, collectReadTimeIssues } from './render/capture';
48
48
  import { sheetArgs, startFfmpeg } from './render/ffmpeg';
49
49
  import { checkTimes, createEventPrinter, openPlayer, renderVideo, stillTimes, transitionStills, type RenderOutput } from './render/render';
50
- import { ASSET_PREFIX, PLAYER_BASE } from './paths';
50
+ import { ASSET_PREFIX, PLAYER_BASE, userCwd } from './paths';
51
51
  import { svgTextWarnings } from './svg-text';
52
52
  import {
53
53
  clipDurations,
@@ -622,7 +622,7 @@ export function validateVideo(json: unknown, doc: VideoDoc, project: ProjectConf
622
622
  export function printCheck(file: string, ctx: { v: LoadedVideo; timeline: ResolvedTimeline | null } | null, r: CheckReport, log: Log): void {
623
623
  log(`check ${file}`);
624
624
  if (ctx) {
625
- log(` project ${ctx.v.project.name} (${ctx.v.project.configPath})`);
625
+ log(` project ${describeProject(ctx.v.project)}`);
626
626
  const rules = rulesSummary(ctx.v.project.config.rules);
627
627
  if (rules) log(` rules ${rules}`);
628
628
  const tl = ctx.timeline;
@@ -699,7 +699,7 @@ export async function runSpeak(cmd: Extract<Command, { cmd: 'speak' }>, log: Log
699
699
  log(` ${c.sceneId.padEnd(width)} would speak ${c.text.length} characters speech/${c.key}.wav "${c.text}"`);
700
700
  }
701
701
  } else if (plan.todo.length > 0) {
702
- const plugins = deps.plugins ?? projectSpeechPlugins(v.project.configPath);
702
+ const plugins = deps.plugins ?? projectSpeechPlugins(v.project.root);
703
703
  const result = await speakVideo(v, opts, {
704
704
  plugins,
705
705
  log,
@@ -745,8 +745,8 @@ function speakSummary(r: SpeakReport, dryRun: boolean): string {
745
745
  // ---------------------------------------------------------------------------
746
746
 
747
747
  /** Starts the studio server and resolves when it is closed (SIGINT/SIGTERM or the returned stop()). */
748
- export async function runStudio(cmd: Extract<Command, { cmd: 'studio' }>, log: Log, cwd = process.cwd()): Promise<RunningServer> {
749
- const project = await discoverProject(cwd);
748
+ export async function runStudio(cmd: Extract<Command, { cmd: 'studio' }>, log: Log, cwd = userCwd()): Promise<RunningServer> {
749
+ const project = await discoverProject(cwd, cwd);
750
750
  // The speech status, speech jobs and the render preflight take beatsheet.config.ts as it is now.
751
751
  const currentProject = projectReloader(project, log);
752
752
  const print = createEventPrinter();
@@ -791,7 +791,7 @@ export async function runStudio(cmd: Extract<Command, { cmd: 'studio' }>, log: L
791
791
  for (const line of loudnessLines(outputs)) log(line);
792
792
  },
793
793
  });
794
- log(`beatsheet studio · ${project.name}`);
794
+ log(`beatsheet studio · ${describeProject(project)}`);
795
795
  log(` studio ${server.url}/`);
796
796
  log(` player ${server.url}${PLAYER_BASE}?video=<file>&format=16:9&mode=studio`);
797
797
  log(` api ${server.url}/api/project`);
@@ -0,0 +1,9 @@
1
+ import { defineProject } from '@beatsheet/core';
2
+ import { builtinScenes, defaultTheme } from '@beatsheet/scenes';
3
+
4
+ /**
5
+ * The project of a folder without beatsheet.config.ts (DEFAULT_CONFIG_PATH): the default theme and
6
+ * the built-in scenes, with that folder as the root. Its name is the folder's (projectContext treats
7
+ * an empty name as none).
8
+ */
9
+ export default defineProject({ name: '', theme: defaultTheme, scenes: builtinScenes });
@@ -0,0 +1,17 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import { CLI_DIR } from './paths';
4
+
5
+ /**
6
+ * The beatsheet packages a project imports that the CLI brings along: a project without its own
7
+ * install gets the CLI's copies. bin/resolve-fallback.mjs (Node) keeps a copy of this pattern.
8
+ */
9
+ export const BEATSHEET_PACKAGE = /^@beatsheet\/(core|scenes)(\/|$)/;
10
+
11
+ /** Folders of @beatsheet/core and @beatsheet/scenes as the CLI in `cliDir` resolves them. */
12
+ export function beatsheetPackageDirs(cliDir: string = CLI_DIR): { core: string; scenes: string } {
13
+ const require = createRequire(path.join(cliDir, 'package.json'));
14
+ // Each entry is <package>/src/index.ts, so the package folder is two levels up.
15
+ const dir = (name: string): string => path.dirname(path.dirname(require.resolve(name)));
16
+ return { core: dir('@beatsheet/core'), scenes: dir('@beatsheet/scenes') };
17
+ }
package/src/paths.ts CHANGED
@@ -15,3 +15,18 @@ export const ASSET_PREFIX = '/project-assets/';
15
15
 
16
16
  /** URL prefix of the narration clips: /speech/<key>.wav from the videos folder's speech/ (PlayerOptions.speechBase default). */
17
17
  export const SPEECH_PREFIX = '/speech/';
18
+
19
+ /** The config of a folder without beatsheet.config.ts: the default theme and the built-in scenes. */
20
+ export const DEFAULT_CONFIG_PATH: string = path.join(CLI_DIR, 'src', 'default-project.config.ts');
21
+
22
+ /**
23
+ * The folder the user ran the command in. `npx beatsheet` inside a workspace package's subfolder
24
+ * runs with the package root as cwd; npm keeps the original in INIT_CWD, used when it lies below
25
+ * the cwd (an outer `npm run -w <pkg>` sets it above the cwd, where the cwd is right).
26
+ */
27
+ export function userCwd(env: NodeJS.ProcessEnv = process.env, cwd: string = process.cwd()): string {
28
+ const init = env.INIT_CWD;
29
+ if (!init) return cwd;
30
+ const rel = path.relative(cwd, path.resolve(init));
31
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? path.resolve(init) : cwd;
32
+ }
package/src/project.ts CHANGED
@@ -2,15 +2,19 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import type { ProjectConfig } from '@beatsheet/core';
5
+ import { DEFAULT_CONFIG_PATH, userCwd } from './paths';
5
6
 
6
7
  export const CONFIG_FILE = 'beatsheet.config.ts';
7
8
  export const VIDEO_SUFFIX = '.video.json';
8
9
 
9
10
  /** A loaded project: the config plus its folders as absolute paths. */
10
11
  export interface ProjectContext {
12
+ /** beatsheet.config.ts, or DEFAULT_CONFIG_PATH for a folder without one. */
11
13
  configPath: string;
12
- /** Folder of beatsheet.config.ts. */
14
+ /** Folder of beatsheet.config.ts (for the default project: the folder the command ran in). */
13
15
  root: string;
16
+ /** False for the default project (no beatsheet.config.ts: default theme, built-in scenes). */
17
+ configured: boolean;
14
18
  name: string;
15
19
  videosDir: string;
16
20
  assetsDir: string;
@@ -23,9 +27,7 @@ export interface ProjectContext {
23
27
  * .json (or an existing file) starts the search in its folder.
24
28
  */
25
29
  export function findConfig(from: string): string | null {
26
- let dir = path.resolve(from);
27
- const isFile = (fs.existsSync(dir) && fs.statSync(dir).isFile()) || (!fs.existsSync(dir) && /\.[a-z0-9]+$/i.test(dir));
28
- if (isFile) dir = path.dirname(dir);
30
+ let dir = folderOf(from);
29
31
  for (;;) {
30
32
  const candidate = path.join(dir, CONFIG_FILE);
31
33
  if (fs.existsSync(candidate)) return candidate;
@@ -35,12 +37,20 @@ export function findConfig(from: string): string | null {
35
37
  }
36
38
  }
37
39
 
38
- /** Absolute folders of a project config (defaults: videos, assets, out). */
39
- export function projectContext(configPath: string, config: ProjectConfig): ProjectContext {
40
- const root = path.dirname(path.resolve(configPath));
40
+ /** The folder of a path: itself for a folder, its parent for a file (or a missing path that looks like one). */
41
+ function folderOf(fileOrDir: string): string {
42
+ const p = path.resolve(fileOrDir);
43
+ const isFile = (fs.existsSync(p) && fs.statSync(p).isFile()) || (!fs.existsSync(p) && /\.[a-z0-9]+$/i.test(p));
44
+ return isFile ? path.dirname(p) : p;
45
+ }
46
+
47
+ /** Absolute folders of a project config (defaults: videos, assets, out); `root` defaults to the config's folder. */
48
+ export function projectContext(configPath: string, config: ProjectConfig, root: string = path.dirname(path.resolve(configPath))): ProjectContext {
49
+ root = path.resolve(root);
41
50
  return {
42
51
  configPath: path.resolve(configPath),
43
52
  root,
53
+ configured: path.resolve(configPath) !== DEFAULT_CONFIG_PATH,
44
54
  name: typeof config.name === 'string' && config.name ? config.name : path.basename(root),
45
55
  videosDir: path.resolve(root, config.videosDir ?? 'videos'),
46
56
  assetsDir: path.resolve(root, config.assetsDir ?? 'assets'),
@@ -53,8 +63,13 @@ export function projectContext(configPath: string, config: ProjectConfig): Proje
53
63
  * Imports beatsheet.config.ts in Node. The CLI registers tsx in bin/beatsheet.js, so a plain
54
64
  * dynamic import handles TypeScript (Vitest transforms it the same way in tests).
55
65
  */
56
- export async function loadProject(configPath: string): Promise<ProjectContext> {
57
- return projectContext(configPath, await importConfig(configPath));
66
+ export async function loadProject(configPath: string, root?: string): Promise<ProjectContext> {
67
+ return projectContext(configPath, await importConfig(configPath), root);
68
+ }
69
+
70
+ /** 'acme (/p/beatsheet.config.ts)', or for the default project what it is made of. */
71
+ export function describeProject(p: Pick<ProjectContext, 'name' | 'configPath' | 'configured'>): string {
72
+ return p.configured ? `${p.name} (${p.configPath})` : `${p.name} (no ${CONFIG_FILE}: default theme, built-in scenes)`;
58
73
  }
59
74
 
60
75
  /** The default export of beatsheet.config.ts; `version` (a query) makes Node import the file afresh. */
@@ -88,8 +103,11 @@ function mtimeOf(file: string): number | null {
88
103
  * the same import as loadProject with the file's mtime as a query, so only beatsheet.config.ts itself
89
104
  * is evaluated again (what it imports stays cached). A stat per call; an import only after an edit.
90
105
  * Keeps the last config that loaded while the file is missing or does not load (`onError` says why).
106
+ * The default project stays as it is: a beatsheet.config.ts that appears in its root takes a
107
+ * restart (its folders may differ), which `onError` says once.
91
108
  */
92
109
  export function projectReloader(project: ProjectContext, onError?: (message: string) => void): () => Promise<ProjectContext> {
110
+ if (!project.configured) return defaultProjectReloader(project, onError);
93
111
  let current = project;
94
112
  let seen = mtimeOf(project.configPath);
95
113
  let loading: Promise<ProjectContext> | null = null;
@@ -110,13 +128,30 @@ export function projectReloader(project: ProjectContext, onError?: (message: str
110
128
  };
111
129
  }
112
130
 
113
- /** Finds and loads the project for a video file (or the cwd when no file is given). */
114
- export async function discoverProject(fileOrDir: string): Promise<ProjectContext> {
131
+ function defaultProjectReloader(project: ProjectContext, onError?: (message: string) => void): () => Promise<ProjectContext> {
132
+ const configPath = path.join(project.root, CONFIG_FILE);
133
+ let told = false;
134
+ return async (): Promise<ProjectContext> => {
135
+ if (!told && fs.existsSync(configPath)) {
136
+ told = true;
137
+ onError?.(`${configPath} appeared: restart beatsheet to use it (keeping the default theme and built-in scenes until then)`);
138
+ }
139
+ return project;
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Finds and loads the project for a video file (or the cwd when no file is given): the nearest
145
+ * beatsheet.config.ts up the tree, else the default project (default theme, built-in scenes). The
146
+ * default project's root is the parent of a folder named `videos` (the video's folder, or the cwd),
147
+ * so `check` run inside videos/ finds ../assets and `render` writes ../out; else `fallbackRoot`.
148
+ * Writes nothing.
149
+ */
150
+ export async function discoverProject(fileOrDir: string, fallbackRoot: string = userCwd()): Promise<ProjectContext> {
115
151
  const configPath = findConfig(fileOrDir);
116
- if (!configPath) {
117
- throw new Error(`No ${CONFIG_FILE} found in ${path.resolve(fileOrDir)} or any parent folder`);
118
- }
119
- return loadProject(configPath);
152
+ if (configPath) return loadProject(configPath);
153
+ const dir = folderOf(fileOrDir);
154
+ return loadProject(DEFAULT_CONFIG_PATH, path.basename(dir) === 'videos' ? path.dirname(dir) : fallbackRoot);
120
155
  }
121
156
 
122
157
  /**
@@ -1,7 +1,10 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
2
4
  import os from 'node:os';
3
5
  import path from 'node:path';
4
6
  import { chromium, type Browser } from 'playwright';
7
+ import { CLI_DIR } from '../paths';
5
8
 
6
9
  /** Playwright's browser cache folder. */
7
10
  export function playwrightCacheDir(): string {
@@ -60,7 +63,26 @@ export const CHROMIUM_ARGS = [
60
63
  '--autoplay-policy=no-user-gesture-required',
61
64
  ];
62
65
 
63
- export const INSTALL_HINT = 'run `npx playwright install chromium-headless-shell` (or set BEATSHEET_CHROMIUM to a Chromium binary)';
66
+ /**
67
+ * The playwright-core the CLI launches with: found through playwright (its dependency), not through
68
+ * hoisting, so a strict pnpm install finds it too.
69
+ */
70
+ export function playwrightCore(): { dir: string; version: string } {
71
+ const playwrightPkg = createRequire(path.join(CLI_DIR, 'package.json')).resolve('playwright/package.json');
72
+ const pkg = createRequire(playwrightPkg).resolve('playwright-core/package.json');
73
+ return { dir: path.dirname(pkg), version: (JSON.parse(fs.readFileSync(pkg, 'utf8')) as { version: string }).version };
74
+ }
75
+
76
+ function pinnedPlaywright(): string {
77
+ try {
78
+ return `playwright@${playwrightCore().version}`;
79
+ } catch {
80
+ return 'playwright';
81
+ }
82
+ }
83
+
84
+ /** Pinned to the CLI's playwright-core: a newer playwright may download a headless shell this one does not launch. */
85
+ export const INSTALL_HINT = `run \`npx -y ${pinnedPlaywright()} install chromium-headless-shell\` (or set BEATSHEET_CHROMIUM to a Chromium binary)`;
64
86
 
65
87
  /** True for Playwright's "browser is not installed" launch error. */
66
88
  export function isMissingBrowser(err: unknown): boolean {
@@ -68,22 +90,67 @@ export function isMissingBrowser(err: unknown): boolean {
68
90
  return /Executable doesn't exist|playwright install|browserType\.launch: .*not found/i.test(msg);
69
91
  }
70
92
 
93
+ /** What launchBrowser runs; tests stub these. Defaults: Playwright's chromium, the Playwright cache, installChromium, stderr, process.env. */
94
+ export interface LaunchDeps {
95
+ launch?: (executablePath?: string) => Promise<Browser>;
96
+ cachedBuild?: () => string | null;
97
+ install?: (log: (line: string) => void) => Promise<void>;
98
+ log?: (line: string) => void;
99
+ env?: NodeJS.ProcessEnv;
100
+ }
101
+
102
+ /**
103
+ * Node arguments that run playwright-core's cli.js `install chromium-headless-shell` with
104
+ * process.argv[1] = 'beatsheet': Playwright prints an "install your project's dependencies first"
105
+ * box when argv[1] (the script path) lies in the npx cache (`_npx`), which is where the CLI's own
106
+ * playwright-core lies under `npx beatsheet`. Its command parser reads argv.slice(2) either way.
107
+ */
108
+ export function chromiumInstallArgs(cli: string): string[] {
109
+ return ['-e', `require(${JSON.stringify(cli)})`, 'beatsheet', 'install', 'chromium-headless-shell'];
110
+ }
111
+
112
+ /**
113
+ * Downloads Playwright's chromium-headless-shell into the Playwright cache with the playwright-core
114
+ * the CLI launches with, so the build matches. The download's progress goes to stderr (a TTY stays
115
+ * one, so the progress bar renders).
116
+ */
117
+ export async function installChromium(log: (line: string) => void): Promise<void> {
118
+ log('Chromium is not installed yet: downloading it once (about 100 MB) …');
119
+ const cli = path.join(playwrightCore().dir, 'cli.js');
120
+ return new Promise((resolve, reject) => {
121
+ const child = spawn(process.execPath, chromiumInstallArgs(cli), { stdio: ['ignore', 2, 2] });
122
+ child.on('error', reject);
123
+ child.on('exit', (code, signal) => {
124
+ if (code === 0) resolve();
125
+ else reject(new Error(`playwright install chromium-headless-shell exited with ${signal ?? `code ${code}`}`));
126
+ });
127
+ });
128
+ }
129
+
130
+ /** The install per installer in this process, shared by concurrent launches; a failed one is forgotten, so a later launch tries again. */
131
+ const installs = new WeakMap<(log: (line: string) => void) => Promise<void>, Promise<void>>();
132
+
71
133
  /**
72
134
  * Launch order: $BEATSHEET_CHROMIUM if set; else Playwright's default browser; if that build is
73
135
  * not installed, the newest cached chromium_headless_shell build (respects PLAYWRIGHT_BROWSERS_PATH);
74
- * else an error with an install hint. Never downloads a browser.
136
+ * else, unless BEATSHEET_NO_DOWNLOAD is set, download Chromium once and launch again; else an
137
+ * error with an install hint.
75
138
  */
76
- export async function launchBrowser(): Promise<Browser> {
77
- const launch = (executablePath?: string): Promise<Browser> => chromium.launch({ executablePath, headless: true, args: CHROMIUM_ARGS });
78
- const fail = (what: string, err: unknown): Error =>
79
- new Error(`Could not launch Chromium (${what}): ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`);
139
+ export async function launchBrowser(deps: LaunchDeps = {}): Promise<Browser> {
140
+ const launch = deps.launch ?? ((executablePath?: string): Promise<Browser> => chromium.launch({ executablePath, headless: true, args: CHROMIUM_ARGS }));
141
+ const cachedBuild = deps.cachedBuild ?? ((): string | null => findChromium() ?? null);
142
+ const install = deps.install ?? installChromium;
143
+ const log = deps.log ?? ((line: string): void => console.error(line));
144
+ const env = deps.env ?? process.env;
145
+ const firstLine = (err: unknown): string => (err instanceof Error ? err.message.split('\n')[0] : String(err));
146
+ const fail = (what: string, err: unknown): Error => new Error(`Could not launch Chromium (${what}): ${firstLine(err)}`);
80
147
 
81
- const env = process.env.BEATSHEET_CHROMIUM;
82
- if (env) {
148
+ const custom = env.BEATSHEET_CHROMIUM;
149
+ if (custom) {
83
150
  try {
84
- return await launch(env);
151
+ return await launch(custom);
85
152
  } catch (err) {
86
- throw fail(`BEATSHEET_CHROMIUM=${env}`, err);
153
+ throw fail(`BEATSHEET_CHROMIUM=${custom}`, err);
87
154
  }
88
155
  }
89
156
  try {
@@ -91,11 +158,28 @@ export async function launchBrowser(): Promise<Browser> {
91
158
  } catch (err) {
92
159
  if (!isMissingBrowser(err)) throw fail("Playwright's default browser", err);
93
160
  }
94
- const cached = findChromium();
95
- if (!cached) throw new Error(`Playwright's Chromium is not installed and no cached chromium_headless_shell build was found in ${playwrightCacheDir()}; ${INSTALL_HINT}`);
161
+ const cached = cachedBuild();
162
+ if (cached) {
163
+ try {
164
+ return await launch(cached);
165
+ } catch (err) {
166
+ throw fail(`cached ${cached}`, err);
167
+ }
168
+ }
169
+ if (env.BEATSHEET_NO_DOWNLOAD) {
170
+ throw new Error(`Playwright's Chromium is not installed and no cached chromium_headless_shell build was found in ${playwrightCacheDir()}; ${INSTALL_HINT}`);
171
+ }
172
+ let pending = installs.get(install);
96
173
  try {
97
- return await launch(cached);
174
+ if (!pending) installs.set(install, (pending = install(log)));
175
+ await pending;
176
+ } catch (err) {
177
+ if (installs.get(install) === pending) installs.delete(install);
178
+ throw new Error(`Could not download Chromium: ${firstLine(err)}; ${INSTALL_HINT}`);
179
+ }
180
+ try {
181
+ return await launch();
98
182
  } catch (err) {
99
- throw fail(`cached ${cached}`, err);
183
+ throw new Error(`Could not launch Chromium after downloading it: ${firstLine(err)}; ${INSTALL_HINT}`);
100
184
  }
101
185
  }
package/src/samples.ts CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  } from '@beatsheet/core';
25
25
  import type { Command } from './args';
26
26
  import { CheckFailed, clearStills, formatPath, validateVideo, videoServer, type Log, type StillsResult } from './commands';
27
- import { discoverProject, type ProjectContext } from './project';
27
+ import { describeProject, discoverProject, type ProjectContext } from './project';
28
28
  import { checkDoc } from './server/api';
29
29
  import { launchBrowser } from './render/browser';
30
30
  import type { RunningServer } from './server/server';
@@ -63,7 +63,7 @@ export interface SamplesVideo {
63
63
 
64
64
  /** Builds samplesDoc(project) for the project at `cwd` and writes it to a temp folder. */
65
65
  export async function loadSamples(sel: SampleSelection, cwd: string = process.cwd()): Promise<SamplesVideo> {
66
- const project = await discoverProject(cwd);
66
+ const project = await discoverProject(cwd, cwd);
67
67
  const config = project.config;
68
68
  const known = config.scenes.map((t) => t.id);
69
69
  const unknownTypes = (sel.types ?? []).filter((t) => !known.includes(t));
@@ -242,7 +242,7 @@ export async function runCheckSamples(
242
242
  moments,
243
243
  seconds: (Date.now() - started) / 1000,
244
244
  };
245
- for (const line of formatSamplesCheck(report, s.project.configPath)) log(line);
245
+ for (const line of formatSamplesCheck(report, describeProject(s.project))) log(line);
246
246
  return report;
247
247
  } finally {
248
248
  await s.dispose();
@@ -367,12 +367,12 @@ export function formatSampleValidationIssue(v: SampleValidationIssue): string {
367
367
  return v.sample ? `${sampleLabel(v.sample)} ${v.where} ${v.message}` : `${v.where} ${v.message}`;
368
368
  }
369
369
 
370
- /** The report lines: header, layout issues, errors, warnings, a per-type summary, the verdict. */
371
- export function formatSamplesCheck(r: SamplesCheckReport, configPath?: string): string[] {
370
+ /** The report lines: header (`project`: describeProject, else the report's name), layout issues, errors, warnings, a per-type summary, the verdict. */
371
+ export function formatSamplesCheck(r: SamplesCheckReport, project?: string): string[] {
372
372
  const out: string[] = [];
373
373
  const types = [...new Set(r.samples.map((s) => s.typeId))];
374
374
  const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`;
375
- out.push(`check --samples · ${r.project}${configPath ? ` (${configPath})` : ''}`);
375
+ out.push(`check --samples · ${project ?? r.project}`);
376
376
  out.push(` ${plural(r.samples.length, 'sample')} of ${plural(types.length, 'scene type')} · ${r.formats.join(', ')} · ${r.moments} moments per format`);
377
377
 
378
378
  const errors = r.validation.filter((v) => v.severity === 'error');
package/src/server/api.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { constants as fsConstants, cpSync } from 'node:fs';
2
3
  import fs from 'node:fs/promises';
3
4
  import path from 'node:path';
4
5
  import type { IncomingMessage, ServerResponse } from 'node:http';
@@ -23,7 +24,11 @@ export interface ApiContext {
23
24
  name: string;
24
25
  /** Folder of the *.video.json files; nothing outside it is read or written. */
25
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;
26
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 };
27
32
  /** Absent: POST /api/render answers 501. */
28
33
  jobs?: RenderJobs;
29
34
  /** Voice-over (/api/speech/*); absent: 501. */
@@ -58,6 +63,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, ctx:
58
63
  else await putVideo(req, res, onDisk);
59
64
  } else if (parts.length === 2 && parts[1] === 'videos' && method === 'POST') {
60
65
  await postVideo(req, res, ctx);
66
+ } else if (parts.length === 2 && parts[1] === 'library-tour' && method === 'POST') {
67
+ await postLibraryTour(res, ctx);
61
68
  } else if (parts.length === 2 && parts[1] === 'render' && method === 'POST') {
62
69
  await postRender(req, res, ctx);
63
70
  } else if (parts.length === 3 && parts[1] === 'render' && parts[2] === 'jobs' && method === 'GET') {
@@ -236,6 +243,30 @@ async function postVideo(req: IncomingMessage, res: ServerResponse, ctx: ApiCont
236
243
  sendJson(res, 200, { ok: true, etag }, { ETag: etag });
237
244
  }
238
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
+
239
270
  async function postRender(req: IncomingMessage, res: ServerResponse, ctx: ApiContext): Promise<void> {
240
271
  if (!ctx.jobs) return sendJson(res, 501, { ok: false, issues: [issue('Rendering is not available on this server')] });
241
272
  const body = await readJson(req);
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import type { ViteDevServer } from 'vite';
6
6
  import { ASSET_PREFIX, PLAYER_BASE, SPEECH_PREFIX } from '../paths';
7
7
  import { projectReloader, type ProjectContext } from '../project';
8
+ import { libraryTourSource } from '../skill';
8
9
  import { projectSpeechPlugins, speakVideo, SPEECH_DIR, SPEECH_FILE, type SpeechPlugins } from '../speech';
9
10
  import { checkDoc, handleApi, type ApiContext } from './api';
10
11
  import { RenderJobs, SpeechJobs, type RenderRunner, type SpeechRunner } from './jobs';
@@ -42,6 +43,8 @@ export interface ServerOptions {
42
43
  currentProject?: () => Promise<ProjectContext>;
43
44
  /** Lines about speech jobs (the studio prints them). */
44
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;
45
48
  }
46
49
 
47
50
  export interface RunningServer {
@@ -59,13 +62,15 @@ export async function startServer(o: ServerOptions): Promise<RunningServer> {
59
62
  let baseUrl = '';
60
63
  const jobs = o.mode === 'studio' && o.renderRunner ? new RenderJobs((file, formats, emit, opts) => o.renderRunner!(baseUrl)(file, formats, emit, opts)) : undefined;
61
64
  const videosDir = o.videosDir ?? o.project.videosDir;
62
- const speechPlugins = o.speechPlugins ?? projectSpeechPlugins(o.project.configPath);
65
+ const speechPlugins = o.speechPlugins ?? projectSpeechPlugins(o.project.root);
63
66
  const currentProject = o.currentProject ?? projectReloader(o.project, (message) => o.log?.(message));
64
67
  const speechJobs = new SpeechJobs(speechRunner(currentProject, videosDir, speechPlugins, o.log));
65
68
  const api: ApiContext = {
66
69
  name: o.project.name,
67
70
  videosDir,
71
+ assetsDir: o.project.assetsDir,
68
72
  outDir: o.project.outDir,
73
+ libraryTour: (o.libraryTour === undefined ? libraryTourSource() : o.libraryTour) ?? undefined,
69
74
  jobs,
70
75
  speech: { project: currentProject, plugins: speechPlugins, jobs: speechJobs },
71
76
  };
@@ -124,6 +129,8 @@ export async function startServer(o: ServerOptions): Promise<RunningServer> {
124
129
  if (!o.noVite) {
125
130
  vite = await createPlayerVite({
126
131
  configPath: o.project.configPath,
132
+ root: o.project.root,
133
+ name: o.project.name,
127
134
  httpServer: o.mode === 'studio' ? server : null,
128
135
  logLevel: o.mode === 'studio' ? 'info' : 'warn',
129
136
  });
@@ -1,13 +1,17 @@
1
1
  import path from 'node:path';
2
2
  import type { Server } from 'node:http';
3
3
  import { createServer, normalizePath, searchForWorkspaceRoot, type Plugin, type ViteDevServer, type LogLevel } from 'vite';
4
+ import { BEATSHEET_PACKAGE, beatsheetPackageDirs } from '../packages';
4
5
  import { CLI_DIR, PLAYER_BASE, PLAYER_DIR } from '../paths';
5
6
 
6
7
  export const PROJECT_MODULE_ID = 'virtual:beatsheet/project';
7
8
  const RESOLVED_PROJECT_ID = '\0' + PROJECT_MODULE_ID;
8
9
 
9
- /** Provides `virtual:beatsheet/project`, re-exporting the default export of beatsheet.config.ts. */
10
- export function beatsheetProjectPlugin(configPath: string): Plugin {
10
+ /**
11
+ * Provides `virtual:beatsheet/project`, re-exporting the default export of beatsheet.config.ts. With
12
+ * `name` (ProjectContext.name), a config without a name (the default project) gets that one.
13
+ */
14
+ export function beatsheetProjectPlugin(configPath: string, name?: string): Plugin {
11
15
  const target = normalizePath(path.resolve(configPath));
12
16
  return {
13
17
  name: 'beatsheet:project',
@@ -16,7 +20,24 @@ export function beatsheetProjectPlugin(configPath: string): Plugin {
16
20
  },
17
21
  load(id: string): string | undefined {
18
22
  if (id !== RESOLVED_PROJECT_ID) return undefined;
19
- return `import project from ${JSON.stringify(target)};\nexport default project;\n`;
23
+ const project = name ? `{ ...project, name: project.name || ${JSON.stringify(name)} }` : 'project';
24
+ return `import project from ${JSON.stringify(target)};\nexport default ${project};\n`;
25
+ },
26
+ };
27
+ }
28
+
29
+ /**
30
+ * A project without its own install imports @beatsheet/core and @beatsheet/scenes from the CLI's
31
+ * copies (bin/register-fallback.mjs does the same in Node). Its own install still wins.
32
+ */
33
+ export function beatsheetPackagesFallback(cliDir: string = CLI_DIR): Plugin {
34
+ const cliImporter = path.join(cliDir, 'package.json');
35
+ return {
36
+ name: 'beatsheet:packages-fallback',
37
+ async resolveId(id, importer, options) {
38
+ if (!BEATSHEET_PACKAGE.test(id)) return null;
39
+ const own = await this.resolve(id, importer, { ...options, skipSelf: true });
40
+ return own ?? this.resolve(id, cliImporter, { ...options, skipSelf: true });
20
41
  },
21
42
  };
22
43
  }
@@ -36,6 +57,10 @@ export function stripViteClient(): Plugin {
36
57
 
37
58
  export interface PlayerViteOptions {
38
59
  configPath: string;
60
+ /** Project root (ProjectContext.root): Vite may serve files below it. */
61
+ root: string;
62
+ /** Project name (ProjectContext.name): the player's name for a config without one. */
63
+ name?: string;
39
64
  /** HTTP server for the HMR websocket; null disables HMR (render commands). */
40
65
  httpServer: Server | null;
41
66
  logLevel?: LogLevel;
@@ -43,9 +68,12 @@ export interface PlayerViteOptions {
43
68
 
44
69
  /** Vite in middleware mode serving the player page under /player/. */
45
70
  export async function createPlayerVite(o: PlayerViteOptions): Promise<ViteDevServer> {
46
- const projectRoot = path.dirname(path.resolve(o.configPath));
71
+ const projectRoot = path.resolve(o.root);
47
72
  const hmr = o.httpServer !== null;
48
- const allow = [...new Set([PLAYER_DIR, projectRoot, searchForWorkspaceRoot(projectRoot), searchForWorkspaceRoot(CLI_DIR)])];
73
+ const packages = beatsheetPackageDirs();
74
+ const allow = [
75
+ ...new Set([PLAYER_DIR, projectRoot, searchForWorkspaceRoot(projectRoot), searchForWorkspaceRoot(CLI_DIR), packages.core, packages.scenes]),
76
+ ];
49
77
  return createServer({
50
78
  configFile: false,
51
79
  envDir: false,
@@ -55,7 +83,7 @@ export async function createPlayerVite(o: PlayerViteOptions): Promise<ViteDevSer
55
83
  logLevel: o.logLevel ?? 'warn',
56
84
  clearScreen: false,
57
85
  cacheDir: path.join(CLI_DIR, 'node_modules', hmr ? '.vite-player-studio' : '.vite-player-render'),
58
- plugins: [beatsheetProjectPlugin(o.configPath), ...(hmr ? [] : [stripViteClient()])],
86
+ plugins: [beatsheetProjectPlugin(o.configPath, o.name), beatsheetPackagesFallback(), ...(hmr ? [] : [stripViteClient()])],
59
87
  server: {
60
88
  middlewareMode: true,
61
89
  hmr: hmr && o.httpServer ? { server: o.httpServer } : false,